BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Tabs: workbench and panel tabs with a sliding accent underline, and
//! document tabs as pills joined to the content below. Tabs never squash or
//! wrap: the ones that do not fit go into a chevron menu.
use super::{paint, surface, Show};
use crate::theme::{radius, space, Text, Theme, RING};
use eframe::egui::{self, Color32, Rect, Stroke, Vec2};

const CHEVRON_W: f32 = 28.0;

/// Which of `widths` are drawn in `available` points: as many as fit from the
/// left, always including `selected`, leaving room for the overflow chevron
/// when anything is hidden. Returns the visible indices in order.
pub(crate) fn visible_tabs(widths: &[f32], available: f32, selected: usize) -> Vec<usize> {
    if widths.iter().sum::<f32>() <= available {
        return (0..widths.len()).collect();
    }
    let mut room = (available - CHEVRON_W - widths.get(selected).copied().unwrap_or(0.0)).max(0.0);
    let mut out = Vec::new();
    for (i, w) in widths.iter().enumerate() {
        if i == selected {
            out.push(i);
        } else if *w <= room {
            room -= w;
            out.push(i);
        } else {
            break;
        }
    }
    if selected < widths.len() && !out.contains(&selected) {
        out.push(selected);
    }
    out
}

/// What a tab row drew: each visible tab's rect (for hit keys), the overflow
/// chevron's rect when there is one, and whether the selection changed.
#[derive(Debug, Clone, Default)]
pub struct TabBarOutput {
    pub tabs: Vec<(usize, Rect)>,
    pub overflow: Option<Rect>,
    pub changed: bool,
}

/// Workbench and panel tabs: text on a transparent row; the active tab in
/// `text.primary` over a 2 px accent underline that slides to the new tab.
pub fn tab_bar(ui: &mut egui::Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, labels: &[&str], selected: &mut usize) -> TabBarOutput {
    tab_bar_shown(ui, id_salt, labels, selected, None)
}

/// [`tab_bar`] with one tab drawn in a fixed state (the gallery).
pub 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 {
    let theme = Theme::of(ui);
    let c = &theme.colors;
    let id = ui.make_persistent_id(egui::Id::new(id_salt));
    let height = theme.control_height() + 6.0;
    let galleys: Vec<_> = labels.iter().map(|l| paint::galley(ui, l, theme.font(Text::Body))).collect();
    let widths: Vec<f32> = galleys.iter().map(|g| g.size().x + space::LG * 2.0).collect();
    let available = ui.available_width();
    let visible = visible_tabs(&widths, available, *selected);
    let hidden: Vec<usize> = (0..labels.len()).filter(|i| !visible.contains(i)).collect();
    let total: f32 = visible.iter().map(|i| widths[*i]).sum::<f32>() + if hidden.is_empty() { 0.0 } else { CHEVRON_W };
    let (bar, _) = ui.allocate_exact_size(Vec2::new(total, height), egui::Sense::hover());
    let mut out = TabBarOutput::default();
    ui.painter().hline(bar.x_range(), bar.bottom() - 0.5, Stroke::new(1.0, c.border_subtle));
    let mut x = bar.left();
    let mut underline = None;
    for i in visible {
        let rect = Rect::from_min_size(egui::pos2(x, bar.top()), Vec2::new(widths[i], height));
        x += widths[i];
        let response = ui.interact(rect, id.with(i), egui::Sense::click());
        response.widget_info(|| {
            let mut info = egui::WidgetInfo::labeled(egui::WidgetType::SelectableLabel, true, labels[i]);
            info.selected = Some(i == *selected);
            info
        });
        if response.clicked() && *selected != i {
            *selected = i;
            out.changed = true;
        }
        let forced = shown.filter(|(tab, _)| *tab == i).map(|(_, show)| show).unwrap_or_default();
        let hovered = response.hovered() || matches!(forced, Show::Hover | Show::Pressed);
        let hover = ui.ctx().animate_bool_with_time(id.with((i, "hover")), hovered, theme.motion_fast());
        if hover > 0.0 {
            let overlay = if response.is_pointer_button_down_on() || forced == Show::Pressed { c.pressed } else { c.hover };
            ui.painter().rect_filled(rect.shrink2(Vec2::new(2.0, 3.0)), radius::BUTTON, paint::lerp_color(Color32::TRANSPARENT, overlay, hover));
        }
        if response.has_focus() || forced == Show::Focus {
            paint::focus_ring(ui, rect.shrink2(Vec2::new(3.0, 4.0)), radius::BUTTON, &theme);
        }
        let ink = if i == *selected { c.text_primary } else { c.text_secondary };
        let g = galleys[i].clone();
        ui.painter().galley(rect.center() - g.size() / 2.0, g, ink);
        if i == *selected {
            underline = Some((rect.left() + space::MD, rect.width() - space::MD * 2.0));
        }
        out.tabs.push((i, rect));
    }
    if let Some((left, width)) = underline {
        // The indicator slides: its left edge and width are animated values.
        let left = ui.ctx().animate_value_with_time(id.with("underline-x"), left, theme.motion_slow());
        let width = ui.ctx().animate_value_with_time(id.with("underline-w"), width, theme.motion_slow());
        let line = Rect::from_min_size(egui::pos2(left, bar.bottom() - RING), Vec2::new(width, RING));
        ui.painter().rect_filled(line, 1.0, c.accent_ring);
    }
    if !hidden.is_empty() {
        let rect = Rect::from_min_size(egui::pos2(x, bar.top()), Vec2::new(CHEVRON_W, height));
        let response = ui.interact(rect, id.with("overflow"), egui::Sense::click());
        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "More tabs"));
        if response.hovered() {
            ui.painter().rect_filled(rect.shrink2(Vec2::new(2.0, 3.0)), radius::BUTTON, c.hover);
        }
        paint::chevron(ui.painter(), rect.center(), 4.0, 0.0, Stroke::new(1.5, c.text_secondary));
        out.overflow = Some(rect);
        let mut pick = None;
        egui::Popup::menu(&response).frame(surface::popup_frame(&theme)).show(|ui| {
            super::themed(ui, theme.clone(), |ui| {
                for i in &hidden {
                    if surface::menu_row(ui, labels[*i], None, false).clicked() {
                        pick = Some(*i);
                    }
                }
            });
        });
        if let Some(i) = pick {
            *selected = i;
            out.changed = true;
        }
    }
    out
}

/// One open document.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DocumentTab<'a> {
    pub name: &'a str,
    /// Unsaved changes: a dot before the name.
    pub dirty: bool,
}

#[derive(Debug, Clone, Default)]
pub struct DocumentTabsOutput {
    pub activated: Option<usize>,
    pub closed: Option<usize>,
    /// Each tab's rect and its close button's rect (when drawn).
    pub tabs: Vec<(usize, Rect, Option<Rect>)>,
}

/// Document tabs: pills on `bg.app`; the active one on `bg.panel`, joined to
/// the content below. The close × shows on hover and always on the active tab.
pub fn document_tabs(ui: &mut egui::Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, tabs: &[DocumentTab<'_>], active: usize) -> DocumentTabsOutput {
    let theme = Theme::of(ui);
    let c = &theme.colors;
    let id = ui.make_persistent_id(egui::Id::new(id_salt));
    let height = theme.control_height() + 6.0;
    let mut out = DocumentTabsOutput::default();
    let strip_width = ui.available_width();
    let (strip, _) = ui.allocate_exact_size(Vec2::new(strip_width, height + 4.0), egui::Sense::hover());
    ui.painter().rect_filled(strip, 0.0, c.bg_app);
    ui.painter().hline(strip.x_range(), strip.bottom() - 0.5, Stroke::new(1.0, c.border_subtle));
    let mut x = strip.left() + space::XS;
    for (i, tab) in tabs.iter().enumerate() {
        let g = paint::galley(ui, tab.name, theme.font(Text::Body));
        let dot = if tab.dirty { 6.0 + space::SM } else { 0.0 };
        let width = space::LG + dot + g.size().x + space::SM + 16.0 + space::SM;
        let rect = Rect::from_min_size(egui::pos2(x, strip.top() + 4.0), Vec2::new(width, height));
        if rect.right() > strip.right() {
            break;
        }
        x += width + 2.0;
        let close = Rect::from_center_size(egui::pos2(rect.right() - space::SM - 8.0, rect.center().y), Vec2::splat(16.0));
        let response = ui.interact(rect, id.with(i), egui::Sense::click());
        response.widget_info(|| {
            let mut info = egui::WidgetInfo::labeled(egui::WidgetType::SelectableLabel, true, tab.name);
            info.selected = Some(i == active);
            info
        });
        let is_active = i == active;
        let hovered = response.hovered() || ui.rect_contains_pointer(rect);
        let top = egui::CornerRadius { nw: radius::BUTTON as u8, ne: radius::BUTTON as u8, sw: 0, se: 0 };
        if is_active {
            // Joined to the content: panel fill, a border on three sides, none below.
            ui.painter().rect_filled(rect, top, c.bg_panel);
            let b = Stroke::new(1.0, c.border_subtle);
            ui.painter().add(egui::Shape::line(
                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()],
                b,
            ));
            ui.painter().hline(rect.shrink2(Vec2::new(1.0, 0.0)).x_range(), strip.bottom() - 0.5, Stroke::new(1.0, c.bg_panel));
        } else if hovered {
            ui.painter().rect_filled(rect.shrink2(Vec2::new(0.0, 2.0)), radius::BUTTON, c.hover);
        }
        if response.has_focus() {
            paint::focus_ring(ui, rect.shrink(2.0), radius::BUTTON, &theme);
        }
        let mut tx = rect.left() + space::LG;
        if tab.dirty {
            ui.painter().circle_filled(egui::pos2(tx + 3.0, rect.center().y), 3.0, c.accent_ring);
            tx += dot;
        }
        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 });
        let mut close_rect = None;
        if is_active || hovered {
            let close_response = ui.interact(close, id.with((i, "close")), egui::Sense::click());
            close_response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("Close {}", tab.name)));
            if close_response.hovered() {
                ui.painter().rect_filled(close, radius::INPUT, c.pressed);
            }
            paint::cross(ui.painter(), close.center(), 3.5, Stroke::new(1.4, if close_response.hovered() { c.text_primary } else { c.text_secondary }));
            if close_response.clicked() {
                out.closed = Some(i);
            }
            close_rect = Some(close);
        }
        if response.clicked() && out.closed.is_none() && !is_active {
            out.activated = Some(i);
        }
        out.tabs.push((i, rect, close_rect));
    }
    out
}