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