Skip to main content

brep_app/ui_kit/
tabs.rs

1//! Tabs: workbench and panel tabs with a sliding accent underline, and
2//! document tabs as pills joined to the content below. Tabs never squash or
3//! wrap: the ones that do not fit go into a chevron menu.
4use super::{paint, surface, Show};
5use crate::theme::{radius, space, Text, Theme, RING};
6use eframe::egui::{self, Color32, Rect, Stroke, Vec2};
7
8const CHEVRON_W: f32 = 28.0;
9
10/// Which of `widths` are drawn in `available` points: as many as fit from the
11/// left, always including `selected`, leaving room for the overflow chevron
12/// when anything is hidden. Returns the visible indices in order.
13pub(crate) fn visible_tabs(widths: &[f32], available: f32, selected: usize) -> Vec<usize> {
14    if widths.iter().sum::<f32>() <= available {
15        return (0..widths.len()).collect();
16    }
17    let mut room = (available - CHEVRON_W - widths.get(selected).copied().unwrap_or(0.0)).max(0.0);
18    let mut out = Vec::new();
19    for (i, w) in widths.iter().enumerate() {
20        if i == selected {
21            out.push(i);
22        } else if *w <= room {
23            room -= w;
24            out.push(i);
25        } else {
26            break;
27        }
28    }
29    if selected < widths.len() && !out.contains(&selected) {
30        out.push(selected);
31    }
32    out
33}
34
35/// What a tab row drew: each visible tab's rect (for hit keys), the overflow
36/// chevron's rect when there is one, and whether the selection changed.
37#[derive(Debug, Clone, Default)]
38pub struct TabBarOutput {
39    pub tabs: Vec<(usize, Rect)>,
40    pub overflow: Option<Rect>,
41    pub changed: bool,
42}
43
44/// Workbench and panel tabs: text on a transparent row; the active tab in
45/// `text.primary` over a 2 px accent underline that slides to the new tab.
46pub fn tab_bar(ui: &mut egui::Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, labels: &[&str], selected: &mut usize) -> TabBarOutput {
47    tab_bar_shown(ui, id_salt, labels, selected, None)
48}
49
50/// [`tab_bar`] with one tab drawn in a fixed state (the gallery).
51pub fn tab_bar_shown(ui: &mut egui::Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, labels: &[&str], selected: &mut usize, shown: Option<(usize, Show)>) -> TabBarOutput {
52    let theme = Theme::of(ui);
53    let c = &theme.colors;
54    let id = ui.make_persistent_id(egui::Id::new(id_salt));
55    let height = theme.control_height() + 6.0;
56    let galleys: Vec<_> = labels.iter().map(|l| paint::galley(ui, l, theme.font(Text::Body))).collect();
57    let widths: Vec<f32> = galleys.iter().map(|g| g.size().x + space::LG * 2.0).collect();
58    let available = ui.available_width();
59    let visible = visible_tabs(&widths, available, *selected);
60    let hidden: Vec<usize> = (0..labels.len()).filter(|i| !visible.contains(i)).collect();
61    let total: f32 = visible.iter().map(|i| widths[*i]).sum::<f32>() + if hidden.is_empty() { 0.0 } else { CHEVRON_W };
62    let (bar, _) = ui.allocate_exact_size(Vec2::new(total, height), egui::Sense::hover());
63    let mut out = TabBarOutput::default();
64    ui.painter().hline(bar.x_range(), bar.bottom() - 0.5, Stroke::new(1.0, c.border_subtle));
65    let mut x = bar.left();
66    let mut underline = None;
67    for i in visible {
68        let rect = Rect::from_min_size(egui::pos2(x, bar.top()), Vec2::new(widths[i], height));
69        x += widths[i];
70        let response = ui.interact(rect, id.with(i), egui::Sense::click());
71        response.widget_info(|| {
72            let mut info = egui::WidgetInfo::labeled(egui::WidgetType::SelectableLabel, true, labels[i]);
73            info.selected = Some(i == *selected);
74            info
75        });
76        if response.clicked() && *selected != i {
77            *selected = i;
78            out.changed = true;
79        }
80        let forced = shown.filter(|(tab, _)| *tab == i).map(|(_, show)| show).unwrap_or_default();
81        let hovered = response.hovered() || matches!(forced, Show::Hover | Show::Pressed);
82        let hover = ui.ctx().animate_bool_with_time(id.with((i, "hover")), hovered, theme.motion_fast());
83        if hover > 0.0 {
84            let overlay = if response.is_pointer_button_down_on() || forced == Show::Pressed { c.pressed } else { c.hover };
85            ui.painter().rect_filled(rect.shrink2(Vec2::new(2.0, 3.0)), radius::BUTTON, paint::lerp_color(Color32::TRANSPARENT, overlay, hover));
86        }
87        if response.has_focus() || forced == Show::Focus {
88            paint::focus_ring(ui, rect.shrink2(Vec2::new(3.0, 4.0)), radius::BUTTON, &theme);
89        }
90        let ink = if i == *selected { c.text_primary } else { c.text_secondary };
91        let g = galleys[i].clone();
92        ui.painter().galley(rect.center() - g.size() / 2.0, g, ink);
93        if i == *selected {
94            underline = Some((rect.left() + space::MD, rect.width() - space::MD * 2.0));
95        }
96        out.tabs.push((i, rect));
97    }
98    if let Some((left, width)) = underline {
99        // The indicator slides: its left edge and width are animated values.
100        let left = ui.ctx().animate_value_with_time(id.with("underline-x"), left, theme.motion_slow());
101        let width = ui.ctx().animate_value_with_time(id.with("underline-w"), width, theme.motion_slow());
102        let line = Rect::from_min_size(egui::pos2(left, bar.bottom() - RING), Vec2::new(width, RING));
103        ui.painter().rect_filled(line, 1.0, c.accent_ring);
104    }
105    if !hidden.is_empty() {
106        let rect = Rect::from_min_size(egui::pos2(x, bar.top()), Vec2::new(CHEVRON_W, height));
107        let response = ui.interact(rect, id.with("overflow"), egui::Sense::click());
108        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "More tabs"));
109        if response.hovered() {
110            ui.painter().rect_filled(rect.shrink2(Vec2::new(2.0, 3.0)), radius::BUTTON, c.hover);
111        }
112        paint::chevron(ui.painter(), rect.center(), 4.0, 0.0, Stroke::new(1.5, c.text_secondary));
113        out.overflow = Some(rect);
114        let mut pick = None;
115        egui::Popup::menu(&response).frame(surface::popup_frame(&theme)).show(|ui| {
116            super::themed(ui, theme.clone(), |ui| {
117                for i in &hidden {
118                    if surface::menu_row(ui, labels[*i], None, false).clicked() {
119                        pick = Some(*i);
120                    }
121                }
122            });
123        });
124        if let Some(i) = pick {
125            *selected = i;
126            out.changed = true;
127        }
128    }
129    out
130}
131
132/// One open document.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct DocumentTab<'a> {
135    pub name: &'a str,
136    /// Unsaved changes: a dot before the name.
137    pub dirty: bool,
138}
139
140#[derive(Debug, Clone, Default)]
141pub struct DocumentTabsOutput {
142    pub activated: Option<usize>,
143    pub closed: Option<usize>,
144    /// Each tab's rect and its close button's rect (when drawn).
145    pub tabs: Vec<(usize, Rect, Option<Rect>)>,
146}
147
148/// Document tabs: pills on `bg.app`; the active one on `bg.panel`, joined to
149/// the content below. The close × shows on hover and always on the active tab.
150pub fn document_tabs(ui: &mut egui::Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, tabs: &[DocumentTab<'_>], active: usize) -> DocumentTabsOutput {
151    let theme = Theme::of(ui);
152    let c = &theme.colors;
153    let id = ui.make_persistent_id(egui::Id::new(id_salt));
154    let height = theme.control_height() + 6.0;
155    let mut out = DocumentTabsOutput::default();
156    let strip_width = ui.available_width();
157    let (strip, _) = ui.allocate_exact_size(Vec2::new(strip_width, height + 4.0), egui::Sense::hover());
158    ui.painter().rect_filled(strip, 0.0, c.bg_app);
159    ui.painter().hline(strip.x_range(), strip.bottom() - 0.5, Stroke::new(1.0, c.border_subtle));
160    let mut x = strip.left() + space::XS;
161    for (i, tab) in tabs.iter().enumerate() {
162        let g = paint::galley(ui, tab.name, theme.font(Text::Body));
163        let dot = if tab.dirty { 6.0 + space::SM } else { 0.0 };
164        let width = space::LG + dot + g.size().x + space::SM + 16.0 + space::SM;
165        let rect = Rect::from_min_size(egui::pos2(x, strip.top() + 4.0), Vec2::new(width, height));
166        if rect.right() > strip.right() {
167            break;
168        }
169        x += width + 2.0;
170        let close = Rect::from_center_size(egui::pos2(rect.right() - space::SM - 8.0, rect.center().y), Vec2::splat(16.0));
171        let response = ui.interact(rect, id.with(i), egui::Sense::click());
172        response.widget_info(|| {
173            let mut info = egui::WidgetInfo::labeled(egui::WidgetType::SelectableLabel, true, tab.name);
174            info.selected = Some(i == active);
175            info
176        });
177        let is_active = i == active;
178        let hovered = response.hovered() || ui.rect_contains_pointer(rect);
179        let top = egui::CornerRadius { nw: radius::BUTTON as u8, ne: radius::BUTTON as u8, sw: 0, se: 0 };
180        if is_active {
181            // Joined to the content: panel fill, a border on three sides, none below.
182            ui.painter().rect_filled(rect, top, c.bg_panel);
183            let b = Stroke::new(1.0, c.border_subtle);
184            ui.painter().add(egui::Shape::line(
185                vec![rect.left_bottom(), rect.left_top() + Vec2::new(0.0, 4.0), rect.left_top() + Vec2::new(4.0, 0.0), rect.right_top() - Vec2::new(4.0, 0.0), rect.right_top() + Vec2::new(0.0, 4.0), rect.right_bottom()],
186                b,
187            ));
188            ui.painter().hline(rect.shrink2(Vec2::new(1.0, 0.0)).x_range(), strip.bottom() - 0.5, Stroke::new(1.0, c.bg_panel));
189        } else if hovered {
190            ui.painter().rect_filled(rect.shrink2(Vec2::new(0.0, 2.0)), radius::BUTTON, c.hover);
191        }
192        if response.has_focus() {
193            paint::focus_ring(ui, rect.shrink(2.0), radius::BUTTON, &theme);
194        }
195        let mut tx = rect.left() + space::LG;
196        if tab.dirty {
197            ui.painter().circle_filled(egui::pos2(tx + 3.0, rect.center().y), 3.0, c.accent_ring);
198            tx += dot;
199        }
200        ui.painter().galley(egui::pos2(tx, rect.center().y - g.size().y / 2.0), g, if is_active { c.text_primary } else { c.text_secondary });
201        let mut close_rect = None;
202        if is_active || hovered {
203            let close_response = ui.interact(close, id.with((i, "close")), egui::Sense::click());
204            close_response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("Close {}", tab.name)));
205            if close_response.hovered() {
206                ui.painter().rect_filled(close, radius::INPUT, c.pressed);
207            }
208            paint::cross(ui.painter(), close.center(), 3.5, Stroke::new(1.4, if close_response.hovered() { c.text_primary } else { c.text_secondary }));
209            if close_response.clicked() {
210                out.closed = Some(i);
211            }
212            close_rect = Some(close);
213        }
214        if response.clicked() && out.closed.is_none() && !is_active {
215            out.activated = Some(i);
216        }
217        out.tabs.push((i, rect, close_rect));
218    }
219    out
220}