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
//! The look of a reference-selection field: picked items as chips that wrap,
//! an accent border that pulses while the field is picking, and a collapsed
//! count once there are more than six picks. The picking itself stays in
//! `reference_selection`; this is only how the field is drawn.
use super::paint;
use crate::theme::{radius, space, Text, Theme, BORDER};
use eframe::egui::{self, Rect, Stroke, Vec2};

/// Above this many picks the chips collapse to a count.
pub const COLLAPSE_ABOVE: usize = 6;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Chip<'a> {
    /// The entity type's icon: a glyph of the icon catalog ("" for none).
    pub glyph: &'a str,
    pub name: &'a str,
}

#[must_use = "a reference field does nothing until `show` is called"]
pub struct ReferenceField<'a> {
    id_salt: egui::Id,
    chips: &'a [Chip<'a>],
    /// The plural noun of what is picked: "faces", "edges".
    noun: &'a str,
    picking: bool,
    width: Option<f32>,
}

pub struct ReferenceOutput {
    /// The field itself: a click starts (or ends) the pick.
    pub response: egui::Response,
    /// A chip's × was pressed.
    pub removed: Option<usize>,
    /// The chips drawn: `(index, chip rect, its × rect)`.
    pub chips: Vec<(usize, Rect, Rect)>,
    /// The collapsed count's disclosure rect, when the picks are collapsed or expandable.
    pub disclosure: Option<Rect>,
}

/// `reference_field("faces-field", &chips, "faces").picking(true).show(ui)`.
pub fn reference_field<'a>(id_salt: impl std::hash::Hash + std::fmt::Debug, chips: &'a [Chip<'a>], noun: &'a str) -> ReferenceField<'a> {
    ReferenceField { id_salt: egui::Id::new(id_salt), chips, noun, picking: false, width: None }
}

/// Where each chip of `widths` sits in a field `inner` points wide: the
/// top-left offset of each, wrapping onto further lines, and the height used.
pub(crate) fn flow(widths: &[f32], inner: f32, chip_height: f32, gap: f32) -> (Vec<Vec2>, f32) {
    let (mut x, mut y) = (0.0, 0.0);
    let mut out = Vec::with_capacity(widths.len());
    for w in widths {
        if x > 0.0 && x + w > inner {
            x = 0.0;
            y += chip_height + gap;
        }
        out.push(Vec2::new(x, y));
        x += w + gap;
    }
    (out, y + chip_height)
}

impl<'a> ReferenceField<'a> {
    pub fn picking(mut self, picking: bool) -> Self {
        self.picking = picking;
        self
    }
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }

    pub fn show(self, ui: &mut egui::Ui) -> ReferenceOutput {
        let theme = Theme::of(ui);
        let c = &theme.colors;
        let id = ui.make_persistent_id(self.id_salt);
        let width = self.width.unwrap_or_else(|| ui.available_width().min(320.0));
        let pad = space::XS;
        let chip_h = 20.0;
        let many = self.chips.len() > COLLAPSE_ABOVE;
        let expanded_id = id.with("expanded");
        let mut expanded = ui.data(|d| d.get_temp::<bool>(expanded_id)).unwrap_or(false);
        let collapsed = many && !expanded;
        let font = theme.font(Text::Body);
        let galleys: Vec<_> = if collapsed { Vec::new() } else { self.chips.iter().map(|chip| paint::galley(ui, chip.name, font.clone())).collect() };
        let widths: Vec<f32> = galleys
            .iter()
            .zip(self.chips)
            .map(|(g, chip)| space::SM + if chip.glyph.is_empty() { 0.0 } else { 14.0 + space::XS } + g.size().x + space::XS + 14.0 + space::XS)
            .collect();
        let header_h = if many { chip_h + space::XS } else { 0.0 };
        let (offsets, flow_h) = flow(&widths, width - pad * 2.0, chip_h, space::XS);
        let body_h = if collapsed || self.chips.is_empty() { 0.0 } else { flow_h };
        let height = (pad * 2.0 + header_h + body_h).max(theme.control_height());
        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::click());
        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{} {}", self.chips.len(), self.noun)));

        let border = if self.picking {
            // A subtle pulse while picking: the border breathes between the
            // ring colour and a lighter mix of it. Still under reduce-motion.
            let t = if theme.reduce_motion {
                0.0
            } else {
                ui.ctx().request_repaint();
                ((ui.input(|i| i.time) * 3.0).sin() * 0.5 + 0.5) as f32
            };
            paint::lerp_color(c.accent_ring, crate::theme::mix(c.accent_ring, c.bg_input, 0.45), t)
        } else if response.hovered() {
            crate::theme::mix(c.border_strong, c.text_secondary, 0.35)
        } else {
            c.border_strong
        };
        ui.painter().rect(rect, radius::INPUT, c.bg_input, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
        if self.picking || response.has_focus() {
            paint::focus_ring(ui, rect, radius::INPUT, &theme);
        }
        let mut out = ReferenceOutput { response: response.clone(), removed: None, chips: Vec::new(), disclosure: None };
        let origin = rect.min + Vec2::splat(pad);
        if self.chips.is_empty() {
            let text = if self.picking { format!("Pick {}…", self.noun) } else { format!("No {} picked", self.noun) };
            let g = paint::galley(ui, &text, font);
            ui.painter().galley(egui::pos2(rect.left() + space::MD, rect.center().y - g.size().y / 2.0), g, c.text_disabled);
            return out;
        }
        let mut top = origin.y;
        if many {
            // "12 faces" with a disclosure arrow.
            let text = format!("{} {}", self.chips.len(), self.noun);
            let g = paint::galley(ui, &text, font.clone());
            let row = Rect::from_min_size(origin, Vec2::new(18.0 + g.size().x + space::SM, chip_h));
            let toggle = ui.interact(row, id.with("disclosure"), egui::Sense::click());
            toggle.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::CollapsingHeader, true, &text));
            let open = ui.ctx().animate_bool_with_time(id.with("open"), expanded, theme.motion_base());
            if toggle.hovered() {
                ui.painter().rect_filled(row, radius::INPUT, c.hover);
            }
            paint::disclosure(ui.painter(), egui::pos2(row.left() + 9.0, row.center().y), 3.5, open, Stroke::new(1.5, c.text_secondary));
            ui.painter().galley(egui::pos2(row.left() + 18.0, row.center().y - g.size().y / 2.0), g, c.text_primary);
            if toggle.clicked() {
                expanded = !expanded;
                ui.data_mut(|d| d.insert_temp(expanded_id, expanded));
            }
            out.disclosure = Some(row);
            top += header_h;
        }
        if collapsed {
            return out;
        }
        for (i, ((chip, g), offset)) in self.chips.iter().zip(galleys).zip(offsets).enumerate() {
            let chip_rect = Rect::from_min_size(egui::pos2(origin.x, top) + offset, Vec2::new(widths[i], chip_h));
            ui.painter().rect(chip_rect, chip_h / 2.0, c.bg_raised, Stroke::new(BORDER, c.border_subtle), egui::StrokeKind::Inside);
            let mut x = chip_rect.left() + space::SM;
            if !chip.glyph.is_empty() {
                paint::icon(ui, chip.glyph, Rect::from_min_size(egui::pos2(x, chip_rect.center().y - 7.0), Vec2::splat(14.0)), c.text_secondary);
                x += 14.0 + space::XS;
            }
            let gw = g.size();
            ui.painter().galley(egui::pos2(x, chip_rect.center().y - gw.y / 2.0), g, c.text_primary);
            let close = Rect::from_center_size(egui::pos2(chip_rect.right() - space::XS - 7.0, chip_rect.center().y), Vec2::splat(14.0));
            let remove = ui.interact(close, id.with(("remove", i)), egui::Sense::click());
            remove.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("Remove {}", chip.name)));
            if remove.hovered() {
                ui.painter().circle_filled(close.center(), 7.0, c.pressed);
            }
            paint::cross(ui.painter(), close.center(), 3.0, Stroke::new(1.3, if remove.hovered() { c.text_primary } else { c.text_secondary }));
            if remove.clicked() {
                out.removed = Some(i);
            }
            out.chips.push((i, chip_rect, close));
        }
        out
    }
}