feat(gui): the tab bar spans the window above the sidebar; tabs carry a badge and a name

A tab is the top level (D-78): the sidebar, with its badge, pages and
status, is the company in the tab, so the bar now runs across the whole
window above it. The bar's height (tabs::BAR_H) is taken from the window:
the four sidenav tests that size a window for the sidebar add it, through
that constant, and the smallest window is 400 points plus the bar. The
sidebar below the bar is pixel for pixel the old 1440x920 golden image;
only its shapes hash moved, with the shapes lower by the bar.

Tabs are as wide as badge plus name between a least and a greatest width,
the name elided with the full name in the hover; the one in front is the
lit surface with the accent bar, open at its foot. Room is left before the
close control for a later state mark. The + follows the last tab (at the
right edge, whole, when the tabs scroll), says 'Open a company' on hover,
and lists companies by remembered name with the id beside it; a name is
remembered when a company's books load (company.<id>.name) and titles a
tab before its books load.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 11:41:10 -07:00
1 parent d7358b605b
commit 80a24a6262
17 files changed
+531 -140

No files matched your search

+67 -20
View File
@@ -22,7 +22,8 @@
//! 4. What is kept for next time: the open companies (`open_companies`, //! 4. What is kept for next time: the open companies (`open_companies`,
//! the ids of their books, comma separated) and the one in front //! the ids of their books, comma separated) and the one in front
//! (`active_company`); for each company its page, its report's //! (`active_company`); for each company its page, its report's
//! period, columns and comparison (`company.<id>.…`); and, as //! period, columns and comparison and its name as last known
//! (`company.<id>.…`); and, as
//! before and under the same keys, the scheme and its filter //! before and under the same keys, the scheme and its filter
//! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`, //! (`scheme`, `scheme_filter`, `dark`) and the dock (`dock_open`,
//! `dock_agent`, the front tab's). //! `dock_agent`, the front tab's).
@@ -35,7 +36,7 @@ use crate::company::CompanyView;
use crate::data::Source; use crate::data::Source;
use crate::nav::Route; use crate::nav::Route;
use crate::scheme_menu::SchemeMenu; use crate::scheme_menu::SchemeMenu;
use crate::tabs::{Tab, TabAction, TabBar}; use crate::tabs::{Listed, Tab, TabAction, TabBar};
use crate::theme::{self, pal}; use crate::theme::{self, pal};
use egui::{Frame, RichText, Ui}; use egui::{Frame, RichText, Ui};
use std::collections::HashMap; use std::collections::HashMap;
@@ -73,6 +74,10 @@ pub struct App {
/// What was kept for companies not open now (and for those that are, /// What was kept for companies not open now (and for those that are,
/// as they were last closed), by key. /// as they were last closed), by key.
kept: HashMap<String, String>, kept: HashMap<String, String>,
/// 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<String, String>,
/// The dock's preferences as they were kept, for a dock made while no /// The dock's preferences as they were kept, for a dock made while no
/// tab has one. /// tab has one.
dock_prefs: (Option<String>, Option<String>), dock_prefs: (Option<String>, Option<String>),
@@ -223,6 +228,7 @@ impl App {
root: None, root: None,
today: None, today: None,
kept: HashMap::new(), kept: HashMap::new(),
names: HashMap::new(),
dock_prefs: (None, None), dock_prefs: (None, None),
title: TITLE.to_string(), title: TITLE.to_string(),
welcome: None, welcome: None,
@@ -269,7 +275,7 @@ impl App {
/// The window's title now. /// The window's title now.
pub fn window_title(&self) -> String { pub fn window_title(&self) -> String {
match self.active_view() { match self.active_view() {
Some(v) => format!("{} · {TITLE}", v.title()), Some(v) => format!("{} · {TITLE}", self.title_of(v)),
None => TITLE.to_string(), None => TITLE.to_string(),
} }
} }
@@ -356,6 +362,9 @@ impl App {
return; return;
}; };
for id in list_books(&root) { 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 { for k in crate::company::KEPT_KEYS {
let key = format!("company.{id}.{k}"); let key = format!("company.{id}.{k}");
if let Some(v) = get(&key) { if let Some(v) = get(&key) {
@@ -383,20 +392,55 @@ impl App {
} }
} }
/// The ids of the data root's companies that aren't open. /// The data root's companies that aren't open, with the names last
fn not_open(&self) -> impl Fn() -> Vec<String> + use<> { /// known (reading the ids is all it does).
fn not_open(&self) -> impl Fn() -> Vec<Listed> + use<> {
let root = self.root.clone(); let root = self.root.clone();
let open: Vec<String> = self.views.iter().filter_map(CompanyView::book_id).collect(); let open: Vec<String> = self.views.iter().filter_map(CompanyView::book_id).collect();
let names = self.names.clone();
move || { move || {
root.as_deref() root.as_deref()
.map(list_books) .map(list_books)
.unwrap_or_default() .unwrap_or_default()
.into_iter() .into_iter()
.filter(|id| !open.contains(id)) .filter(|id| !open.contains(id))
.map(|id| Listed {
name: names.get(&id).cloned(),
id,
})
.collect() .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<String> {
self.views.get(i).map(|v| self.title_of(v))
}
/// Do what the tab bar was asked. /// Do what the tab bar was asked.
fn act(&mut self, ctx: &egui::Context, action: TabAction) { fn act(&mut self, ctx: &egui::Context, action: TabAction) {
match action { match action {
@@ -561,30 +605,30 @@ impl eframe::App for App {
for (i, v) in self.views.iter_mut().enumerate() { for (i, v) in self.views.iter_mut().enumerate() {
v.pump(&ctx, i == self.active); v.pump(&ctx, i == self.active);
} }
self.learn_names();
let tabs: Vec<Tab> = self let tabs: Vec<Tab> = self
.views .views
.iter() .iter()
.map(|v| Tab { .map(|v| {
title: v.title(), let title = self.title_of(v);
detail: v.book_id().unwrap_or_else(|| v.title()), Tab {
detail: match v.book_id() {
Some(id) if id != title => format!("{title}\n{id}"),
_ => title.clone(),
},
title,
}
}) })
.collect(); .collect();
let shown = self.active(); let shown = self.active();
let others = self.not_open(); let others = self.not_open();
let mut action = None; // The bar goes across the whole window, above everything of the
// The bar goes where the front view says (beside its sidebar, which // company in front: a tab is the top level (D-78).
// keeps the window's whole height), or across the window when let action = self.tabs.show(ui, &tabs, shown, &others);
// there is no view.
let mut bar = |ui: &mut Ui| {
action = self.tabs.show(ui, &tabs, shown, &others);
};
let active = self.active; let active = self.active;
match self.views.get_mut(active) { match self.views.get_mut(active) {
Some(v) => v.ui(ui, &mut self.schemes, &mut bar), Some(v) => v.ui(ui, &mut self.schemes),
None => { None => self.empty(ui),
bar(ui);
self.empty(ui);
}
} }
if let Some(action) = action { if let Some(action) = action {
self.act(&ctx, action); self.act(&ctx, action);
@@ -634,6 +678,9 @@ impl eframe::App for App {
for (k, v) in &self.kept { for (k, v) in &self.kept {
storage.set_string(k, v.clone()); 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 { for v in &self.views {
if let Some(id) = v.book_id() { if let Some(id) = v.book_id() {
v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val)); v.keep(&mut |k, val| storage.set_string(&format!("company.{id}.{k}"), val));
+18 -25
View File
@@ -34,9 +34,7 @@ use crate::receipts::Receipts;
use crate::scheme_menu::SchemeMenu; use crate::scheme_menu::SchemeMenu;
use crate::schemes; use crate::schemes;
use crate::theme::{self, pal}; use crate::theme::{self, pal};
use egui::{ use egui::{Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, vec2};
Align, CornerRadius, Frame, Key, Layout, Margin, RichText, Sense, Stroke, Ui, UiBuilder, vec2,
};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use std::sync::Arc; use std::sync::Arc;
@@ -191,15 +189,19 @@ impl CompanyView {
.flatten() .flatten()
} }
/// The name the books carry, once they are loaded (and it isn't
/// blank).
pub fn name(&self) -> Option<String> {
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 /// The tab's title: the name the books carry, else the id of the
/// books, else the folder's name. /// books, else the folder's name.
pub fn title(&self) -> String { pub fn title(&self) -> String {
let named = self self.name()
.books
.as_ref()
.map(|b| b.company_name().trim().to_string())
.filter(|n| !n.is_empty());
named
.or_else(|| self.book_id()) .or_else(|| self.book_id())
.or_else(|| { .or_else(|| {
let dir = self.data_dir.as_deref()?; 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 /// The window: the sidebar, the top bar, the dock and the page, with
/// every id in them scoped to this view (INVARIANT 2). /// every id in them scoped to this view (INVARIANT 2).
/// ///
/// `bar` draws the app's tab bar. It goes where the sidebar has already /// The app's tab bar is already across the top of `ui` (`tabs.rs`):
/// taken its column and nothing else has been laid out: along the top /// this window is what is below it, and the sidebar's height is the
/// of the rest of the window, so the sidebar keeps all the height the /// window's less the bar's (`tests/sidenav.rs` adds the bar's height
/// owner's window gives it (`tests/sidenav.rs`), and in a scope of its /// to the windows it sizes).
/// 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) {
pub fn ui(&mut self, ui: &mut Ui, schemes: &mut SchemeMenu, bar: &mut dyn FnMut(&mut Ui)) {
let id = self.id; 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); self.handle_keys(ui);
let compact = ui.available_width() < COMPACT_BELOW; let compact = ui.available_width() < COMPACT_BELOW;
self.sidebar(ui, schemes, compact); 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.topbar(ui);
self.draw_dock(ui); self.draw_dock(ui);
let p = pal(ui.ctx()); let p = pal(ui.ctx());
+4 -3
View File
@@ -22,7 +22,7 @@ mod prefs;
mod receipts; mod receipts;
mod scheme_menu; mod scheme_menu;
mod schemes; mod schemes;
mod tabs; pub mod tabs;
#[cfg(test)] #[cfg(test)]
mod test_support; mod test_support;
mod theme; mod theme;
@@ -140,8 +140,9 @@ pub fn run(
.with_app_id("wanderbooks") .with_app_id("wanderbooks")
.with_inner_size([1440.0, 920.0]) .with_inner_size([1440.0, 920.0])
// Small on purpose: tiling window managers hand out small slots // Small on purpose: tiling window managers hand out small slots
// regardless, and every screen lays itself out to fit. // regardless, and every screen lays itself out to fit. The
.with_min_inner_size([360.0, 400.0]), // 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 // The platform's place for app settings, never the books' folder
// (prefs.rs). // (prefs.rs).
persistence_path: prefs::prepare(), persistence_path: prefs::prepare(),
+207 -80
View File
@@ -7,6 +7,12 @@
//! points); with no company open there is no sidebar and it runs the whole //! points); with no company open there is no sidebar and it runs the whole
//! width. //! 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 //! ```text
//! GOAL: a person has several companies open at once, each in its own //! GOAL: a person has several companies open at once, each in its own
//! tab, and moves between them, opens and closes them, without //! tab, and moves between them, opens and closes them, without
@@ -16,8 +22,9 @@
//! company is reachable exactly while it has a tab). //! company is reachable exactly while it has a tab).
//! INVARIANTS: //! INVARIANTS:
//! 1. One tab per open company, in the order opened, showing the //! 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 //! company's badge (as the sidebar's header draws it, small) and
//! bar is there with one company open, and with none. //! 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 //! 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 //! bar in the accent colour along its top edge, and "selected" to
//! assistive technology. //! assistive technology.
@@ -25,12 +32,15 @@
//! technology with the company's name; a middle click on a tab //! technology with the company's name; a middle click on a tab
//! closes it as well. //! closes it as well.
//! 4. "+" lists only companies of the data root that are not open //! 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 //! (a company can't be opened twice), by name with the id of the
//! none. //! books beside it (the id alone for a company never opened), and
//! 5. Tabs never overlap or leave the bar: they shrink to a least //! says so when there are none.
//! width, then the strip scrolls, with a step control at each end //! 5. Tabs never overlap or leave the bar: each is as wide as its
//! that is clipped; the tab shown is scrolled into view when it //! content between a least and a greatest width (a longer name is
//! changes. //! 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 //! 6. This only says what was asked (show, close, open); the app does
//! it. //! it.
//! ``` //! ```
@@ -42,13 +52,30 @@ use egui::{
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use std::time::{Duration, Instant}; 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; pub const BAR_H: f32 = 36.0;
/// A tab's widest and least widths (a name is cut with an ellipsis to fit). /// A tab's widest and least widths (a name is cut with an ellipsis to fit).
const TAB_MAX: f32 = 220.0; const TAB_MAX: f32 = 240.0;
const TAB_MIN: f32 = 120.0; const TAB_MIN: f32 = 110.0;
/// The close control's size. /// The close control's size.
const CLOSE: f32 = 20.0; 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 /// How long a reading of the data root's companies is kept while "+" is
/// open. /// open.
const LIST_KEPT: Duration = Duration::from_millis(750); const LIST_KEPT: Duration = Duration::from_millis(750);
@@ -61,6 +88,15 @@ pub struct Tab {
pub detail: String, 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<String>,
}
/// What a person asked of the bar. /// What a person asked of the bar.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum TabAction { pub enum TabAction {
@@ -77,7 +113,7 @@ pub enum TabAction {
#[derive(Default)] #[derive(Default)]
pub struct TabBar { pub struct TabBar {
reveal: bool, reveal: bool,
listed: Option<(Instant, Vec<String>)>, listed: Option<(Instant, Vec<Listed>)>,
} }
impl TabBar { impl TabBar {
@@ -86,15 +122,16 @@ impl TabBar {
self.reveal = true; self.reveal = true;
} }
/// The bar. `shown` is the tab in front, if there is one; `others` /// The bar, across the top of the window. `shown` is the tab in
/// reads the ids of the root's companies that are not open (called /// front, if there is one; `others` reads the companies of the root
/// now and then while "+" is open, never otherwise). /// that are not open (called now and then while "+" is open, never
/// otherwise).
pub fn show( pub fn show(
&mut self, &mut self,
ui: &mut Ui, ui: &mut Ui,
tabs: &[Tab], tabs: &[Tab],
shown: Option<usize>, shown: Option<usize>,
others: &dyn Fn() -> Vec<String>, others: &dyn Fn() -> Vec<Listed>,
) -> Option<TabAction> { ) -> Option<TabAction> {
let p = pal(ui.ctx()); let p = pal(ui.ctx());
let mut action = None; let mut action = None;
@@ -102,19 +139,27 @@ impl TabBar {
egui::Panel::top("company_tabs") egui::Panel::top("company_tabs")
.exact_size(BAR_H) .exact_size(BAR_H)
.resizable(false) .resizable(false)
.frame( .frame(Frame::new().inner_margin(Margin::symmetric(8, 0)))
Frame::new()
.fill(p.sidebar)
.inner_margin(Margin::symmetric(8, 0))
.stroke(Stroke::new(1.0, p.border)),
)
.show(ui, |ui| { .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(); let bar = ui.max_rect();
// The "+" at the right end, always whole; the tabs get the // The line along the bar's foot; the tab in front covers
// rest. // it, and so is one with what is below.
let plus_w = 30.0; let outer = ui.clip_rect();
let strip_w = (ui.available_width() - plus_w - 6.0).max(0.0); 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<f32> = tabs.iter().map(|t| tab_width(ui, t)).collect();
let total: f32 =
widths.iter().sum::<f32>() + 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 strip = egui::Rect::from_min_size(bar.min, vec2(strip_w, bar.height()));
let mut strip_ui = ui.new_child( let mut strip_ui = ui.new_child(
UiBuilder::new() UiBuilder::new()
@@ -122,10 +167,18 @@ impl TabBar {
.layout(Layout::left_to_right(Align::Max)), .layout(Layout::left_to_right(Align::Max)),
); );
strip_ui.set_clip_rect(strip); 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( let plus = egui::Rect::from_min_size(
egui::pos2(strip.right() + 6.0, bar.top()), egui::pos2(strip.right() + PLUS_GAP, bar.top()),
vec2(plus_w, bar.height()), vec2(PLUS_W, bar.height()),
); );
let mut plus_ui = ui.new_child( let mut plus_ui = ui.new_child(
UiBuilder::new() UiBuilder::new()
@@ -143,28 +196,29 @@ impl TabBar {
} }
/// The tabs, scrolling sideways when they don't fit. /// The tabs, scrolling sideways when they don't fit.
#[allow(clippy::too_many_arguments)]
fn strip( fn strip(
&mut self, &mut self,
ui: &mut Ui, ui: &mut Ui,
tabs: &[Tab], tabs: &[Tab],
widths: &[f32],
overflows: bool,
shown: Option<usize>, shown: Option<usize>,
reveal: &mut bool, reveal: &mut bool,
action: &mut Option<TabAction>, action: &mut Option<TabAction>,
) { ) {
let p = pal(ui.ctx()); let p = pal(ui.ctx());
let room = ui.available_width(); 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. // A step control at each end while the tabs overflow.
let step_w = if overflows { 22.0 } else { 0.0 }; 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 area_id = ui.id().with("tab_scroll");
let mut step = 0.0_f32; let mut step = 0.0_f32;
if overflows { if overflows {
let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click()); let (r, resp) = ui.allocate_exact_size(vec2(step_w, 26.0), Sense::click());
step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs"); step_button(ui, r, &resp, icon::CARET_LEFT, "Earlier tabs");
if resp.clicked() { if resp.clicked() {
step = -each; step = -step_by;
} }
} }
let view_w = room - 2.0 * step_w; let view_w = room - 2.0 * step_w;
@@ -178,11 +232,11 @@ impl TabBar {
.max_width(view_w.max(0.0)) .max_width(view_w.max(0.0))
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
.show(ui, |ui| { .show(ui, |ui| {
ui.spacing_mut().item_spacing.x = 2.0; ui.spacing_mut().item_spacing.x = TAB_GAP;
ui.horizontal_top(|ui| { ui.horizontal_top(|ui| {
for (i, tab) in tabs.iter().enumerate() { for (i, tab) in tabs.iter().enumerate() {
let here = shown == Some(i); 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 { if here && *reveal {
r.scroll_to_me(Some(Align::Center)); r.scroll_to_me(Some(Align::Center));
*reveal = false; *reveal = false;
@@ -197,7 +251,7 @@ impl TabBar {
step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs"); step_button(ui, r, &resp, icon::CARET_RIGHT, "Later tabs");
if resp.clicked() { if resp.clicked() {
let mut s = out.state; 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); s.store(ui.ctx(), out.id);
} }
} }
@@ -210,16 +264,16 @@ impl TabBar {
fn plus( fn plus(
&mut self, &mut self,
ui: &mut Ui, ui: &mut Ui,
others: &dyn Fn() -> Vec<String>, others: &dyn Fn() -> Vec<Listed>,
action: &mut Option<TabAction>, action: &mut Option<TabAction>,
) { ) {
let p = pal(ui.ctx()); 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) .frame(false)
.min_size(vec2(28.0, 28.0)); .min_size(vec2(28.0, 28.0));
let (response, open) = let (response, open) =
egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { 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 let stale = self
.listed .listed
.as_ref() .as_ref()
@@ -231,11 +285,11 @@ impl TabBar {
let list = self let list = self
.listed .listed
.as_ref() .as_ref()
.map(|(_, l)| l.as_slice()) .map(|(_, l)| l.clone())
.unwrap_or(&[]); .unwrap_or_default();
if list.is_empty() { if list.is_empty() {
ui.label( ui.label(
RichText::new("Every company here is open.") RichText::new("Every company is already open.")
.font(theme::regular(13.0)) .font(theme::regular(13.0))
.color(p.muted), .color(p.muted),
); );
@@ -245,9 +299,9 @@ impl TabBar {
.font(theme::regular(12.0)) .font(theme::regular(12.0))
.color(p.muted), .color(p.muted),
); );
for id in list { for c in &list {
if ui.button(id).clicked() { if listed_row(ui, c, &p).clicked() {
*action = Some(TabAction::Open(id.clone())); *action = Some(TabAction::Open(c.id.clone()));
ui.close(); ui.close();
} }
} }
@@ -257,13 +311,54 @@ impl TabBar {
if open.is_none() { if open.is_none() {
self.listed = None; self.listed = None;
} }
// Named as it always was for assistive technology; the hover says
// what it does.
response.widget_info(|| { response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Open another company") 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. /// 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) { fn step_button(ui: &Ui, r: egui::Rect, resp: &egui::Response, glyph: &str, label: &'static str) {
let p = pal(ui.ctx()); 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. /// One tab, `width` wide.
fn one_tab( fn one_tab(
ui: &mut Ui, ui: &mut Ui,
@@ -290,12 +401,12 @@ fn one_tab(
p: &theme::Palette, p: &theme::Palette,
action: &mut Option<TabAction>, action: &mut Option<TabAction>,
) -> egui::Response { ) -> 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()); 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 // The tab's own id for its close control: tabs are told apart by
// their place, and two tabs never share one. // their place, and two tabs never share one.
let close_rect = egui::Rect::from_center_size( 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), vec2(CLOSE, CLOSE),
); );
let close = ui.interact(close_rect, resp.id.with("close"), Sense::click()); let close = ui.interact(close_rect, resp.id.with("close"), Sense::click());
@@ -317,47 +428,62 @@ fn one_tab(
sw: 0, sw: 0,
se: 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 { if here {
// A bar along the top edge and the page's own fill: the tab // The lit tab: the page's surface, outlined on its top and
// in front is part of the page below it. // sides, open at the foot where it meets what is below, with a
painter.rect_filled( // bar in the accent colour along its top edge.
egui::Rect::from_min_size(rect.min, vec2(rect.width(), 3.0)), painter.rect_filled(rect, top, p.surface);
CornerRadius { painter.rect_stroke(
nw: 8, rect,
ne: 8, top,
sw: 0, Stroke::new(1.0, p.border),
se: 0, egui::StrokeKind::Inside,
},
p.accent,
); );
painter.rect_filled( painter.rect_filled(
egui::Rect::from_min_max( egui::Rect::from_min_max(
egui::pos2(rect.left(), rect.bottom() - 1.0), egui::pos2(rect.left() + 1.0, rect.bottom() - 1.0),
egui::pos2(rect.right(), rect.bottom() + 1.0), egui::pos2(rect.right() - 1.0, rect.bottom() + 1.0),
), ),
0.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 { let font = if here {
theme::semibold(13.0) theme::semibold(13.0)
} else { } else {
theme::regular(13.0) 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( let mut job = egui::text::LayoutJob::single_section(
tab.title.clone(), 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_width = text_w.max(10.0);
job.wrap.max_rows = 1; job.wrap.max_rows = 1;
@@ -365,10 +491,7 @@ fn one_tab(
job.wrap.overflow_character = Some('…'); job.wrap.overflow_character = Some('…');
let galley = painter.layout_job(job); let galley = painter.layout_job(job);
painter.galley( painter.galley(
egui::pos2( egui::pos2(text_x, rect.center().y - galley.size().y / 2.0 + 1.0),
rect.left() + 14.0,
rect.center().y - galley.size().y / 2.0 + 1.0,
),
galley, galley,
p.text, p.text,
); );
@@ -380,7 +503,11 @@ fn one_tab(
egui::Align2::CENTER_CENTER, egui::Align2::CENTER_CENTER,
icon::X, icon::X,
egui::FontId::proportional(12.0), 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); let resp = resp.on_hover_text(&tab.detail);
@@ -1 +1 @@
b4c03adfe9dc03e6 fb22421d46ed2f8b
+15 -6
View File
@@ -24,6 +24,7 @@ use ledger_core::{AccountType, Currency, Money, Side};
use ledger_gui::books::Books; use ledger_gui::books::Books;
use ledger_gui::nav::{Route, Section}; use ledger_gui::nav::{Route, Section};
use ledger_gui::owner::{Agent, Owner, RestorePlan}; use ledger_gui::owner::{Agent, Owner, RestorePlan};
use ledger_gui::tabs::BAR_H;
use ledger_gui::{App, Source, data}; use ledger_gui::{App, Source, data};
use ledger_store::{DiskCheck, Store}; use ledger_store::{DiskCheck, Store};
use rust_decimal::Decimal; use rust_decimal::Decimal;
@@ -372,7 +373,8 @@ fn grid(scale: f32) {
for side in [Pane::Sidebar, Pane::Rail] { for side in [Pane::Sidebar, Pane::Rail] {
let mut h = f.harness(footer, Route::Projects, side.width(), 920.0, scale); let mut h = f.harness(footer, Route::Projects, side.width(), 920.0, scale);
for px in (300..=920).step_by(20) { 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.set_size(vec2(side.width(), pt));
h.run_steps(4); h.run_steps(4);
let tag = format!("{footer:?} {side:?} {px}px @{scale}"); 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() { fn at_1479x519_every_link_shows_unscrolled() {
let f = Fixture::new(); let f = Fixture::new();
for footer in FOOTERS { 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); let (view, _, scrolls) = drawn(&h, Pane::Sidebar);
assert!(!scrolls, "{footer:?}: the links scroll"); assert!(!scrolls, "{footer:?}: the links scroll");
for s in Section::ALL { for s in Section::ALL {
@@ -546,7 +549,8 @@ fn the_rail_at_519_shows_every_link_unscrolled() {
let f = Fixture::new(); let f = Fixture::new();
for footer in FOOTERS { for footer in FOOTERS {
for route in [Route::Projects, Route::Overview, Route::Journal] { 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 tag = format!("{footer:?} {route:?}");
let (view, _, scrolls) = drawn(&h, Pane::Rail); let (view, _, scrolls) = drawn(&h, Pane::Rail);
assert!(!scrolls, "{tag}: the rail's links scroll"); assert!(!scrolls, "{tag}: the rail's links scroll");
@@ -638,7 +642,9 @@ fn going_somewhere_scrolls_its_link_into_view() {
#[test] #[test]
fn a_tall_sidebar_is_unchanged() { fn a_tall_sidebar_is_unchanged() {
let f = Fixture::new(); 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 dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens");
let shapes = sidebar_shapes(&h); let shapes = sidebar_shapes(&h);
let bless = std::env::var("SIDENAV_BLESS").is_ok(); 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"); let png = dir.join("sidenav-1440x920.png");
match h.render() { match h.render() {
Ok(img) => { 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 { if bless {
side.save(&png).unwrap(); side.save(&png).unwrap();
} else { } else {
@@ -687,7 +695,8 @@ fn a_tall_sidebar_is_unchanged() {
fn sidebar_shapes(h: &Harness<'_, App>) -> u64 { fn sidebar_shapes(h: &Harness<'_, App>) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325; let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for s in &h.output().shapes { 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() { for b in format!("{:?}", s.shape).bytes() {
hash ^= b as u64; hash ^= b as u64;
hash = hash.wrapping_mul(0x100_0000_01b3); hash = hash.wrapping_mul(0x100_0000_01b3);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 32 KiB

+219 -5
View File
@@ -28,6 +28,12 @@
//! sizes and times as they were. //! sizes and times as they were.
//! 8. The tab bar and the empty state look as pictured //! 8. The tab bar and the empty state look as pictured
//! (`tests/snapshots/`). //! (`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; 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. // Beta can be opened again: a new tab, a new lock.
h.get_by_label("Open another company").click(); h.get_by_label("Open another company").click();
h.run_steps(3); h.run_steps(3);
h.get_by_label("beta").click(); h.get_by_label("Beta Co").click();
h.run_steps(3); h.run_steps(3);
assert_eq!(titles(&h).len(), 2); assert_eq!(titles(&h).len(), 2);
until(&mut h, "beta's lock is taken again", |_| { 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. // Every one is open: the list says so.
h.get_by_label("Open another company").click(); h.get_by_label("Open another company").click();
h.run_steps(3); 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. // Opening an open company by other means shows its tab, never a second.
let ctx = h.ctx.clone(); let ctx = h.ctx.clone();
let n = h.state_mut().open(&ctx, w.source("beta")); 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"); close_tab(&mut h, "Alpha Co");
h.get_by_label("Open another company").click(); h.get_by_label("Open another company").click();
h.run_steps(3); h.run_steps(3);
h.get_by_label("alpha").click(); h.get_by_label("Alpha Co").click();
h.run_steps(3); h.run_steps(3);
let last = h.state().views().len() - 1; let last = h.state().views().len() - 1;
assert!(matches!( 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 // Closing the last tab keeps a list with nothing in it, and the next
// start opens the data root's first. // start opens the data root's first.
for _ in 0..3 { for _ in 0..3 {
let name = h.state().views()[0].title(); let name = h.state().tab_title(0).unwrap();
close_tab(&mut h, &name); close_tab(&mut h, &name);
} }
assert!(h.state().views().is_empty()); 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. // The bar is still there, and "+" opens a company from the empty window.
h.get_by_label("Open another company").click(); h.get_by_label("Open another company").click();
h.run_steps(3); h.run_steps(3);
h.get_by_label("beta").click(); h.get_by_label("Beta Co").click();
loaded(&mut h); loaded(&mut h);
assert_eq!(titles(&h), ["Beta Co"]); assert_eq!(titles(&h), ["Beta Co"]);
assert!(!shows(&h, "No company is open")); 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"); 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<egui::Rect> {
fn walk(s: &egui::Shape, size: egui::Vec2, out: &mut Option<egui::Rect>) {
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<String> = (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 ----------------------------- // ---- 7: read-only, in a tab that is not in front -----------------------------
type Tree = BTreeMap<PathBuf, (Vec<u8>, u64, SystemTime)>; type Tree = BTreeMap<PathBuf, (Vec<u8>, u64, SystemTime)>;
@@ -1200,5 +1385,34 @@ fn pictures() {
close_tab(&mut h, "Beta Co"); close_tab(&mut h, "Beta Co");
h.run_steps(4); h.run_steps(4);
save(&mut h, &format!("empty-state-{mode}")); save(&mut h, &format!("empty-state-{mode}"));
// Eight companies open: the tabs scroll, the "+" stays at the edge.
let names: Vec<String> = [
"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}"));
} }
} }