Skip to main content

brep_app/ui_kit/
chips.rs

1//! The look of a reference-selection field: picked items as chips that wrap,
2//! an accent border that pulses while the field is picking, and a collapsed
3//! count once there are more than six picks. The picking itself stays in
4//! `reference_selection`; this is only how the field is drawn.
5use super::paint;
6use crate::theme::{radius, space, Text, Theme, BORDER};
7use eframe::egui::{self, Rect, Stroke, Vec2};
8
9/// Above this many picks the chips collapse to a count.
10pub const COLLAPSE_ABOVE: usize = 6;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Chip<'a> {
14    /// The entity type's icon: a glyph of the icon catalog ("" for none).
15    pub glyph: &'a str,
16    pub name: &'a str,
17}
18
19#[must_use = "a reference field does nothing until `show` is called"]
20pub struct ReferenceField<'a> {
21    id_salt: egui::Id,
22    chips: &'a [Chip<'a>],
23    /// The plural noun of what is picked: "faces", "edges".
24    noun: &'a str,
25    picking: bool,
26    width: Option<f32>,
27}
28
29pub struct ReferenceOutput {
30    /// The field itself: a click starts (or ends) the pick.
31    pub response: egui::Response,
32    /// A chip's × was pressed.
33    pub removed: Option<usize>,
34    /// The chips drawn: `(index, chip rect, its × rect)`.
35    pub chips: Vec<(usize, Rect, Rect)>,
36    /// The collapsed count's disclosure rect, when the picks are collapsed or expandable.
37    pub disclosure: Option<Rect>,
38}
39
40/// `reference_field("faces-field", &chips, "faces").picking(true).show(ui)`.
41pub fn reference_field<'a>(id_salt: impl std::hash::Hash + std::fmt::Debug, chips: &'a [Chip<'a>], noun: &'a str) -> ReferenceField<'a> {
42    ReferenceField { id_salt: egui::Id::new(id_salt), chips, noun, picking: false, width: None }
43}
44
45/// Where each chip of `widths` sits in a field `inner` points wide: the
46/// top-left offset of each, wrapping onto further lines, and the height used.
47pub(crate) fn flow(widths: &[f32], inner: f32, chip_height: f32, gap: f32) -> (Vec<Vec2>, f32) {
48    let (mut x, mut y) = (0.0, 0.0);
49    let mut out = Vec::with_capacity(widths.len());
50    for w in widths {
51        if x > 0.0 && x + w > inner {
52            x = 0.0;
53            y += chip_height + gap;
54        }
55        out.push(Vec2::new(x, y));
56        x += w + gap;
57    }
58    (out, y + chip_height)
59}
60
61impl<'a> ReferenceField<'a> {
62    pub fn picking(mut self, picking: bool) -> Self {
63        self.picking = picking;
64        self
65    }
66    pub fn width(mut self, width: f32) -> Self {
67        self.width = Some(width);
68        self
69    }
70
71    pub fn show(self, ui: &mut egui::Ui) -> ReferenceOutput {
72        let theme = Theme::of(ui);
73        let c = &theme.colors;
74        let id = ui.make_persistent_id(self.id_salt);
75        let width = self.width.unwrap_or_else(|| ui.available_width().min(320.0));
76        let pad = space::XS;
77        let chip_h = 20.0;
78        let many = self.chips.len() > COLLAPSE_ABOVE;
79        let expanded_id = id.with("expanded");
80        let mut expanded = ui.data(|d| d.get_temp::<bool>(expanded_id)).unwrap_or(false);
81        let collapsed = many && !expanded;
82        let font = theme.font(Text::Body);
83        let galleys: Vec<_> = if collapsed { Vec::new() } else { self.chips.iter().map(|chip| paint::galley(ui, chip.name, font.clone())).collect() };
84        let widths: Vec<f32> = galleys
85            .iter()
86            .zip(self.chips)
87            .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)
88            .collect();
89        let header_h = if many { chip_h + space::XS } else { 0.0 };
90        let (offsets, flow_h) = flow(&widths, width - pad * 2.0, chip_h, space::XS);
91        let body_h = if collapsed || self.chips.is_empty() { 0.0 } else { flow_h };
92        let height = (pad * 2.0 + header_h + body_h).max(theme.control_height());
93        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::click());
94        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{} {}", self.chips.len(), self.noun)));
95
96        let border = if self.picking {
97            // A subtle pulse while picking: the border breathes between the
98            // ring colour and a lighter mix of it. Still under reduce-motion.
99            let t = if theme.reduce_motion {
100                0.0
101            } else {
102                ui.ctx().request_repaint();
103                ((ui.input(|i| i.time) * 3.0).sin() * 0.5 + 0.5) as f32
104            };
105            paint::lerp_color(c.accent_ring, crate::theme::mix(c.accent_ring, c.bg_input, 0.45), t)
106        } else if response.hovered() {
107            crate::theme::mix(c.border_strong, c.text_secondary, 0.35)
108        } else {
109            c.border_strong
110        };
111        ui.painter().rect(rect, radius::INPUT, c.bg_input, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
112        if self.picking || response.has_focus() {
113            paint::focus_ring(ui, rect, radius::INPUT, &theme);
114        }
115        let mut out = ReferenceOutput { response: response.clone(), removed: None, chips: Vec::new(), disclosure: None };
116        let origin = rect.min + Vec2::splat(pad);
117        if self.chips.is_empty() {
118            let text = if self.picking { format!("Pick {}…", self.noun) } else { format!("No {} picked", self.noun) };
119            let g = paint::galley(ui, &text, font);
120            ui.painter().galley(egui::pos2(rect.left() + space::MD, rect.center().y - g.size().y / 2.0), g, c.text_disabled);
121            return out;
122        }
123        let mut top = origin.y;
124        if many {
125            // "12 faces" with a disclosure arrow.
126            let text = format!("{} {}", self.chips.len(), self.noun);
127            let g = paint::galley(ui, &text, font.clone());
128            let row = Rect::from_min_size(origin, Vec2::new(18.0 + g.size().x + space::SM, chip_h));
129            let toggle = ui.interact(row, id.with("disclosure"), egui::Sense::click());
130            toggle.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::CollapsingHeader, true, &text));
131            let open = ui.ctx().animate_bool_with_time(id.with("open"), expanded, theme.motion_base());
132            if toggle.hovered() {
133                ui.painter().rect_filled(row, radius::INPUT, c.hover);
134            }
135            paint::disclosure(ui.painter(), egui::pos2(row.left() + 9.0, row.center().y), 3.5, open, Stroke::new(1.5, c.text_secondary));
136            ui.painter().galley(egui::pos2(row.left() + 18.0, row.center().y - g.size().y / 2.0), g, c.text_primary);
137            if toggle.clicked() {
138                expanded = !expanded;
139                ui.data_mut(|d| d.insert_temp(expanded_id, expanded));
140            }
141            out.disclosure = Some(row);
142            top += header_h;
143        }
144        if collapsed {
145            return out;
146        }
147        for (i, ((chip, g), offset)) in self.chips.iter().zip(galleys).zip(offsets).enumerate() {
148            let chip_rect = Rect::from_min_size(egui::pos2(origin.x, top) + offset, Vec2::new(widths[i], chip_h));
149            ui.painter().rect(chip_rect, chip_h / 2.0, c.bg_raised, Stroke::new(BORDER, c.border_subtle), egui::StrokeKind::Inside);
150            let mut x = chip_rect.left() + space::SM;
151            if !chip.glyph.is_empty() {
152                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);
153                x += 14.0 + space::XS;
154            }
155            let gw = g.size();
156            ui.painter().galley(egui::pos2(x, chip_rect.center().y - gw.y / 2.0), g, c.text_primary);
157            let close = Rect::from_center_size(egui::pos2(chip_rect.right() - space::XS - 7.0, chip_rect.center().y), Vec2::splat(14.0));
158            let remove = ui.interact(close, id.with(("remove", i)), egui::Sense::click());
159            remove.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("Remove {}", chip.name)));
160            if remove.hovered() {
161                ui.painter().circle_filled(close.center(), 7.0, c.pressed);
162            }
163            paint::cross(ui.painter(), close.center(), 3.0, Stroke::new(1.3, if remove.hovered() { c.text_primary } else { c.text_secondary }));
164            if remove.clicked() {
165                out.removed = Some(i);
166            }
167            out.chips.push((i, chip_rect, close));
168        }
169        out
170    }
171}