Skip to main content

brep_app/ui_kit/
gallery.rs

1//! The developer gallery: every component in every state, in both themes and
2//! both densities, with the four open decisions (spec section 9) as dropdowns
3//! so the owner can try each option, and a switch that previews the theme on
4//! the whole app.
5//!
6//! Reached from MCP (`ui.gallery`), from `BREP_UI_GALLERY=1` on the desktop and
7//! from `?uiGallery` in the browser. It is not in any menu: nothing in the
8//! app's chrome changes until the owner has signed off on the look.
9use super::preview::{theme_for, Choices, FontChoice, LightScope, Preview, PreviewFonts, View};
10use super::surface::{self, Cell, Kind, TreeRow};
11use super::{chips, dropdown, icon_button, input, paint, tabs, toggle, Button, Chip, DocumentTab, IconButton, Show, Size, Variant};
12use crate::automation::hit_keys::HitKeyDoc;
13use crate::theme::{self, contrast, over, space, Density, Mode, Text, Theme, ACCENTS};
14use eframe::egui::{self, Color32, Rect, Vec2};
15use std::collections::HashMap;
16use std::sync::Arc;
17
18pub static HIT_KEYS: &[HitKeyDoc] = &[
19    HitKeyDoc { panel: "uigallery", prefix: "choice:", meaning: "one of the four open decisions as a dropdown (choice:font, choice:accent, choice:density, choice:light); while it is open its rows are choice:<name>:<index>", command: Some("gallery") },
20    HitKeyDoc { panel: "uigallery", prefix: "view:", meaning: "how the gallery is shown: view:theme (dropdown; rows view:theme:<index>), view:preview (switch: the theme on the whole app), view:reduceMotion (switch), view:close", command: Some("gallery") },
21    HitKeyDoc { panel: "uigallery", prefix: "section:", meaning: "a gallery section's card (section:decisions, section:colours, section:buttons, ...): a region to capture", command: None },
22    HitKeyDoc { panel: "uigallery", prefix: "demo:", meaning: "a live sample control (demo:primary, demo:tab:<index>, demo:switch, demo:checkbox, demo:dropdown and its rows demo:dropdown:<index>, demo:long and demo:long:<index>, demo:search, demo:number)", command: None },
23];
24
25/// The values the gallery's live samples hold.
26struct Demo {
27    clicks: u32,
28    tab: usize,
29    wide_tab: usize,
30    document: usize,
31    documents: Vec<(String, bool)>,
32    name: String,
33    search: String,
34    depth: f64,
35    width_in: f64,
36    angle: f64,
37    operation: usize,
38    material: usize,
39    checked: bool,
40    switch_on: bool,
41    slider: f32,
42    picks: Vec<String>,
43    picking: bool,
44    panel_collapsed: bool,
45    tree_selected: usize,
46    table_selected: usize,
47    list_selected: usize,
48    tool: usize,
49}
50
51impl Default for Demo {
52    fn default() -> Self {
53        Demo {
54            clicks: 0,
55            tab: 0,
56            wide_tab: 1,
57            document: 0,
58            documents: vec![("bracket.nbrep".into(), true), ("gearbox.nbrep".into(), false), ("board.nbrep".into(), false)],
59            name: "Bracket".into(),
60            search: String::new(),
61            depth: 12.5,
62            width_in: 2.0,
63            angle: 45.0,
64            operation: 0,
65            material: 3,
66            checked: true,
67            switch_on: true,
68            slider: 0.4,
69            picks: (1..=3).map(|i| format!("Face {i}")).collect(),
70            picking: false,
71            panel_collapsed: false,
72            tree_selected: 2,
73            table_selected: 1,
74            list_selected: 0,
75            tool: 1,
76        }
77    }
78}
79
80const OPERATIONS: &[&str] = &["New body", "Join", "Cut", "Intersect"];
81const OPERATION_GROUPS: &[(usize, &str)] = &[(0, "Create"), (1, "Combine with the target")];
82const MATERIALS: &[&str] = &[
83    "ABS", "Acetal", "Aluminium 6061", "Aluminium 7075", "Brass", "Bronze", "Carbon steel", "Cast iron", "Copper", "Nylon", "PEEK", "Polycarbonate", "Stainless 304", "Stainless 316", "Titanium Gr 5",
84];
85const WORKBENCHES: &[&str] = &["Modeling", "Sketch", "Assembly", "Drawing", "PMI", "CAM", "PCB"];
86const MANY_TABS: &[&str] = &["Features", "Bodies", "Sketches", "Constraints", "Expressions", "Materials", "Appearance", "Simulation", "Toolpaths", "Notes", "History", "Diagnostics"];
87
88/// The gallery, the decisions chosen in it, and the whole-app preview.
89#[derive(Default)]
90pub struct Gallery {
91    pub open: bool,
92    /// Whether the theme is previewed on the whole app. Never saved.
93    pub preview: bool,
94    pub choices: Choices,
95    pub view: View,
96    /// Fill the whole window (captures).
97    pub maximized: bool,
98    pub reduce_motion: bool,
99    fonts: PreviewFonts,
100    applied: Preview,
101    demo: Demo,
102    hits: HashMap<String, Rect>,
103    /// The hit blob was published non-empty last frame, so one more (empty)
104    /// publish is owed after closing.
105    published: bool,
106}
107
108impl Default for View {
109    fn default() -> Self {
110        View::App
111    }
112}
113
114fn hex(c: Color32) -> String {
115    format!("#{:02x}{:02x}{:02x}", c.r(), c.g(), c.b())
116}
117
118impl Gallery {
119    /// The gallery as the launch environment asks for it: open when
120    /// `BREP_UI_GALLERY` is set (desktop) or the page URL carries `?uiGallery`
121    /// (browser), closed otherwise.
122    pub fn from_launch() -> Self {
123        Gallery { open: launch_requested(), ..Default::default() }
124    }
125
126    /// Nothing to do this frame: closed, not previewing, nothing to restore.
127    pub fn idle(&self) -> bool {
128        !self.open && !self.preview && !self.applied.active() && !self.fonts.touched()
129    }
130
131    /// Whether the hit blob must be published this frame.
132    pub fn publishes(&self) -> bool {
133        self.open || self.published
134    }
135
136    pub fn hits_json(&mut self) -> String {
137        self.published = !self.hits.is_empty();
138        crate::automation::hit_rects::hits_json(&self.hits)
139    }
140
141    /// The theme mode the app is in.
142    fn app_mode(ctx: &egui::Context) -> Mode {
143        Mode::of(ctx.theme() == egui::Theme::Dark)
144    }
145
146    /// The mode the gallery window is drawn in.
147    pub fn mode(&self, ctx: &egui::Context) -> Mode {
148        match self.view {
149            View::App => Self::app_mode(ctx),
150            View::Dark => Mode::Dark,
151            View::Light => Mode::Light,
152        }
153    }
154
155    fn theme(&self, ctx: &egui::Context, mode: Mode) -> Theme {
156        theme_for(self.choices, mode, &self.fonts.families(ctx), self.reduce_motion)
157    }
158
159    /// Whether the whole-app preview is on or still installed.
160    pub fn previewing(&self) -> bool {
161        self.preview || self.applied.active()
162    }
163
164    /// Bring the context in line with the gallery's state: bind or restore the
165    /// preview fonts, install or remove the whole-app preview. Called once per
166    /// frame, before any panel draws; returns at once while [`Gallery::idle`].
167    pub fn sync(&mut self, ctx: &egui::Context) {
168        if self.idle() {
169            return;
170        }
171        if self.open || self.preview {
172            self.fonts.ensure(ctx, self.choices.font);
173        }
174        if self.preview {
175            let families = self.fonts.families(ctx);
176            self.applied.apply(ctx, self.choices, &families, self.reduce_motion);
177            theme::set(ctx, Arc::new(self.theme(ctx, Self::app_mode(ctx))));
178        } else if self.applied.active() {
179            self.applied.remove(ctx);
180            theme::clear(ctx);
181        }
182        if !self.open && !self.preview {
183            // Styles first (above), fonts after: no style names a family that
184            // is about to be unbound.
185            self.fonts.restore(ctx);
186        }
187    }
188
189    /// The gallery's state, as the `gallery` command answers it.
190    pub fn state_json(&self, ctx: &egui::Context) -> serde_json::Value {
191        let accent = ACCENTS[self.choices.accent];
192        let mode = self.mode(ctx);
193        let theme = self.theme(ctx, mode);
194        let c = &theme.colors;
195        serde_json::json!({
196            "open": self.open,
197            "preview": self.preview,
198            "previewApplied": self.applied.active(),
199            "font": self.choices.font,
200            "fontDescription": self.fonts.description(),
201            "accent": { "key": accent.key, "label": accent.label, "hex": hex(accent.color) },
202            "density": self.choices.density.label().to_lowercase(),
203            "light": self.choices.light,
204            "view": self.view,
205            "mode": mode.label().to_lowercase(),
206            "maximized": self.maximized,
207            "reduceMotion": self.reduce_motion,
208            "summary": self.choices.summary(),
209            "tokens": {
210                "bgApp": hex(c.bg_app), "bgPanel": hex(c.bg_panel), "bgRaised": hex(c.bg_raised), "bgInput": hex(c.bg_input),
211                "textPrimary": hex(c.text_primary), "textSecondary": hex(c.text_secondary),
212                "accent": hex(c.accent), "accentFill": hex(c.accent_fill), "accentText": hex(c.accent_text), "accentRing": hex(c.accent_ring),
213                "controlHeight": theme.control_height(),
214                "whiteOnAccent": (f64::from(contrast(Color32::WHITE, c.accent)) * 100.0).round() / 100.0,
215                "whiteOnAccentFill": (f64::from(contrast(Color32::WHITE, c.accent_fill)) * 100.0).round() / 100.0,
216            },
217            "demo": {
218                "clicks": self.demo.clicks,
219                "tab": self.demo.tab,
220                "switchOn": self.demo.switch_on,
221                "checked": self.demo.checked,
222                "operation": OPERATIONS[self.demo.operation],
223                "material": MATERIALS[self.demo.material],
224                "search": self.demo.search,
225                "depth": self.demo.depth,
226            },
227        })
228    }
229
230    pub fn show(&mut self, ctx: &egui::Context) {
231        self.hits.clear();
232        if !self.open {
233            return;
234        }
235        let theme = Arc::new(self.theme(ctx, self.mode(ctx)));
236        let c = theme.colors;
237        let frame = egui::Frame::new()
238            .fill(c.bg_panel)
239            .stroke(egui::Stroke::new(1.0, c.border_subtle))
240            .corner_radius(theme::radius::CARD)
241            .shadow(theme.shadow_medium())
242            .inner_margin(egui::Margin::same(space::LG as i8));
243        let mut window = egui::Window::new("UI gallery (developer)").id(egui::Id::new("brep-ui-gallery-window")).title_bar(false).frame(frame).collapsible(false);
244        window = if self.maximized {
245            window.fixed_rect(ctx.content_rect().shrink(6.0))
246        } else {
247            window.resizable(true).default_size([1180.0, 760.0]).default_pos(crate::panels::below_chrome(ctx, 60.0, 0.0))
248        };
249        window.show(ctx, |ui| {
250            super::themed(ui, theme.clone(), |ui| {
251                self.header(ui, &theme);
252                ui.add_space(space::MD);
253                egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
254                    ui.spacing_mut().item_spacing.y = space::LG;
255                    self.decisions(ui, &theme);
256                    ui.columns(2, |columns| {
257                        let (left, right) = columns.split_at_mut(1);
258                        let left = &mut left[0];
259                        left.spacing_mut().item_spacing.y = space::LG;
260                        self.colours(left, &theme);
261                        self.typography(left, &theme);
262                        self.buttons(left, &theme);
263                        self.icon_buttons(left, &theme);
264                        self.tabs(left, &theme);
265                        let right = &mut right[0];
266                        right.spacing_mut().item_spacing.y = space::LG;
267                        self.inputs(right, &theme);
268                        self.dropdowns(right, &theme);
269                        self.toggles(right, &theme);
270                        self.references(right, &theme);
271                        self.surfaces(right, &theme);
272                        self.data(right, &theme);
273                    });
274                });
275            });
276        });
277    }
278
279    fn hit(&mut self, key: impl Into<String>, rect: Rect) {
280        self.hits.insert(key.into(), rect);
281    }
282
283    /// A section card that takes the column's width and publishes its rect.
284    fn card(&mut self, ui: &mut egui::Ui, key: &str, title: &str, contents: impl FnOnce(&mut Self, &mut egui::Ui)) {
285        let rect = surface::section(ui, title, |ui| {
286            ui.set_width(ui.available_width());
287            ui.spacing_mut().item_spacing.y = space::SM;
288            contents(self, ui);
289        })
290        .response
291        .rect;
292        self.hit(format!("section:{key}"), rect);
293    }
294
295    fn header(&mut self, ui: &mut egui::Ui, theme: &Theme) {
296        ui.horizontal(|ui| {
297            ui.label(egui::RichText::new("UI gallery").font(theme.font(Text::Title)).color(theme.colors.text_primary));
298            ui.label(egui::RichText::new("developer preview of the UI refresh · rollout step 1 · nothing here changes the app until the preview switch is on").font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
299            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
300                let close = ui.add(Button::ghost("Close").size(Size::Sm));
301                self.hit("view:close", close.rect);
302                if close.clicked() {
303                    self.open = false;
304                }
305            });
306        });
307    }
308
309    /// A dropdown of the gallery's own, with its closed rect and open rows published.
310    fn choice(&mut self, ui: &mut egui::Ui, key: &str, items: &[&str], selected: &mut usize, width: f32) -> bool {
311        let out = dropdown(("brep-ui-gallery", key), items).width(width).show(ui, selected);
312        self.hit(key, out.response.rect);
313        for (i, rect) in &out.rows {
314            self.hit(format!("{key}:{i}"), *rect);
315        }
316        out.changed
317    }
318
319    fn caption(ui: &mut egui::Ui, theme: &Theme, text: &str) {
320        ui.label(egui::RichText::new(text).font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
321    }
322
323    fn decisions(&mut self, ui: &mut egui::Ui, theme: &Theme) {
324        self.card(ui, "decisions", "Decisions for the owner", |this, ui| {
325            Self::caption(ui, theme, "Spec section 9. Each choice restyles this gallery at once, and the whole app while the preview is on. Nothing is saved.");
326            let label = 130.0;
327            let width = 300.0;
328            ui.columns(2, |columns| {
329                let ui = &mut columns[0];
330                ui.spacing_mut().item_spacing.y = space::SM;
331                surface::field_row(ui, "1. Font", label, |ui| {
332                    let labels: Vec<&str> = FontChoice::ALL.iter().map(|f| f.label()).collect();
333                    let mut index = FontChoice::ALL.iter().position(|f| *f == this.choices.font).unwrap_or(0);
334                    if this.choice(ui, "choice:font", &labels, &mut index, width) {
335                        this.choices.font = FontChoice::ALL[index];
336                    }
337                });
338                surface::field_row(ui, "", label, |ui| Self::caption(ui, theme, this.fonts.description()));
339                surface::field_row(ui, "2. Accent colour", label, |ui| {
340                    let labels: Vec<&str> = ACCENTS.iter().map(|a| a.label).collect();
341                    let mut index = this.choices.accent;
342                    if this.choice(ui, "choice:accent", &labels, &mut index, width) {
343                        this.choices.accent = index;
344                    }
345                    for (name, color) in [("accent", theme.colors.accent), ("fill", theme.colors.accent_fill), ("text", theme.colors.accent_text)] {
346                        let (rect, _) = ui.allocate_exact_size(Vec2::splat(theme.control_height()), egui::Sense::hover());
347                        ui.painter().rect_filled(rect.shrink(3.0), 4.0, color);
348                        Self::caption(ui, theme, name);
349                    }
350                });
351                surface::field_row(ui, "3. Default density", label, |ui| {
352                    let all = [Density::Compact, Density::Comfortable];
353                    let labels = ["Compact (24 px controls, proposed)", "Comfortable (28 px controls)"];
354                    let mut index = all.iter().position(|d| *d == this.choices.density).unwrap_or(0);
355                    if this.choice(ui, "choice:density", &labels, &mut index, width) {
356                        this.choices.density = all[index];
357                    }
358                });
359                surface::field_row(ui, "4. Light theme", label, |ui| {
360                    let labels: Vec<&str> = LightScope::ALL.iter().map(|l| l.label()).collect();
361                    let mut index = LightScope::ALL.iter().position(|l| *l == this.choices.light).unwrap_or(0);
362                    if this.choice(ui, "choice:light", &labels, &mut index, width) {
363                        this.choices.light = LightScope::ALL[index];
364                    }
365                });
366                let ui = &mut columns[1];
367                ui.spacing_mut().item_spacing.y = space::SM;
368                surface::field_row(ui, "Gallery theme", label, |ui| {
369                    let labels: Vec<&str> = View::ALL.iter().map(|v| v.label()).collect();
370                    let mut index = View::ALL.iter().position(|v| *v == this.view).unwrap_or(0);
371                    if this.choice(ui, "view:theme", &labels, &mut index, 180.0) {
372                        this.view = View::ALL[index];
373                    }
374                });
375                surface::field_row(ui, "Whole app", label, |ui| {
376                    let r = toggle::switch(ui, &mut this.preview, "Preview the theme on the whole app");
377                    this.hit("view:preview", r.rect);
378                });
379                surface::field_row(ui, "Motion", label, |ui| {
380                    let r = toggle::switch(ui, &mut this.reduce_motion, "Reduce motion");
381                    this.hit("view:reduceMotion", r.rect);
382                });
383                let white = contrast(Color32::WHITE, theme.colors.accent);
384                if white < 4.5 {
385                    surface::field_row(ui, "Finding", label, |ui| {
386                        ui.vertical(|ui| {
387                        ui.set_max_width(380.0);
388                        ui.add(egui::Label::new(
389                            egui::RichText::new(format!(
390                                "White text on this accent is {white:.2}:1, under the 4.5:1 the spec asks for. Filled buttons use the accent darkened to {} ({:.2}:1); rings, bars and marks keep the accent itself.",
391                                hex(theme.colors.accent_fill),
392                                contrast(Color32::WHITE, theme.colors.accent_fill)
393                            ))
394                            .font(theme.font(Text::Caption))
395                            .color(theme.colors.warning),
396                        ).wrap());
397                        });
398                    });
399                }
400            });
401            ui.label(egui::RichText::new(format!("Chosen: {}", this.choices.summary())).font(theme.font(Text::Label)).color(theme.colors.text_primary));
402        });
403    }
404
405    fn colours(&mut self, ui: &mut egui::Ui, theme: &Theme) {
406        self.card(ui, "colours", &format!("Colour roles ({})", theme.mode.label().to_lowercase()), |_, ui| {
407            let c = &theme.colors;
408            let swatches: [(&str, Color32, Color32); 16] = [
409                ("bg.app", c.bg_app, c.text_primary),
410                ("bg.panel", c.bg_panel, c.text_primary),
411                ("bg.raised", c.bg_raised, c.text_primary),
412                ("bg.input", c.bg_input, c.text_primary),
413                ("bg.hover", over(c.bg_panel, c.hover), c.text_primary),
414                ("bg.pressed", over(c.bg_panel, c.pressed), c.text_primary),
415                ("border.subtle", c.border_subtle, c.text_primary),
416                ("border.strong", c.border_strong, c.text_primary),
417                ("accent", c.accent, c.on_accent),
418                ("accent.fill", c.accent_fill, c.on_accent),
419                ("accent.muted", over(c.bg_panel, c.accent_muted), c.text_primary),
420                ("text.secondary", c.bg_panel, c.text_secondary),
421                ("text.disabled", c.bg_panel, c.text_disabled),
422                ("danger", c.bg_panel, c.danger),
423                ("warning", c.bg_panel, c.warning),
424                ("success", c.bg_panel, c.success),
425            ];
426            egui::Grid::new("brep-ui-gallery-swatches").num_columns(4).spacing([space::SM, space::SM]).show(ui, |ui| {
427                for (i, (name, bg, fg)) in swatches.iter().enumerate() {
428                    let (rect, _) = ui.allocate_exact_size(Vec2::new(128.0, 40.0), egui::Sense::hover());
429                    ui.painter().rect(rect, 6.0, *bg, egui::Stroke::new(1.0, c.border_subtle), egui::StrokeKind::Inside);
430                    let g = paint::galley(ui, name, theme.font(Text::Label));
431                    ui.painter().galley(rect.min + Vec2::new(8.0, 5.0), g, *fg);
432                    let shown = if *bg == c.bg_panel && !name.starts_with("bg.") { *fg } else { *bg };
433                    let detail = format!("{}  {:.1}:1", hex(shown), contrast(*fg, *bg));
434                    let g = paint::galley(ui, &detail, theme.font(Text::Caption));
435                    ui.painter().galley(rect.min + Vec2::new(8.0, 22.0), g, *fg);
436                    if i % 4 == 3 {
437                        ui.end_row();
438                    }
439                }
440            });
441            Self::caption(ui, theme, "Each swatch shows its hex and the contrast of its text on its fill. Body text roles meet 4.5:1 on every surface; focus rings meet 3:1.");
442        });
443    }
444
445    fn typography(&mut self, ui: &mut egui::Ui, theme: &Theme) {
446        self.card(ui, "typography", "Typography", |_, ui| {
447            for (role, name, sample) in [
448                (Text::Title, "Panel title 16 semibold", "Extrude"),
449                (Text::Section, "Section header 14 semibold", "Profile and direction"),
450                (Text::Body, "Body 13", "Select a closed profile, then set the depth."),
451                (Text::Label, "Label 12 semibold", "Depth"),
452                (Text::Caption, "Caption 11", "Measured along the sketch normal"),
453                (Text::Code, "Code 12 monospace", "depth = width / 2 + 0.5"),
454                (Text::Data, "Data 12 monospace", "Extrude 1     12.500 mm"),
455            ] {
456                ui.horizontal(|ui| {
457                    let g = paint::galley(ui, name, theme.font(Text::Caption));
458                    let (rect, _) = ui.allocate_exact_size(Vec2::new(170.0, 22.0), egui::Sense::hover());
459                    ui.painter().galley(egui::pos2(rect.left(), rect.center().y - g.size().y / 2.0), g, theme.colors.text_secondary);
460                    ui.label(egui::RichText::new(sample).font(theme.font(role)).color(theme.colors.text_primary));
461                });
462            }
463            ui.horizontal(|ui| {
464                let (rect, _) = ui.allocate_exact_size(Vec2::new(170.0, 40.0), egui::Sense::hover());
465                let g = paint::galley(ui, "Numbers, right-aligned", theme.font(Text::Caption));
466                ui.painter().galley(egui::pos2(rect.left(), rect.top() + 4.0), g, theme.colors.text_secondary);
467                ui.vertical(|ui| {
468                    ui.spacing_mut().item_spacing.y = 0.0;
469                    for value in ["1 111.10", "8 888.88", "12.50"] {
470                        let g = paint::galley(ui, value, theme.font(Text::Body));
471                        let (rect, _) = ui.allocate_exact_size(Vec2::new(80.0, g.size().y), egui::Sense::hover());
472                        ui.painter().galley(egui::pos2(rect.right() - g.size().x, rect.top()), g, theme.colors.text_primary);
473                    }
474                });
475            });
476        });
477    }
478
479    fn buttons(&mut self, ui: &mut egui::Ui, theme: &Theme) {
480        self.card(ui, "buttons", "Buttons", |this, ui| {
481            let glyphs = demo_glyphs();
482            egui::Grid::new("brep-ui-gallery-buttons").spacing([space::MD, space::MD]).show(ui, |ui| {
483                for head in ["", "Rest", "Hover", "Pressed", "Focus", "Disabled", "Busy"] {
484                    Self::caption(ui, theme, head);
485                }
486                ui.end_row();
487                for (name, variant, text) in [
488                    ("primary", Variant::Primary, "Apply"),
489                    ("secondary", Variant::Secondary, "Cancel"),
490                    ("ghost", Variant::Ghost, "Reset"),
491                    ("danger", Variant::Danger, "Delete"),
492                    ("danger, confirm", Variant::DangerFilled, "Delete"),
493                ] {
494                    Self::caption(ui, theme, name);
495                    for show in [Show::Live, Show::Hover, Show::Pressed, Show::Focus] {
496                        ui.add(Button::new(text).variant(variant).show(show));
497                    }
498                    ui.add(Button::new(text).variant(variant).enabled(false));
499                    ui.add(Button::new(text).variant(variant).icon(&glyphs[0]).busy(true));
500                    ui.end_row();
501                }
502            });
503            ui.horizontal_wrapped(|ui| {
504                Self::caption(ui, theme, "sizes and content");
505                ui.add(Button::new("Small 24").size(Size::Sm));
506                ui.add(Button::new("Medium 28").size(Size::Md));
507                ui.add(Button::primary("Create").icon(&glyphs[1]).size(Size::Md));
508                ui.add(Button::new("Save").icon(&glyphs[2]).shortcut("Ctrl+S"));
509                ui.add(Button::ghost("Undo").shortcut("Ctrl+Z"));
510            });
511            ui.horizontal(|ui| {
512                Self::caption(ui, theme, "live");
513                let r = ui.add(Button::primary("Click me"));
514                this.hit("demo:primary", r.rect);
515                if r.clicked() {
516                    this.demo.clicks += 1;
517                }
518                ui.label(egui::RichText::new(format!("clicked {} times", this.demo.clicks)).font(theme.font(Text::Body)).color(theme.colors.text_secondary));
519            });
520        });
521    }
522
523    fn icon_buttons(&mut self, ui: &mut egui::Ui, theme: &Theme) {
524        self.card(ui, "iconButtons", "Icon buttons and the ribbon", |this, ui| {
525            let glyphs = demo_glyphs();
526            ui.horizontal(|ui| {
527                Self::caption(ui, theme, "toolbar 28:");
528                ui.add(IconButton::new(&glyphs[0], "Rest"));
529                ui.add(IconButton::new(&glyphs[1], "Hover").show(Show::Hover));
530                ui.add(IconButton::new(&glyphs[2], "Pressed").show(Show::Pressed));
531                ui.add(IconButton::new(&glyphs[3], "Focus").show(Show::Focus));
532                ui.add(IconButton::new(&glyphs[4], "Active").active(true));
533                ui.add(IconButton::new(&glyphs[5], "Disabled").enabled(false));
534                ui.add_space(space::LG);
535                Self::caption(ui, theme, "rail:");
536                ui.add(IconButton::new(&glyphs[6], "Active on a rail").active(true).bar(icon_button::BarSide::Left));
537            });
538            // A mock ribbon: groups, caption labels, separators.
539            let frame = egui::Frame::new().fill(theme.colors.bg_app).corner_radius(6.0).inner_margin(egui::Margin::same(space::MD as i8));
540            frame.show(ui, |ui| {
541                ui.horizontal(|ui| {
542                    let groups: [(&str, usize); 3] = [("Create", 4), ("Modify", 3), ("Inspect", 2)];
543                    let mut next = 0;
544                    for (g, (label, count)) in groups.iter().enumerate() {
545                        if g > 0 {
546                            icon_button::group_separator(ui, 50.0);
547                        }
548                        icon_button::ribbon_group(ui, label, |ui| {
549                            for _ in 0..*count {
550                                let index = next;
551                                let name = format!("Tool {}", index + 1);
552                                let r = ui.add(
553                                    IconButton::new(&glyphs[index % glyphs.len()], &name)
554                                        .ribbon()
555                                        .active(this.demo.tool == index)
556                                        .description("What the tool does, in one line.")
557                                        .shortcut("E"),
558                                );
559                                if r.clicked() {
560                                    this.demo.tool = index;
561                                }
562                                next += 1;
563                            }
564                        });
565                    }
566                });
567            });
568            ui.horizontal(|ui| {
569                Self::caption(ui, theme, "tooltip:");
570                surface::popup_frame(theme).inner_margin(egui::Margin::same(space::MD as i8)).show(ui, |ui| {
571                    ui.vertical(|ui| icon_button::tooltip_card(ui, "Extrude", Some("Pull a profile into a solid or a cut."), Some("E")));
572                });
573            });
574        });
575    }
576
577    fn tabs(&mut self, ui: &mut egui::Ui, theme: &Theme) {
578        self.card(ui, "tabs", "Tabs", |this, ui| {
579            Self::caption(ui, theme, "Workbench and panel tabs: the underline slides to the tab you pick.");
580            let out = tabs::tab_bar(ui, "brep-ui-gallery-workbench", WORKBENCHES, &mut this.demo.tab);
581            for (i, rect) in out.tabs {
582                this.hit(format!("demo:tab:{i}"), rect);
583            }
584            Self::caption(ui, theme, "Hover and focus:");
585            let mut fixed = 0;
586            tabs::tab_bar_shown(ui, "brep-ui-gallery-tab-hover", &["Active", "Hover", "Inactive"], &mut fixed, Some((1, Show::Hover)));
587            let mut fixed = 0;
588            tabs::tab_bar_shown(ui, "brep-ui-gallery-tab-focus", &["Active", "Focus", "Inactive"], &mut fixed, Some((1, Show::Focus)));
589            Self::caption(ui, theme, "Overflow: tabs that do not fit go into the chevron menu.");
590            ui.scope(|ui| {
591                ui.set_max_width(420.0);
592                tabs::tab_bar(ui, "brep-ui-gallery-overflow", MANY_TABS, &mut this.demo.wide_tab);
593            });
594            Self::caption(ui, theme, "Document tabs: the active tab joins the content; a dot marks unsaved changes.");
595            let docs: Vec<DocumentTab<'_>> = this.demo.documents.iter().map(|(name, dirty)| DocumentTab { name, dirty: *dirty }).collect();
596            let out = tabs::document_tabs(ui, "brep-ui-gallery-documents", &docs, this.demo.document);
597            if let Some(i) = out.activated {
598                this.demo.document = i;
599            }
600            if let Some(i) = out.closed {
601                if this.demo.documents.len() > 1 {
602                    this.demo.documents.remove(i);
603                    this.demo.document = this.demo.document.min(this.demo.documents.len() - 1);
604                }
605            }
606            let (content, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 28.0), egui::Sense::hover());
607            ui.painter().rect_filled(content, 0.0, theme.colors.bg_panel);
608        });
609    }
610
611    fn inputs(&mut self, ui: &mut egui::Ui, theme: &Theme) {
612        self.card(ui, "inputs", "Text and number inputs", |this, ui| {
613            let label = 110.0;
614            let width = 200.0;
615            surface::field_row(ui, "Name", label, |ui| {
616                input::text_input(&mut this.demo.name).placeholder("Name").width(width).show(ui);
617            });
618            surface::field_row(ui, "Placeholder", label, |ui| {
619                let mut empty = String::new();
620                input::text_input(&mut empty).placeholder("Optional note").width(width).id(egui::Id::new("brep-ui-gallery-empty")).show(ui);
621            });
622            surface::field_row(ui, "Hover / focus", label, |ui| {
623                let mut a = String::from("Hover");
624                input::text_input(&mut a).width(96.0).id(egui::Id::new("brep-ui-gallery-hover")).show_state(Show::Hover).show(ui);
625                let mut b = String::from("Focus");
626                input::text_input(&mut b).width(96.0).id(egui::Id::new("brep-ui-gallery-focus")).show_state(Show::Focus).show(ui);
627            });
628            surface::field_row(ui, "Disabled", label, |ui| {
629                let mut text = String::from("Locked by the feature");
630                input::text_input(&mut text).width(width).enabled(false).id(egui::Id::new("brep-ui-gallery-disabled")).show(ui);
631            });
632            surface::field_row(ui, "Error", label, |ui| {
633                ui.vertical(|ui| {
634                    let mut text = String::from("12 +");
635                    input::text_input(&mut text).width(width).suffix("mm").right_aligned(true).error(Some("a value is missing")).id(egui::Id::new("brep-ui-gallery-error")).show(ui);
636                });
637            });
638            surface::field_row(ui, "Search", label, |ui| {
639                let out = input::search_input(&mut this.demo.search).width(width).id(egui::Id::new("brep-ui-gallery-search")).show(ui);
640                this.hit("demo:search", out.rect);
641                let mut filled = String::from("fillet");
642                input::search_input(&mut filled).width(140.0).id(egui::Id::new("brep-ui-gallery-search-filled")).show(ui);
643            });
644            Self::caption(ui, theme, "Numbers: the unit sits inside the field; type an expression or another unit (1/2 in becomes 12.7 mm); drag the label to scrub.");
645            surface::field_row(ui, "", 0.0, |ui| {
646                let out = input::number_input(&mut this.demo.depth).unit("mm").label("Depth").width(120.0).id(egui::Id::new("brep-ui-gallery-depth")).show(ui);
647                this.hit("demo:number", out.input.rect);
648                ui.add_space(space::LG);
649                input::number_input(&mut this.demo.width_in).unit("in").label("Width").width(100.0).id(egui::Id::new("brep-ui-gallery-width")).show(ui);
650                ui.add_space(space::LG);
651                input::number_input(&mut this.demo.angle).unit("deg").label("Angle").width(100.0).speed(0.5).id(egui::Id::new("brep-ui-gallery-angle")).show(ui);
652            });
653        });
654    }
655
656    fn dropdowns(&mut self, ui: &mut egui::Ui, theme: &Theme) {
657        self.card(ui, "dropdowns", "Dropdowns (every enumeration)", |this, ui| {
658            let label = 110.0;
659            surface::field_row(ui, "Operation", label, |ui| {
660                let out = dropdown("brep-ui-gallery-operation", OPERATIONS).groups(OPERATION_GROUPS).width(200.0).show(ui, &mut this.demo.operation);
661                this.hit("demo:dropdown", out.response.rect);
662                for (i, rect) in out.rows {
663                    this.hit(format!("demo:dropdown:{i}"), rect);
664                }
665            });
666            surface::field_row(ui, "Material", label, |ui| {
667                let out = dropdown("brep-ui-gallery-material", MATERIALS).width(200.0).show(ui, &mut this.demo.material);
668                this.hit("demo:long", out.response.rect);
669                for (i, rect) in out.rows {
670                    this.hit(format!("demo:long:{i}"), rect);
671                }
672                Self::caption(ui, theme, "more than 12 items: search at the top");
673            });
674            surface::field_row(ui, "States", label, |ui| {
675                let mut i = 0;
676                dropdown("brep-ui-gallery-dd-hover", &["Hover"]).width(96.0).show_state(Show::Hover).show(ui, &mut i);
677                dropdown("brep-ui-gallery-dd-focus", &["Focus"]).width(96.0).show_state(Show::Focus).show(ui, &mut i);
678                dropdown("brep-ui-gallery-dd-disabled", &["Disabled"]).width(96.0).enabled(false).show(ui, &mut i);
679            });
680            surface::field_row(ui, "Open", label, |ui| {
681                // The popup's look, drawn in place.
682                surface::popup_frame(theme).show(ui, |ui| {
683                    ui.vertical(|ui| {
684                        ui.set_width(200.0);
685                        ui.spacing_mut().item_spacing.y = 0.0;
686                        surface::menu_header(ui, "Create");
687                        surface::menu_row_with(ui, "New body", None, true, false);
688                        surface::menu_header(ui, "Combine with the target");
689                        surface::menu_row_with(ui, "Join", None, false, true);
690                        surface::menu_row_with(ui, "Cut", None, false, false);
691                        surface::menu_row_with(ui, "Intersect", None, false, false);
692                    });
693                });
694            });
695        });
696    }
697
698    fn toggles(&mut self, ui: &mut egui::Ui, theme: &Theme) {
699        self.card(ui, "toggles", "Checkboxes, switches and sliders", |this, ui| {
700            ui.horizontal_wrapped(|ui| {
701                let r = toggle::checkbox(ui, &mut this.demo.checked, "Symmetric");
702                this.hit("demo:checkbox", r.rect);
703                toggle::checkbox_shown(ui, toggle::Check::Off, "Off", true, Show::Live);
704                toggle::checkbox_shown(ui, toggle::Check::On, "Hover", true, Show::Hover);
705                toggle::checkbox_shown(ui, toggle::Check::On, "Focus", true, Show::Focus);
706                toggle::checkbox_shown(ui, toggle::Check::Indeterminate, "Mixed", true, Show::Live);
707                toggle::checkbox_shown(ui, toggle::Check::On, "Disabled", false, Show::Live);
708            });
709            ui.horizontal_wrapped(|ui| {
710                let r = toggle::switch(ui, &mut this.demo.switch_on, "Show edges");
711                this.hit("demo:switch", r.rect);
712                toggle::switch_shown(ui, false, "Off", true, Show::Live);
713                toggle::switch_shown(ui, true, "Focus", true, Show::Focus);
714                toggle::switch_shown(ui, true, "Disabled", false, Show::Live);
715            });
716            ui.horizontal(|ui| {
717                Self::caption(ui, theme, "slider");
718                toggle::slider(ui, &mut this.demo.slider, 0.0..=1.0, 180.0);
719                let mut hover = 0.7;
720                toggle::slider_shown(ui, &mut hover, 0.0..=1.0, 120.0, true, Show::Hover);
721                let mut off = 0.3;
722                toggle::slider_shown(ui, &mut off, 0.0..=1.0, 120.0, false, Show::Live);
723            });
724        });
725    }
726
727    fn references(&mut self, ui: &mut egui::Ui, theme: &Theme) {
728        self.card(ui, "references", "Reference-selection fields", |this, ui| {
729            let glyphs = demo_glyphs();
730            let label = 110.0;
731            surface::field_row(ui, "Faces", label, |ui| {
732                let chip_list: Vec<Chip<'_>> = this.demo.picks.iter().map(|name| Chip { glyph: &glyphs[3], name }).collect();
733                let out = chips::reference_field("brep-ui-gallery-picks", &chip_list, "faces").picking(this.demo.picking).width(300.0).show(ui);
734                if let Some(i) = out.removed {
735                    this.demo.picks.remove(i);
736                } else if out.response.clicked() {
737                    this.demo.picking = !this.demo.picking;
738                }
739            });
740            surface::field_row(ui, "Picking, empty", label, |ui| {
741                chips::reference_field("brep-ui-gallery-picking", &[], "edges").picking(true).width(300.0).show(ui);
742            });
743            surface::field_row(ui, "Many picks", label, |ui| {
744                let names: Vec<String> = (1..=12).map(|i| format!("Face {i}")).collect();
745                let many: Vec<Chip<'_>> = names.iter().map(|name| Chip { glyph: &glyphs[3], name }).collect();
746                chips::reference_field("brep-ui-gallery-many", &many, "faces").width(300.0).show(ui);
747            });
748            Self::caption(ui, theme, "Click the first field to start or stop picking (the border pulses); more than 6 picks collapse to a count.");
749        });
750    }
751
752    fn surfaces(&mut self, ui: &mut egui::Ui, theme: &Theme) {
753        self.card(ui, "surfaces", "Surfaces: panel, tree, menu, dialog, toasts", |this, ui| {
754            let glyphs = demo_glyphs();
755            ui.horizontal_top(|ui| {
756                ui.vertical(|ui| {
757                    ui.set_width(250.0);
758                    // A panel with its header and a tree.
759                    let frame = egui::Frame::new().fill(theme.colors.bg_panel).stroke(egui::Stroke::new(1.0, theme.colors.border_subtle)).corner_radius(6.0);
760                    frame.show(ui, |ui| {
761                        ui.spacing_mut().item_spacing.y = 0.0;
762                        surface::panel_header(ui, "Model", &mut this.demo.panel_collapsed, |ui| {
763                            ui.add(IconButton::new(&glyphs[5], "Panel action"));
764                        });
765                        if !this.demo.panel_collapsed {
766                            let rows = [
767                                (0, "Bracket", None, false),
768                                (1, "Sketch 1", None, false),
769                                (1, "Extrude 1", None, false),
770                                (1, "Fillet 1", Some(Kind::Warning), false),
771                                (1, "Shell 1", Some(Kind::Error), false),
772                                (1, "Pattern 1", None, true),
773                            ];
774                            for (i, (depth, label, badge, suppressed)) in rows.into_iter().enumerate() {
775                                let row = TreeRow { depth, glyph: &glyphs[i % glyphs.len()], label, selected: this.demo.tree_selected == i, badge, suppressed };
776                                if surface::tree_row(ui, row).clicked() {
777                                    this.demo.tree_selected = i;
778                                }
779                            }
780                        }
781                    });
782                    ui.add_space(space::MD);
783                    // A context menu, drawn in place.
784                    surface::popup_frame(theme).show(ui, |ui| {
785                        ui.set_width(220.0);
786                        ui.spacing_mut().item_spacing.y = 0.0;
787                        surface::menu_row(ui, "Edit feature", Some("Enter"), false);
788                        surface::menu_row(ui, "Suppress", Some("Ctrl+H"), false);
789                        surface::menu_row(ui, "Show edges", None, true);
790                        surface::menu_separator(ui);
791                        surface::menu_row(ui, "Delete", Some("Del"), false);
792                    });
793                });
794                ui.add_space(space::LG);
795                ui.vertical(|ui| {
796                    surface::dialog(ui, "Delete 3 features?", "Delete", "Cancel", 300.0, |ui| {
797                        ui.label(egui::RichText::new("Fillet 1, Shell 1 and Pattern 1 will be removed. Features that depend on them will fail.").font(theme.font(Text::Body)).color(theme.colors.text_primary));
798                    });
799                    ui.add_space(space::LG);
800                    surface::toast(ui, Kind::Success, "Saved bracket.nbrep", 300.0);
801                    ui.add_space(space::SM);
802                    surface::toast(ui, Kind::Warning, "Fillet 1 was rebuilt with a smaller radius.", 300.0);
803                    ui.add_space(space::SM);
804                    surface::toast(ui, Kind::Error, "Shell 1 failed: the wall is thicker than the body.", 300.0);
805                });
806            });
807        });
808    }
809}
810
811impl Gallery {
812    /// Owner 2026-11-28: tables, trees and lists draw in the monospace data
813    /// face whichever UI font is chosen, so their characters line up.
814    fn data(&mut self, ui: &mut egui::Ui, theme: &Theme) {
815        self.card(ui, "data", "Tables and lists: monospace rows", |this, ui| {
816            ui.horizontal_top(|ui| {
817                let frame = egui::Frame::new().fill(theme.colors.bg_panel).stroke(egui::Stroke::new(1.0, theme.colors.border_subtle)).corner_radius(6.0);
818                ui.vertical(|ui| {
819                    ui.set_width(330.0);
820                    frame.show(ui, |ui| {
821                        ui.spacing_mut().item_spacing.y = 0.0;
822                        let widths = [130.0, 100.0, 100.0];
823                        let cells = |row: [&'static str; 3]| [0, 1, 2].map(|i| Cell { text: row[i], width: widths[i], number: i > 0 });
824                        surface::table_row(ui, &cells(["Name", "Value", "Mass kg"]), true, false);
825                        let rows = [["width", "120.000 mm", "1.250"], ["depth", "62.500 mm", "0.875"], ["wall", "2.000 mm", "11.004"], ["holes", "8", "0.000"], ["draft", "1.500 deg", "110.310"]];
826                        for (i, row) in rows.into_iter().enumerate() {
827                            if surface::table_row(ui, &cells(row), false, this.demo.table_selected == i).clicked() {
828                                this.demo.table_selected = i;
829                            }
830                        }
831                    });
832                });
833                ui.add_space(space::LG);
834                ui.vertical(|ui| {
835                    ui.set_width(220.0);
836                    frame.show(ui, |ui| {
837                        ui.spacing_mut().item_spacing.y = 0.0;
838                        for (i, text) in ["R1   10k   0603", "R12  4k7   0603", "C3   100n  0402", "U1   MCU   QFN32", "J2   USB-C"].into_iter().enumerate() {
839                            if surface::table_row(ui, &[Cell { text, width: 220.0, number: false }], false, this.demo.list_selected == i).clicked() {
840                                this.demo.list_selected = i;
841                            }
842                        }
843                    });
844                });
845            });
846            Self::caption(ui, theme, "Tree rows (in Surfaces), table rows and list rows always use the monospace face, with font A or B: digits and columns line up.");
847        });
848    }
849}
850
851/// A handful of glyphs from the icon catalog for the samples (their meaning
852/// does not matter here), padded with letters if the catalog is short.
853fn demo_glyphs() -> Vec<String> {
854    let mut glyphs: Vec<String> = crate::icons::ICONS.iter().step_by((crate::icons::ICONS.len() / 12).max(1)).take(12).map(|icon| icon.ch.to_string()).collect();
855    while glyphs.len() < 12 {
856        glyphs.push(char::from(b'A' + glyphs.len() as u8).to_string());
857    }
858    glyphs
859}
860
861#[cfg(not(target_arch = "wasm32"))]
862fn launch_requested() -> bool {
863    std::env::var("BREP_UI_GALLERY").is_ok_and(|v| !v.is_empty() && v != "0")
864}
865
866#[cfg(target_arch = "wasm32")]
867fn launch_requested() -> bool {
868    web_sys::window()
869        .and_then(|w| w.location().search().ok())
870        .and_then(|search| web_sys::UrlSearchParams::new_with_str(&search).ok())
871        .is_some_and(|params| params.has("uiGallery"))
872}