functora-egui 0.4.2

shadcn/ui-inspired widget library for egui - buttons, inputs, selects, dialogs, and 70+ more components with light/dark theming
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::cell::Cell;

use crate::nav::NavHistory;
use crate::responsive::responsive_ext::ResponsiveExt;
use crate::route::RouteMetadata;
use crate::theme::shadcn_theme_ext::ShadcnThemeExt;
use crate::theme_extra::Theme;
use crate::widgets::breadcrumb::{Breadcrumb, NavAction};

type FooterFn<'a> = Box<dyn FnOnce(&mut egui::Ui) + 'a>;

#[must_use]
pub fn initial_sidebar_collapsed(ctx: &egui::Context) -> bool {
    let width = sidebar_startup_width(ctx);
    if width == 0.0 {
        true
    } else {
        width < crate::responsive::breakpoint::Breakpoint::MOBILE_MAX_WIDTH
    }
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
fn sidebar_startup_width(ctx: &egui::Context) -> f32 {
    web_sys::window()
        .and_then(|win| {
            win.visual_viewport()
                .map(|vp| crate::utils::f64_to_f32(vp.width()))
                .or_else(|| {
                    win.inner_width()
                        .ok()
                        .and_then(|v| v.as_f64())
                        .map(crate::utils::f64_to_f32)
                })
        })
        .unwrap_or_else(|| ctx.input(|i| i.viewport_rect().width()))
}

#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
fn sidebar_startup_width(ctx: &egui::Context) -> f32 {
    ctx.input(|i| i.viewport_rect().width())
}

fn sync_sidebar_collapsed(ctx: &egui::Context, collapsed: bool) -> bool {
    let width = ctx.input(|i| i.viewport_rect().width());
    let is_mobile = ctx.on_mobile();
    let init_id = egui::Id::unique("shell_sidebar_init_done");
    let prev_id = egui::Id::unique("shell_prev_is_mobile");
    let init_done = ctx.data(|d| d.get_temp::<bool>(init_id).unwrap_or(false));
    if !init_done {
        if width == 0.0 {
            let _ = ctx.data_mut(|d| d.insert_temp(prev_id, true));
            true
        } else {
            let _ = ctx.data_mut(|d| {
                let _ = d.insert_temp(init_id, true);
                d.insert_temp(prev_id, is_mobile)
            });
            is_mobile
        }
    } else if width == 0.0 {
        collapsed
    } else {
        let prev = ctx.data(|d| d.get_temp::<bool>(prev_id).unwrap_or(is_mobile));
        let _ = ctx.data_mut(|d| d.insert_temp(prev_id, is_mobile));
        match (is_mobile, prev) {
            (true, false) => true,
            (false, true) => false,
            (true, true) | (false, false) => collapsed,
        }
    }
}

#[must_use]
pub fn sidebar_effective_width(ctx: &egui::Context, labels: &[&str]) -> f32 {
    let spacing = ctx.responsive_spacing();
    let max_text = labels
        .iter()
        .map(|name| {
            let font_id = egui::FontId::proportional(14.0);
            crate::text::natural_width(ctx, (*name).to_owned(), font_id)
        })
        .fold(0.0, f32::max);
    let icon = spacing.touch_height * 0.5;
    let toggle_size = crate::tokens::component_size::ComponentSize::Sm
        .metrics_for(&spacing)
        .0;
    max_text + icon + spacing.gap + spacing.touch_padding * 2.0 + spacing.gap + toggle_size
}

/// Clamps the sidebar width to the viewport: full label width where it fits,
/// shrunk instead of overflowing on narrow screens.
fn clamped_sidebar_width(ctx: &egui::Context, sidebar_labels: &[&str]) -> f32 {
    let spacing = ctx.responsive_spacing();
    let screen_width = ctx.input(|i| i.viewport_rect().width());
    let max_allowed_outer = (screen_width - spacing.page_padding * 2.0).max(0.0);
    sidebar_effective_width(ctx, sidebar_labels).min((max_allowed_outer - 16.0).max(0.0))
}

/// Renders the collapsible sidebar and folds a mobile close request back
/// into `collapsed`. Shared by the desktop side panel and the mobile drawer.
fn render_sidebar(
    ui: &mut egui::Ui,
    effective: f32,
    collapsed: &mut bool,
    sidebar: &mut dyn FnMut(&mut egui::Ui) -> bool,
) {
    let close = std::cell::Cell::new(false);
    let _ = crate::widgets::sidebar::widget::Sidebar::new()
        .width(effective)
        .collapsible()
        .show(ui, collapsed, |side_ui| {
            close.set(sidebar(side_ui));
        });
    if close.get() {
        *collapsed = true;
    }
}

pub struct Shell<'a, R>
where
    R: RouteMetadata,
{
    brand: &'a str,
    brand_icon: Option<crate::icons::lucide_icon::LucideIcon>,
    version: Option<&'a str>,
    collapsed: &'a mut bool,
    theme: Option<&'a mut Theme>,
    language: Option<&'a Cell<functora_core::i18n::Language>>,
    search_label: Option<&'a str>,
    search_shortcut: Option<&'a str>,
    on_brand: Option<Box<dyn FnMut() + 'a>>,
    on_search: Option<Box<dyn FnMut() + 'a>>,
    sidebar: Box<dyn FnMut(&mut egui::Ui) -> bool + 'a>,
    breadcrumb: Option<(&'a R, &'a NavHistory<R>)>,
    sidebar_labels: Vec<&'a str>,
    scroll_top: bool,
    footer: Option<FooterFn<'a>>,
    system_back: bool,
}

impl<'a, R> Shell<'a, R>
where
    R: RouteMetadata,
{
    pub fn new(
        brand: &'a str,
        collapsed: &'a mut bool,
        sidebar: impl FnMut(&mut egui::Ui) -> bool + 'a,
    ) -> Self {
        Self {
            brand,
            brand_icon: None,
            version: None,
            collapsed,
            theme: None,
            language: None,
            search_label: None,
            search_shortcut: None,
            on_brand: None,
            on_search: None,
            sidebar: Box::new(sidebar),
            breadcrumb: None,
            sidebar_labels: Vec::new(),
            scroll_top: false,
            footer: None,
            system_back: true,
        }
    }

    #[must_use]
    pub fn brand_icon(mut self, icon: Option<crate::icons::lucide_icon::LucideIcon>) -> Self {
        self.brand_icon = icon;
        self
    }

    #[must_use]
    pub fn version(mut self, version: &'a str) -> Self {
        self.version = Some(version);
        self
    }

    #[must_use]
    pub fn theme(mut self, theme: &'a mut Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    #[must_use]
    pub fn language(mut self, language: &'a Cell<functora_core::i18n::Language>) -> Self {
        self.language = Some(language);
        self
    }

    #[must_use]
    pub fn search(mut self, label: &'a str, shortcut: Option<&'a str>) -> Self {
        self.search_label = Some(label);
        self.search_shortcut = shortcut;
        self
    }

    #[must_use]
    pub fn on_brand(mut self, f: impl FnMut() + 'a) -> Self {
        self.on_brand = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn on_search(mut self, f: impl FnMut() + 'a) -> Self {
        self.on_search = Some(Box::new(f));
        self
    }

    #[must_use]
    pub fn breadcrumb(mut self, route: &'a R, history: &'a NavHistory<R>) -> Self {
        self.breadcrumb = Some((route, history));
        self
    }

    #[must_use]
    pub fn sidebar_labels(mut self, labels: impl IntoIterator<Item = &'a str>) -> Self {
        self.sidebar_labels = labels.into_iter().collect();
        self
    }

    #[must_use]
    pub fn scroll_top(mut self, top: bool) -> Self {
        self.scroll_top = top;
        self
    }

    #[must_use]
    pub fn footer(mut self, footer: impl FnOnce(&mut egui::Ui) + 'a) -> Self {
        self.footer = Some(Box::new(footer));
        self
    }

    #[must_use]
    pub fn system_back(mut self, enabled: bool) -> Self {
        self.system_back = enabled;
        self
    }

    pub fn show(
        self,
        ui: &mut egui::Ui,
        content: impl FnOnce(&mut egui::Ui),
    ) -> Option<NavAction<R>> {
        let Self {
            brand,
            brand_icon,
            version,
            collapsed,
            theme,
            language,
            search_label,
            search_shortcut,
            on_brand,
            mut on_search,
            mut sidebar,
            breadcrumb,
            sidebar_labels,
            scroll_top,
            footer,
            system_back,
        } = self;
        let ctx = ui.ctx().clone();
        if let Some(lang_cell) = language {
            crate::language::set_language(&ctx, lang_cell.get());
        }
        let route_id = egui::Id::unique("shell_prev_route");
        let prev_route = ctx.data(|d| d.get_temp::<R>(route_id));
        let route_changed = breadcrumb.is_some_and(|(route, _)| prev_route.as_ref() != Some(route));
        if route_changed && let Some((route, _)) = breadcrumb {
            let _ = ctx.data_mut(|d| d.insert_temp(route_id, route.clone()));
        }
        let mut collapsed_val = sync_sidebar_collapsed(&ctx, *collapsed);
        let mut breadcrumb_action = system_back_action(&ctx, system_back, breadcrumb);
        let brand_clicked = std::rc::Rc::new(std::cell::Cell::new(false));
        if let Some(th) = theme.as_deref() {
            crate::theme_extra::set_theme(&ctx, *th);
        }
        let theme_bg = ShadcnThemeExt::shadcn_theme(&ctx);
        let top = egui::Panel::top("top_bar")
            .frame(egui::Frame::NONE.fill(theme_bg.card))
            .show_separator_line(false)
            .show(ui, |top_ui| {
                let mut navbar = crate::widgets::navbar::widget::Navbar::new(brand);
                navbar = navbar.brand_icon(brand_icon);
                if let Some(v) = version {
                    navbar = navbar.version(v);
                }
                if let Some(l) = search_label {
                    navbar = navbar.search(l, search_shortcut);
                }
                let mut on_brand_wrapper: Option<Box<dyn FnMut() + 'a>> = on_brand.map(|mut cb| {
                    let clicked = std::rc::Rc::clone(&brand_clicked);
                    Box::new(move || {
                        clicked.set(true);
                        cb();
                    }) as Box<dyn FnMut() + 'a>
                });
                let brand_cb: Option<&mut dyn FnMut()> = on_brand_wrapper
                    .as_mut()
                    .map(|b| b.as_mut() as &mut dyn FnMut());
                let search_cb: Option<&mut dyn FnMut()> =
                    on_search.as_mut().map(|b| b.as_mut() as &mut dyn FnMut());
                let _ = navbar.show(
                    top_ui,
                    &mut collapsed_val,
                    theme,
                    language,
                    brand_cb,
                    search_cb,
                );
            });
        let _ = ui.painter().hline(
            top.response.rect.x_range(),
            top.response.rect.max.y - 0.5,
            egui::Stroke::new(1.0, theme_bg.border),
        );
        if !ctx.on_mobile() {
            let is_rail = collapsed_val;
            let spacing = ctx.responsive_spacing();
            let effective = if is_rail {
                spacing.touch_height
            } else {
                clamped_sidebar_width(&ctx, &sidebar_labels)
            };
            let ppp = ctx.pixels_per_point();
            let panel_outer = if ppp > 0.0 {
                ((effective + 16.0) * ppp).round() / ppp
            } else {
                effective + 16.0
            };
            let panel_fill = if is_rail {
                theme_bg.background
            } else {
                theme_bg.card
            };
            let _ = egui::Panel::right("sidebar_panel")
                .exact_size(panel_outer)
                .frame(egui::Frame::NONE.fill(panel_fill))
                .resizable(false)
                .show_separator_line(false)
                .show(ui, |panel_ui| {
                    let mut tmp = collapsed_val;
                    let _ = egui::ScrollArea::vertical().show(panel_ui, |scroll_ui| {
                        render_sidebar(scroll_ui, effective, &mut tmp, &mut sidebar);
                    });
                    collapsed_val = tmp;
                });
        }
        let _ = egui::CentralPanel::default()
            .frame(egui::Frame::NONE.fill(theme_bg.background))
            .show(ui, |central_ui| {
                if central_ui.on_mobile() {
                    let effective = clamped_sidebar_width(central_ui.ctx(), &sidebar_labels);
                    let mut tmp = collapsed_val;
                    render_sidebar(central_ui, effective, &mut tmp, &mut sidebar);
                    collapsed_val = tmp;
                    central_ui.add_space(-central_ui.spacing().item_spacing.y);
                }
                if let Some((route, history)) = breadcrumb {
                    render_breadcrumb_strip(
                        central_ui,
                        route,
                        history,
                        !brand_clicked.get(),
                        language,
                        &mut breadcrumb_action,
                    );
                }
                render_scrolled_content(central_ui, scroll_top, route_changed, footer, content);
            });
        *collapsed = collapsed_val;
        breadcrumb_action
    }
}

/// Maps the hardware back button onto a shell navigation action: `Back`
/// when the history can go back, consumed otherwise.
fn system_back_action<R: RouteMetadata>(
    ctx: &egui::Context,
    system_back: bool,
    breadcrumb: Option<(&R, &NavHistory<R>)>,
) -> Option<NavAction<R>> {
    if !system_back {
        None
    } else if let Some((_, history)) = breadcrumb {
        let mut do_nav = false;
        let _ =
            crate::platform::android_back::handle_system_back(ctx, history.can_go_back(), || {
                do_nav = true
            });
        do_nav.then_some(NavAction::Back)
    } else {
        let _ = crate::platform::android_back::handle_system_back(ctx, false, || {});
        None
    }
}

/// Renders the breadcrumb strip when there is anywhere to go, recording the
/// clicked action into `breadcrumb_action`.
fn render_breadcrumb_strip<R: RouteMetadata>(
    central_ui: &mut egui::Ui,
    route: &R,
    history: &NavHistory<R>,
    brand_alive: bool,
    language: Option<&std::cell::Cell<functora_core::i18n::Language>>,
    breadcrumb_action: &mut Option<NavAction<R>>,
) {
    let should_show = brand_alive
        && (history.can_go_back() || history.can_go_forward() || route.parent().is_some());
    if should_show {
        let lang = language.map_or_else(
            functora_core::i18n::detect_browser_language,
            std::cell::Cell::get,
        );
        let available_w = central_ui.available_width();
        let strip_theme = ShadcnThemeExt::shadcn_theme(central_ui.ctx());
        let strip = egui::Frame::NONE
            .fill(strip_theme.card)
            .inner_margin(egui::Margin::symmetric(12, 8))
            .show(central_ui, |strip_ui| {
                strip_ui.set_min_width(available_w - 24.0);
                if let Some(action) = Breadcrumb::new(route, history).show(strip_ui, lang) {
                    *breadcrumb_action = Some(action);
                }
            });
        let _ = central_ui.painter().hline(
            central_ui.max_rect().x_range(),
            strip.response.rect.max.y + 0.5,
            egui::Stroke::new(1.0, strip_theme.border),
        );
        central_ui.add_space(8.0);
    }
}

/// Renders the centered, scrollable page content with the footer docked at
/// its end, resetting the scroll position when the route changed.
fn render_scrolled_content(
    central_ui: &mut egui::Ui,
    scroll_top: bool,
    route_changed: bool,
    mut footer: Option<FooterFn<'_>>,
    content: impl FnOnce(&mut egui::Ui),
) {
    let spacing = central_ui.responsive_spacing();
    let available = central_ui.available_width();
    let content_width = available.min(spacing.content_max_width);
    let margin = ((available - content_width) * 0.5).max(0.0);
    let inner_width = (content_width - 2.0 * spacing.page_padding).max(0.0);
    let mut scroll = egui::ScrollArea::vertical().auto_shrink([false; 2]);
    if scroll_top || route_changed {
        scroll = scroll.vertical_scroll_offset(0.0);
    }
    let _ = scroll.show(central_ui, |scroll_ui| {
        scroll_ui.add_space(spacing.page_padding);
        let _ = scroll_ui.horizontal_top(|h_ui| {
            h_ui.add_space(margin);
            h_ui.add_space(spacing.page_padding);
            let _ = h_ui.vertical(|v_ui| {
                v_ui.set_max_width(inner_width);
                content(v_ui);
                if let Some(f) = footer.take() {
                    v_ui.add_space(16.0);
                    let _ = crate::widgets::footer::widget::Footer::new().show(v_ui, f);
                    v_ui.add_space(12.0);
                } else {
                    v_ui.add_space(48.0);
                }
            });
            h_ui.add_space(spacing.page_padding);
            h_ui.add_space(margin);
        });
    });
}