Skip to main content

euv_example/pages/shell/
fn.rs

1use super::*;
2
3/// Registers every `SHOWCASE_ROUTES` entry lazily onto `router` using typed `#[component(retention = Freeze)]` pages.
4///
5/// # Arguments
6///
7/// - `&ShowcaseState` - Shared reactive showcase state.
8pub(crate) fn ensure_showcase_routes_registered(state: &ShowcaseState) {
9    if state.get_router_ready().replace(true) {
10        return;
11    }
12    let mut router: EuvRouter = state.get_router().clone();
13    for spec in SHOWCASE_ROUTES.iter() {
14        let path: &'static str = spec.get_path();
15        let st: ShowcaseState = state.clone();
16        router = router.route_component(path, spec.get_label(), move |_: &EuvRouteMatch| {
17            let tok: ThemeTokens = untracked(|| st.get_theme().get_tokens().get());
18            ShowcasePage::new(path, st.clone(), tok)
19        });
20    }
21    let _: EuvRouter = router;
22}
23
24/// Lazily mounts the global Command Palette `EuvCommand` + `EuvModal` subtree on first open so Frame 1 mounts zero hidden portals.
25///
26/// # Arguments
27///
28/// - `&ShowcaseState` - Shared reactive showcase state.
29/// - `ThemeTokens` - Active design tokens at first open.
30///
31/// # Returns
32///
33/// - `NodeId` - Mounted `EuvModal` handle with selection and in-place theme-remap scopes attached.
34pub(crate) fn mount_lazy_cmd_palette_modal(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
35    let cmd_open: Signal<bool> = state.get_cmd_palette_open();
36    let cmd_query: Signal<String> = state.get_cmd_palette_query();
37    let mut cmd_items: Vec<String> = SHOWCASE_ROUTES
38        .iter()
39        .map(|spec: &ShowcaseRouteSpec| {
40            format!("Go to {} ({})", spec.get_label(), spec.get_section())
41        })
42        .collect();
43    cmd_items.push(CMD_ITEM_TOGGLE_MODE.to_string());
44    let cmd_sel: Signal<Option<usize>> = Signal::new(None);
45    let cmd_route: Signal<String> = state.get_route();
46    let cmd_state: ShowcaseState = state.clone();
47    let cmd_list: NodeId = view! {
48        EuvCommand {
49            items: cmd_items
50            selected: cmd_sel
51            tokens: tokens
52            query: cmd_query
53            placeholder: CMD_PLACEHOLDER
54        }
55    };
56    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
57        Effect::new(move || {
58            if let Some(idx) = cmd_sel.get() {
59                match SHOWCASE_ROUTES.get(idx) {
60                    Some(spec) => {
61                        let _: bool = cmd_route.set_if_changed(spec.get_path().to_string());
62                    }
63                    None => {
64                        cmd_state.toggle_theme_mode();
65                    }
66                }
67                let _: bool = cmd_sel.set_if_changed(None);
68                let _: bool = cmd_open.set_if_changed(false);
69            }
70        })
71    });
72    let cmd_modal: NodeId = view! {
73        EuvModal {
74            open: cmd_open
75            title: CMD_MODAL_TITLE.to_string()
76            body: cmd_list
77            tokens: tokens
78        }
79    };
80    let rctx: Context = current_context();
81    let cmd_theme_sig: Memo<ThemeTokens> = state.get_theme().get_tokens();
82    let prev_cmd_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
83    let cmd_theme_ctx: Context = rctx.clone();
84    let (cmd_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
85        Effect::new(move || {
86            let next_tok: ThemeTokens = cmd_theme_sig.get();
87            let old_tok: ThemeTokens = prev_cmd_tok.replace(next_tok);
88            if old_tok == next_tok {
89                return;
90            }
91            cmd_theme_ctx.get_scene().with_write(
92                |tree: &mut SceneTree| {
93                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
94                },
95                (),
96            );
97        })
98    });
99    rctx.get_scene().with_write(
100        |tree: &mut SceneTree| {
101            tree.attach_scope(cmd_modal, cmd_scope);
102            tree.attach_scope(cmd_modal, cmd_theme_scope);
103        },
104        (),
105    );
106    cmd_modal
107}
108
109/// Mounts the fully reactive showcase application shell with lazy `PageRetention::Freeze` routing and cross-component events.
110///
111/// # Arguments
112///
113/// - `&ShowcaseState` - Reactive showcase state.
114///
115/// # Returns
116///
117/// - `NodeId` - Mounted reactive root container handle.
118pub fn mount_showcase_root(state: &ShowcaseState) -> NodeId {
119    provide_theme(state.get_theme().clone());
120    ensure_showcase_routes_registered(state);
121    let global_banner: Signal<ShowcaseGlobalBanner> =
122        state!(global ShowcaseGlobalBanner = ShowcaseGlobalBanner::default());
123    let state_c: ShowcaseState = state.clone();
124    let bg_state: ShowcaseState = state.clone();
125    let fg_state: ShowcaseState = state.clone();
126    let sys_state: ShowcaseState = state.clone();
127    let sys_log_sig: Signal<Vec<String>> = state.get_system_event_log();
128    let sys_count_sig: Signal<u32> = state.get_system_event_count();
129    let (ev_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
130        let _: SystemEventSubscription = on_background(move || {
131            bg_state.freeze_for_background();
132        });
133        let _: SystemEventSubscription = on_foreground(move || {
134            fg_state.restore_from_foreground();
135        });
136        let _: SystemEventSubscription = on_system_event(move |ev: &SystemEvent| {
137            if matches!(ev, SystemEvent::Terminate) {
138                sys_state.freeze_for_background();
139                let _: usize = EuvOverlayStack::dismiss_all();
140                reset_fullscreen_state();
141            } else if matches!(ev, SystemEvent::Foreground) {
142                sys_state.restore_from_foreground();
143            }
144            let next_seq: u32 = sys_count_sig.get_untracked().saturating_add(1);
145            let _: bool = sys_count_sig.set(next_seq);
146            let entry: String = format!("#{next_seq}: {ev:?}");
147            let _: bool = sys_log_sig.update(|items: &mut Vec<String>| {
148                items.insert(0, entry);
149                if items.len() > SYS_EVENTS_LOG_LIMIT {
150                    items.truncate(SYS_EVENTS_LOG_LIMIT);
151                }
152            });
153        });
154        on!(ShowcasePulseEvent => move |ev: &ShowcasePulseEvent| {
155            let src: String = ev.get_source().clone();
156            let _: bool = global_banner.update(|b: &mut ShowcaseGlobalBanner| {
157                let next_pulses: u32 = b.get_pulses().saturating_add(1);
158                b.set_pulses(next_pulses);
159                b.set_last_source(src);
160            });
161        })
162    });
163    let build_root_children = move || -> Vec<NodeId> {
164        let tokens: ThemeTokens = untracked(|| state_c.get_theme().get_tokens().get());
165        let hub: DynamicUpdateHub = state_c.get_dynamic_hub().clone();
166        let _: u64 = hub.routes_signal().get();
167        let cmd_open: Signal<bool> = state_c.get_cmd_palette_open();
168        let cmd_slot: NodeId = view! {
169            column {
170                style: {
171                    position: Position::Absolute
172                    width: Length::Px(0.0)
173                    height: Length::Px(0.0)
174                }
175            }
176        };
177        let cmd_mounted: Rc<Cell<bool>> = Rc::new(Cell::new(false));
178        let cmd_state_lazy: ShowcaseState = state_c.clone();
179        let rctx: Context = current_context();
180        let cmd_ctx: Context = rctx.clone();
181        let (cmd_lazy_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
182            Effect::new(move || {
183                if !cmd_open.get() || cmd_mounted.get() {
184                    return;
185                }
186                cmd_mounted.set(true);
187                let live_tok: ThemeTokens =
188                    untracked(|| cmd_state_lazy.get_theme().get_tokens().get());
189                let modal_node: NodeId = with_context(cmd_ctx.clone(), || {
190                    mount_lazy_cmd_palette_modal(&cmd_state_lazy, live_tok)
191                });
192                cmd_ctx.get_scene().with_write(
193                    |tree: &mut SceneTree| {
194                        let dirty_mask: u16 = DIRTY_CHILDREN + DIRTY_LAYOUT + DIRTY_PAINT;
195                        tree.append_child(cmd_slot, modal_node);
196                        tree.mark_dirty(cmd_slot, dirty_mask);
197                    },
198                    (),
199                );
200            })
201        });
202        rctx.get_scene().with_write(
203            |tree: &mut SceneTree| {
204                tree.attach_scope(cmd_slot, cmd_lazy_scope);
205            },
206            (),
207        );
208        let state_shell: ShowcaseState = state_c.clone();
209        let hub_shell: DynamicUpdateHub = hub.clone();
210        let render_native_shell = move || -> NodeId {
211            let shell_node: NodeId = mount_native_app_shell(&state_shell, &hub_shell, tokens);
212            shell_node
213        };
214        let global_wasm_slot: NodeId = view! {
215            slot {
216                id: WASM_GLOBAL_ROOT_SLOT
217                hub: hub
218                style: c_full_col()
219                fallback: render_native_shell
220            }
221        };
222        vec![global_wasm_slot, cmd_slot]
223    };
224    let root_node: NodeId = view! {
225        column {
226            style: {
227                width: Length::Percent(100.0)
228                height: Length::Percent(100.0)
229            }
230            bind_children: build_root_children
231        }
232    };
233    let root_ctx: Context = current_context();
234    root_ctx.get_scene().with_write(
235        |tree: &mut SceneTree| {
236            tree.attach_scope(root_node, ev_scope);
237        },
238        (),
239    );
240    root_node
241}
242
243/// Mounts the native `EuvAppShell` containing the sectioned sidebar drawer, bottom navigation bar, swipe router outlet, and uniform topbar actions.
244///
245/// # Arguments
246///
247/// - `&ShowcaseState` - Reactive showcase state.
248/// - `&DynamicUpdateHub` - Active OTA dynamic route hub.
249/// - `ThemeTokens` - Active design tokens at mount time.
250///
251/// # Returns
252///
253/// - `NodeId` - Mounted `EuvAppShell` root handle.
254pub(crate) fn mount_native_app_shell(
255    state_shell: &ShowcaseState,
256    hub_shell: &DynamicUpdateHub,
257    tokens: ThemeTokens,
258) -> NodeId {
259    let mut nav_items: Vec<EuvNavItem> = ShowcaseState::nav_items();
260    for dyn_route in hub_shell.registered_routes().into_iter() {
261        if dyn_route == ROUTE_DYNAMIC_PANEL {
262            continue;
263        }
264        if !nav_items
265            .iter()
266            .any(|item: &EuvNavItem| item.get_path().as_str() == dyn_route.as_str())
267        {
268            let label: String = hub_shell
269                .page_title(&dyn_route)
270                .filter(|t: &String| !t.is_empty())
271                .unwrap_or_else(|| dyn_route.clone());
272            nav_items.push(EuvNavItem::new(dyn_route, label).section(NAV_SEC_RUNTIME));
273        }
274    }
275    let nav: NodeId = view! {
276        EuvSidebarNav {
277            items: nav_items
278            active_route: state_shell.get_route()
279            tokens: tokens
280        }
281    };
282    let bottom_items: Vec<EuvNavItem> = vec![
283        EuvNavItem::new(ROUTE_OVERVIEW.to_string(), BNAV_HOME_LABEL.to_string())
284            .section(BNAV_HOME_ICON),
285        EuvNavItem::new(ROUTE_MARKDOWN.to_string(), BNAV_DOCS_LABEL.to_string())
286            .section(BNAV_DOCS_ICON),
287        EuvNavItem::new(ROUTE_LAB.to_string(), BNAV_CASES_LABEL.to_string())
288            .section(BNAV_CASES_ICON),
289        EuvNavItem::new(ROUTE_STRESS.to_string(), BNAV_STRESS_LABEL.to_string())
290            .section(BNAV_STRESS_ICON),
291        EuvNavItem::new(ROUTE_GAME_3D.to_string(), BNAV_3D_LABEL.to_string()).section(BNAV_3D_ICON),
292    ];
293    let bottom_nav: NodeId = view! {
294        EuvBottomNav {
295            items: bottom_items
296            active_route: state_shell.get_route()
297            tokens: tokens
298        }
299    };
300    let swipe_order: Vec<String> = showcase_swipe_order();
301    let state_for_outlet: ShowcaseState = state_shell.clone();
302    let router: EuvRouter = state_shell
303        .get_router()
304        .clone()
305        .with_dynamic_hub(hub_shell.clone());
306    let route_sig: Signal<String> = state_shell.get_route();
307    let cur_target: String = route_sig.get_untracked();
308    if router.get_current_path().get_untracked() != cur_target {
309        router.replace(&cur_target);
310    }
311    let breadcrumb_sig: Signal<String> =
312        Signal::new(ShowcaseState::breadcrumb_for_route(&cur_target));
313    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
314    let router_sync_in: EuvRouter = router.clone();
315    let router_path_sig: Signal<String> = router.get_current_path();
316    let sctx: Context = current_context();
317    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
318        let _: Effect = Effect::new(move || {
319            let target: String = route_sig.get();
320            if router_sync_in.get_current_path().get_untracked() != target {
321                router_sync_in.push(&target);
322            }
323            let _: bool =
324                breadcrumb_sig.set_if_changed(ShowcaseState::breadcrumb_for_route(&target));
325        });
326        Effect::new(move || {
327            let rp: String = router_path_sig.get();
328            if route_sig.get_untracked() != rp {
329                let _: bool = route_sig.set_if_changed(rp);
330            }
331        })
332    });
333    let page_node: NodeId = router
334        .outlet(move |matched: &EuvRouteMatch| {
335            let tok: ThemeTokens = untracked(|| state_for_outlet.get_theme().get_tokens().get());
336            mount_route_by_name(matched.get_path(), &state_for_outlet, tok)
337        })
338        .with_theme(state_shell.get_theme().clone())
339        .with_page_padding(page_pad_sig)
340        .with_route_order(swipe_order.clone())
341        .with_double_back_exit(true)
342        .mount();
343    sctx.get_scene().with_write(
344        |tree: &mut SceneTree| {
345            tree.attach_scope(page_node, sync_scope);
346        },
347        (),
348    );
349    let top_actions: NodeId = mount_topbar_actions(state_shell, tokens);
350    let mobile_actions: NodeId = mount_topbar_actions(state_shell, tokens);
351    view! {
352        EuvAppShell {
353            brand: SHOWCASE_BRAND.to_string()
354            sidebar: nav
355            main_content: page_node
356            tokens: tokens
357            theme: state_shell.get_theme().clone()
358            page_padding: page_pad_sig
359            route: state_shell.get_route()
360            breadcrumb: breadcrumb_sig
361            top_bar_actions: top_actions
362            mobile_header_actions: mobile_actions
363            bottom_nav: bottom_nav
364            swipe_routes: swipe_order
365            show_fps: true
366            auto_hide_chrome_on_scroll: true
367        }
368    }
369}
370
371/// Mounts the showcase page corresponding to the active route in `state`.
372///
373/// # Arguments
374///
375/// - `&ShowcaseState` - Reactive showcase state.
376/// - `ThemeTokens` - Active resolved design tokens.
377///
378/// # Returns
379///
380/// - `NodeId` - Mounted page container handle.
381pub fn mount_active_route(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
382    let route: String = state.get_route().get_untracked();
383    mount_route_by_name(&route, state, tokens)
384}
385
386/// Dispatches a route string to its corresponding declarative showcase page builder.
387///
388/// # Arguments
389///
390/// - `&str` - Active route path.
391/// - `&ShowcaseState` - Reactive showcase state.
392/// - `ThemeTokens` - Active resolved design tokens.
393///
394/// # Returns
395///
396/// - `NodeId` - Mounted page container handle.
397pub(crate) fn mount_route_by_name(
398    route: &str,
399    state: &ShowcaseState,
400    tokens: ThemeTokens,
401) -> NodeId {
402    let builder: fn(&ShowcaseState, ThemeTokens) -> NodeId = SHOWCASE_ROUTES
403        .iter()
404        .find(|spec: &&ShowcaseRouteSpec| spec.get_path() == route)
405        .map(|spec: &ShowcaseRouteSpec| spec.get_mount())
406        .unwrap_or(mount_overview_page);
407    builder(state, tokens)
408}
409
410/// Builds the horizontal swipe route order: the five bottom-nav destinations first, then every remaining registry route in sidebar order.
411///
412/// # Returns
413///
414/// - `Vec<String>` - Ordered swipe route paths.
415pub(crate) fn showcase_swipe_order() -> Vec<String> {
416    let mut order: Vec<String> = BOTTOM_NAV_ROUTES
417        .iter()
418        .map(|path: &&str| (*path).to_string())
419        .collect();
420    for spec in SHOWCASE_ROUTES.iter() {
421        if !BOTTOM_NAV_ROUTES.contains(&spec.get_path()) {
422            order.push(spec.get_path().to_string());
423        }
424    }
425    order
426}
427
428/// Mounts one uniform topbar action cluster (command palette, scheme cycle, Light/Dark toggle) whose square icon buttons share the shell control-line height and `radius_md`.
429///
430/// # Arguments
431///
432/// - `&ShowcaseState` - Shared reactive showcase state.
433/// - `ThemeTokens` - Active design tokens at mount time.
434///
435/// # Returns
436///
437/// - `NodeId` - Mounted action row handle.
438pub(crate) fn mount_topbar_actions(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
439    let cmd_open: Signal<bool> = state.get_cmd_palette_open();
440    let st_scheme: ShowcaseState = state.clone();
441    let st_mode: ShowcaseState = state.clone();
442    let icon_btn_style = move || -> Style {
443        let live_tok: ThemeTokens = use_live_tokens(tokens);
444        let live_p: ThemePalette = live_tok.get_palette();
445        let live_g: ThemeGeometry = live_tok.get_geometry();
446        Style::default()
447            .row()
448            .width(Length::Px(TOPBAR_CONTROL_SIZE))
449            .height(Length::Px(TOPBAR_CONTROL_SIZE))
450            .flex_shrink(0.0)
451            .justify(JustifyContent::Center)
452            .align(AlignItems::Center)
453            .background(live_p.get_background())
454            .border(live_g.get_border_width(), live_p.get_border())
455            .radius(live_g.get_radius_md())
456            .cursor(CursorIcon::Pointer)
457    };
458    let paint_search = move |bounds: Rect, dl: &mut DisplayList| {
459        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
460        draw_euv_icon(EuvIconName::Search, bounds, dl, live_p.get_foreground());
461    };
462    let paint_scheme = move |bounds: Rect, dl: &mut DisplayList| {
463        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
464        draw_euv_icon(EuvIconName::Palette, bounds, dl, live_p.get_primary());
465    };
466    let paint_mode = move |bounds: Rect, dl: &mut DisplayList| {
467        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
468        let glyph: EuvIconName = match live_tok.get_mode() {
469            ThemeMode::Dark => EuvIconName::Sun,
470            ThemeMode::Light => EuvIconName::Moon,
471        };
472        draw_euv_icon(glyph, bounds, dl, live_tok.get_palette().get_foreground());
473    };
474    let on_open_cmd = move |_: &UiEvent| {
475        let _: bool = cmd_open.set_if_changed(true);
476    };
477    let on_cycle_scheme = move |_: &UiEvent| {
478        st_scheme.next_scheme();
479    };
480    let on_toggle_mode = move |_: &UiEvent| {
481        st_mode.toggle_theme_mode();
482    };
483    view! {
484        row {
485            style: {
486                gap: SPACE_XS
487                align: AlignItems::Center
488            }
489            row {
490                bind_style: icon_btn_style
491                role: A11yRole::Button
492                a11y_label: BTN_SEARCH_A11Y.to_string()
493                on_click: on_open_cmd
494                canvas {
495                    style: {
496                        width: Length::Px(TOPBAR_ICON_SIZE)
497                        height: Length::Px(TOPBAR_ICON_SIZE)
498                    }
499                    painter: paint_search
500                }
501            }
502            row {
503                bind_style: icon_btn_style
504                role: A11yRole::Button
505                a11y_label: BTN_SCHEME_A11Y.to_string()
506                on_click: on_cycle_scheme
507                canvas {
508                    style: {
509                        width: Length::Px(TOPBAR_ICON_SIZE)
510                        height: Length::Px(TOPBAR_ICON_SIZE)
511                    }
512                    painter: paint_scheme
513                }
514            }
515            row {
516                bind_style: icon_btn_style
517                role: A11yRole::Button
518                a11y_label: BTN_MODE_A11Y.to_string()
519                on_click: on_toggle_mode
520                canvas {
521                    style: {
522                        width: Length::Px(TOPBAR_ICON_SIZE)
523                        height: Length::Px(TOPBAR_ICON_SIZE)
524                    }
525                    painter: paint_mode
526                }
527            }
528        }
529    }
530}