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            frameless: true
55        }
56    };
57    let (cmd_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
58        Effect::new(move || {
59            if let Some(idx) = cmd_sel.get() {
60                match SHOWCASE_ROUTES.get(idx) {
61                    Some(spec) => {
62                        let _: bool = cmd_route.set_if_changed(spec.get_path().to_string());
63                    }
64                    None => {
65                        cmd_state.toggle_theme_mode();
66                    }
67                }
68                let _: bool = cmd_sel.set_if_changed(None);
69                let _: bool = cmd_open.set_if_changed(false);
70            }
71        })
72    });
73    let cmd_modal: NodeId = view! {
74        EuvModal {
75            open: cmd_open
76            title: CMD_MODAL_TITLE.to_string()
77            body: cmd_list
78            tokens: tokens
79        }
80    };
81    let rctx: Context = current_context();
82    let cmd_theme_sig: Memo<ThemeTokens> = state.get_theme().get_tokens();
83    let prev_cmd_tok: Rc<Cell<ThemeTokens>> = Rc::new(Cell::new(tokens));
84    let cmd_theme_ctx: Context = rctx.clone();
85    let (cmd_theme_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
86        Effect::new(move || {
87            let next_tok: ThemeTokens = cmd_theme_sig.get();
88            let old_tok: ThemeTokens = prev_cmd_tok.replace(next_tok);
89            if old_tok == next_tok {
90                return;
91            }
92            cmd_theme_ctx.get_scene().with_write(
93                |tree: &mut SceneTree| {
94                    remap_subtree_theme_in_place(tree, cmd_modal, old_tok, next_tok);
95                },
96                (),
97            );
98        })
99    });
100    rctx.get_scene().with_write(
101        |tree: &mut SceneTree| {
102            tree.attach_scope(cmd_modal, cmd_scope);
103            tree.attach_scope(cmd_modal, cmd_theme_scope);
104        },
105        (),
106    );
107    cmd_modal
108}
109
110/// Mounts the fully reactive showcase application shell with lazy `PageRetention::Freeze` routing and cross-component events.
111///
112/// # Arguments
113///
114/// - `&ShowcaseState` - Reactive showcase state.
115///
116/// # Returns
117///
118/// - `NodeId` - Mounted reactive root container handle.
119pub fn mount_showcase_root(state: &ShowcaseState) -> NodeId {
120    provide_theme(state.get_theme().clone());
121    ensure_showcase_routes_registered(state);
122    let global_banner: Signal<ShowcaseGlobalBanner> =
123        state!(global ShowcaseGlobalBanner = ShowcaseGlobalBanner::default());
124    let state_c: ShowcaseState = state.clone();
125    let bg_state: ShowcaseState = state.clone();
126    let fg_state: ShowcaseState = state.clone();
127    let sys_state: ShowcaseState = state.clone();
128    let sys_log_sig: Signal<Vec<String>> = state.get_system_event_log();
129    let sys_count_sig: Signal<u32> = state.get_system_event_count();
130    let (ev_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
131        let _: SystemEventSubscription = on_background(move || {
132            bg_state.freeze_for_background();
133        });
134        let _: SystemEventSubscription = on_foreground(move || {
135            fg_state.restore_from_foreground();
136        });
137        let _: SystemEventSubscription = on_system_event(move |ev: &SystemEvent| {
138            if matches!(ev, SystemEvent::Terminate) {
139                sys_state.freeze_for_background();
140                let _: usize = EuvOverlayStack::dismiss_all();
141                reset_fullscreen_state();
142            } else if matches!(ev, SystemEvent::Foreground) {
143                sys_state.restore_from_foreground();
144            } else if let SystemEvent::DeepLink(raw_uri) = ev {
145                let stripped: &str = raw_uri
146                    .trim()
147                    .strip_prefix(DEEP_LINK_SCHEME_PREFIX)
148                    .unwrap_or(raw_uri.trim());
149                let (path_part, query_part): (&str, &str) = stripped
150                    .split('#')
151                    .next()
152                    .unwrap_or("")
153                    .split_once('?')
154                    .unwrap_or((stripped.split('#').next().unwrap_or(""), ""));
155                let trimmed: &str = path_part.trim_matches('/');
156                if trimmed.eq_ignore_ascii_case(DEEP_LINK_HOT_UPDATE_HOST) {
157                    if apply_hot_update_deep_link(sys_state.get_dynamic_hub(), query_part) {
158                        let _: bool = sys_state
159                            .get_route()
160                            .set_if_changed(ROUTE_DYNAMIC.to_string());
161                    }
162                } else {
163                    let candidate: String = if trimmed.is_empty() {
164                        ROUTE_OVERVIEW.to_string()
165                    } else {
166                        format!("/{trimmed}")
167                    };
168                    if SHOWCASE_ROUTES
169                        .iter()
170                        .any(|spec: &ShowcaseRouteSpec| spec.get_path() == candidate.as_str())
171                    {
172                        let _: bool = sys_state.get_route().set_if_changed(candidate);
173                    }
174                }
175            }
176            let next_seq: u32 = sys_count_sig.get_untracked().saturating_add(1);
177            let _: bool = sys_count_sig.set(next_seq);
178            let entry: String = format!("#{next_seq}: {ev:?}");
179            let _: bool = sys_log_sig.update(|items: &mut Vec<String>| {
180                items.insert(0, entry);
181                if items.len() > SYS_EVENTS_LOG_LIMIT {
182                    items.truncate(SYS_EVENTS_LOG_LIMIT);
183                }
184            });
185        });
186        on!(ShowcasePulseEvent => move |ev: &ShowcasePulseEvent| {
187            let src: String = ev.get_source().clone();
188            let _: bool = global_banner.update(|b: &mut ShowcaseGlobalBanner| {
189                let next_pulses: u32 = b.get_pulses().saturating_add(1);
190                b.set_pulses(next_pulses);
191                b.set_last_source(src);
192            });
193        })
194    });
195    let build_root_children = move || -> Vec<NodeId> {
196        let tokens: ThemeTokens = untracked(|| state_c.get_theme().get_tokens().get());
197        let hub: DynamicUpdateHub = state_c.get_dynamic_hub().clone();
198        let cmd_open: Signal<bool> = state_c.get_cmd_palette_open();
199        let cmd_slot: NodeId = view! {
200            column {
201                style: {
202                    position: Position::Absolute
203                    width: Length::Px(0.0)
204                    height: Length::Px(0.0)
205                }
206            }
207        };
208        let cmd_mounted: Rc<Cell<bool>> = Rc::new(Cell::new(false));
209        let cmd_state_lazy: ShowcaseState = state_c.clone();
210        let rctx: Context = current_context();
211        let cmd_ctx: Context = rctx.clone();
212        let (cmd_lazy_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
213            Effect::new(move || {
214                if !cmd_open.get() || cmd_mounted.get() {
215                    return;
216                }
217                cmd_mounted.set(true);
218                let live_tok: ThemeTokens =
219                    untracked(|| cmd_state_lazy.get_theme().get_tokens().get());
220                let modal_node: NodeId = with_context(cmd_ctx.clone(), || {
221                    mount_lazy_cmd_palette_modal(&cmd_state_lazy, live_tok)
222                });
223                cmd_ctx.get_scene().with_write(
224                    |tree: &mut SceneTree| {
225                        let dirty_mask: u16 = DIRTY_CHILDREN + DIRTY_LAYOUT + DIRTY_PAINT;
226                        tree.append_child(cmd_slot, modal_node);
227                        tree.mark_dirty(cmd_slot, dirty_mask);
228                    },
229                    (),
230                );
231            })
232        });
233        rctx.get_scene().with_write(
234            |tree: &mut SceneTree| {
235                tree.attach_scope(cmd_slot, cmd_lazy_scope);
236            },
237            (),
238        );
239        let state_shell: ShowcaseState = state_c.clone();
240        let hub_shell: DynamicUpdateHub = hub.clone();
241        let render_native_shell = move || -> NodeId {
242            let shell_node: NodeId = mount_native_app_shell(&state_shell, &hub_shell, tokens);
243            shell_node
244        };
245        let global_wasm_slot: NodeId = view! {
246            slot {
247                id: WASM_GLOBAL_ROOT_SLOT
248                hub: hub
249                style: c_full_col()
250                fallback: render_native_shell
251            }
252        };
253        vec![global_wasm_slot, cmd_slot]
254    };
255    let root_node: NodeId = view! {
256        column {
257            style: {
258                width: Length::Percent(100.0)
259                height: Length::Percent(100.0)
260            }
261            bind_children: build_root_children
262        }
263    };
264    let root_ctx: Context = current_context();
265    root_ctx.get_scene().with_write(
266        |tree: &mut SceneTree| {
267            tree.attach_scope(root_node, ev_scope);
268        },
269        (),
270    );
271    root_node
272}
273
274/// Mounts the native dual-mode `EuvAppShell` (Desktop `>= 960px`: full-width topbar + permanent left sidebar + zero bottom nav; Mobile `< 960px`: compact topbar + overlay drawer + floating bottom navigation bar).
275///
276/// # Arguments
277///
278/// - `&ShowcaseState` - Reactive showcase state.
279/// - `&DynamicUpdateHub` - Active OTA dynamic route hub.
280/// - `ThemeTokens` - Active design tokens at mount time.
281///
282/// # Returns
283///
284/// - `NodeId` - Mounted `EuvAppShell` root handle.
285pub(crate) fn mount_native_app_shell(
286    state_shell: &ShowcaseState,
287    hub_shell: &DynamicUpdateHub,
288    tokens: ThemeTokens,
289) -> NodeId {
290    let hub_sidebar: DynamicUpdateHub = hub_shell.clone();
291    let route_sidebar: Signal<String> = state_shell.get_route();
292    let dynamic_route_list: Memo<Vec<(String, String)>> = Memo::new(move || {
293        let _: u64 = hub_sidebar.routes_signal().get();
294        hub_sidebar
295            .registered_routes()
296            .into_iter()
297            .filter(|r: &String| r != ROUTE_DYNAMIC_PANEL)
298            .map(|r: String| {
299                let label: String = hub_sidebar
300                    .page_title(&r)
301                    .filter(|t: &String| !t.is_empty())
302                    .unwrap_or_else(|| r.clone());
303                (r, label)
304            })
305            .collect()
306    });
307    let build_sidebar_children = move || -> Vec<NodeId> {
308        let mut nav_items: Vec<EuvNavItem> = ShowcaseState::nav_items();
309        for (dyn_route, label) in dynamic_route_list.get().into_iter() {
310            if !nav_items
311                .iter()
312                .any(|item: &EuvNavItem| item.get_path().as_str() == dyn_route.as_str())
313            {
314                nav_items.push(EuvNavItem::new(dyn_route, label).section(NAV_SEC_RUNTIME));
315            }
316        }
317        let sidebar_node: NodeId = view! {
318            EuvSidebarNav {
319                items: nav_items
320                active_route: route_sidebar
321                tokens: tokens
322            }
323        };
324        vec![sidebar_node]
325    };
326    let nav: NodeId = view! {
327        column {
328            style: {
329                width: Length::Percent(100.0)
330            }
331            bind_children: build_sidebar_children
332        }
333    };
334    let bottom_items: Vec<EuvNavItem> = vec![
335        EuvNavItem::new(ROUTE_OVERVIEW.to_string(), BNAV_HOME_LABEL.to_string())
336            .section(BNAV_HOME_ICON),
337        EuvNavItem::new(ROUTE_MARKDOWN.to_string(), BNAV_DOCS_LABEL.to_string())
338            .section(BNAV_DOCS_ICON),
339        EuvNavItem::new(ROUTE_LAB.to_string(), BNAV_CASES_LABEL.to_string())
340            .section(BNAV_CASES_ICON),
341        EuvNavItem::new(ROUTE_STRESS.to_string(), BNAV_STRESS_LABEL.to_string())
342            .section(BNAV_STRESS_ICON),
343        EuvNavItem::new(ROUTE_GAME_3D.to_string(), BNAV_3D_LABEL.to_string()).section(BNAV_3D_ICON),
344    ];
345    let bottom_nav: NodeId = view! {
346        EuvBottomNav {
347            items: bottom_items
348            active_route: state_shell.get_route()
349            tokens: tokens
350        }
351    };
352    let swipe_order: Vec<String> = showcase_swipe_order();
353    let state_for_outlet: ShowcaseState = state_shell.clone();
354    let router: EuvRouter = state_shell
355        .get_router()
356        .clone()
357        .with_dynamic_hub(hub_shell.clone());
358    let route_sig: Signal<String> = state_shell.get_route();
359    let cur_target: String = route_sig.get_untracked();
360    if router.get_current_path().get_untracked() != cur_target {
361        router.replace(&cur_target);
362    }
363    let breadcrumb_sig: Signal<String> =
364        Signal::new(ShowcaseState::breadcrumb_for_route(&cur_target));
365    let page_pad_sig: Signal<Edges> = Signal::new(Edges::all(SPACE_LG));
366    let router_sync_in: EuvRouter = router.clone();
367    let router_path_sig: Signal<String> = router.get_current_path();
368    let reduced_motion_sig: Signal<bool> = state_shell.get_reduced_motion();
369    let sctx: Context = current_context();
370    let (sync_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
371        let _: Effect = Effect::new(move || {
372            let target: String = route_sig.get();
373            if router_sync_in.get_current_path().get_untracked() != target {
374                router_sync_in.push(&target);
375            }
376            let _: bool =
377                breadcrumb_sig.set_if_changed(ShowcaseState::breadcrumb_for_route(&target));
378        });
379        let _: Effect = Effect::new(move || {
380            set_reduced_motion(reduced_motion_sig.get());
381        });
382        Effect::new(move || {
383            let rp: String = router_path_sig.get();
384            if route_sig.get_untracked() != rp {
385                let _: bool = route_sig.set_if_changed(rp);
386            }
387        })
388    });
389    let page_node: NodeId = router
390        .outlet(move |matched: &EuvRouteMatch| {
391            let tok: ThemeTokens = untracked(|| state_for_outlet.get_theme().get_tokens().get());
392            mount_route_by_name(matched.get_path(), &state_for_outlet, tok)
393        })
394        .with_theme(state_shell.get_theme().clone())
395        .with_page_padding(page_pad_sig)
396        .with_route_order(swipe_order.clone())
397        .with_double_back_exit(true)
398        .mount();
399    sctx.get_scene().with_write(
400        |tree: &mut SceneTree| {
401            tree.attach_scope(page_node, sync_scope);
402        },
403        (),
404    );
405    let scheme_menu_open: Signal<bool> = Signal::new(false);
406    let (top_actions, palette_btn_desk): (NodeId, NodeId) =
407        mount_topbar_actions(state_shell, scheme_menu_open, tokens, true);
408    let (mobile_actions, palette_btn_mob): (NodeId, NodeId) =
409        mount_topbar_actions(state_shell, scheme_menu_open, tokens, false);
410    let shell_node: NodeId = view! {
411        EuvAppShell {
412            brand: SHOWCASE_BRAND.to_string()
413            sidebar: nav
414            main_content: page_node
415            tokens: tokens
416            theme: state_shell.get_theme().clone()
417            page_padding: page_pad_sig
418            route: state_shell.get_route()
419            breadcrumb: breadcrumb_sig
420            top_bar_actions: top_actions
421            mobile_header_actions: mobile_actions
422            bottom_nav: bottom_nav
423            swipe_routes: swipe_order
424            swipe_routes_enabled: state_shell.get_swipe_routing()
425            show_fps: true
426            show_fps_signal: state_shell.get_show_fps_hud()
427            auto_hide_chrome_on_scroll: true
428            auto_hide_chrome_signal: state_shell.get_auto_hide_chrome()
429        }
430    };
431    let scheme_portal: NodeId = mount_topbar_scheme_dropdown_portal(
432        state_shell,
433        scheme_menu_open,
434        tokens,
435        vec![palette_btn_desk, palette_btn_mob],
436    );
437    view! {
438        column {
439            style: {
440                width: Length::Percent(100.0)
441                height: Length::Percent(100.0)
442            }
443            { shell_node }
444            { scheme_portal }
445        }
446    }
447}
448
449/// Mounts the showcase page corresponding to the active route in `state`.
450///
451/// # Arguments
452///
453/// - `&ShowcaseState` - Reactive showcase state.
454/// - `ThemeTokens` - Active resolved design tokens.
455///
456/// # Returns
457///
458/// - `NodeId` - Mounted page container handle.
459pub fn mount_active_route(state: &ShowcaseState, tokens: ThemeTokens) -> NodeId {
460    let route: String = state.get_route().get_untracked();
461    mount_route_by_name(&route, state, tokens)
462}
463
464/// Dispatches a route string to its corresponding declarative showcase page builder.
465///
466/// # Arguments
467///
468/// - `&str` - Active route path.
469/// - `&ShowcaseState` - Reactive showcase state.
470/// - `ThemeTokens` - Active resolved design tokens.
471///
472/// # Returns
473///
474/// - `NodeId` - Mounted page container handle.
475pub(crate) fn mount_route_by_name(
476    route: &str,
477    state: &ShowcaseState,
478    tokens: ThemeTokens,
479) -> NodeId {
480    let builder: fn(&ShowcaseState, ThemeTokens) -> NodeId = SHOWCASE_ROUTES
481        .iter()
482        .find(|spec: &&ShowcaseRouteSpec| spec.get_path() == route)
483        .map(|spec: &ShowcaseRouteSpec| spec.get_mount())
484        .unwrap_or(mount_overview_page);
485    builder(state, tokens)
486}
487
488/// Builds the horizontal swipe route order: the five bottom-nav destinations first, then every remaining registry route in sidebar order.
489///
490/// # Returns
491///
492/// - `Vec<String>` - Ordered swipe route paths.
493pub(crate) fn showcase_swipe_order() -> Vec<String> {
494    let mut order: Vec<String> = BOTTOM_NAV_ROUTES
495        .iter()
496        .map(|path: &&str| (*path).to_string())
497        .collect();
498    for spec in SHOWCASE_ROUTES.iter() {
499        if !BOTTOM_NAV_ROUTES.contains(&spec.get_path()) {
500            order.push(spec.get_path().to_string());
501        }
502    }
503    order
504}
505
506/// Computes normalized 24x24 viewbox origin, unit scale, and Lucide-grade stroke width centered inside `bounds`.
507///
508/// # Arguments
509///
510/// - `Rect` - Target logical bounding box.
511///
512/// # Returns
513///
514/// - `(f32, f32, f32, f32)` - Tuple `(ox, oy, u, stroke_width)`.
515pub(crate) fn topbar_icon_basis(bounds: Rect) -> (f32, f32, f32, f32) {
516    let w: f32 = bounds.get_width().max(8.0);
517    let h: f32 = bounds.get_height().max(8.0);
518    let side: f32 = w.min(h);
519    let ox: f32 = bounds.get_x() + (w - side) * 0.5;
520    let oy: f32 = bounds.get_y() + (h - side) * 0.5;
521    let u: f32 = side / 24.0;
522    let sw: f32 = (1.75 * u).clamp(1.2, 2.0);
523    (ox, oy, u, sw)
524}
525
526/// Emits an anti-aliased line segment with precision rounded endcaps into `dl`.
527///
528/// # Arguments
529///
530/// - `&mut DisplayList` - Destination vector draw command list.
531/// - `Point` - Segment start point.
532/// - `Point` - Segment end point.
533/// - `Color` - Stroke color.
534/// - `f32` - Stroke width in logical pixels.
535pub(crate) fn push_rounded_stroke(
536    dl: &mut DisplayList,
537    from: Point,
538    to: Point,
539    color: Color,
540    width: f32,
541) {
542    dl.push(DrawCommand::Line {
543        from,
544        to,
545        color,
546        width,
547    });
548}
549
550/// Renders a Lucide-grade 24x24 search magnifying glass icon into `dl`.
551///
552/// # Arguments
553///
554/// - `Rect` - Target logical bounding box.
555/// - `&mut DisplayList` - Destination vector draw command list.
556/// - `Color` - Foreground stroke color.
557pub(crate) fn draw_topbar_search_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
558    let (ox, oy, u, sw): (f32, f32, f32, f32) = topbar_icon_basis(bounds);
559    let lens_d: f32 = 13.6 * u;
560    dl.push(DrawCommand::FillRoundedRect {
561        rect: Rect::new(ox + 4.0 * u, oy + 4.0 * u, lens_d, lens_d),
562        color: COLOR_TRANSPARENT,
563        radius: CornerRadius::all(RADIUS_PILL),
564        border: Border::new(sw, color),
565    });
566    push_rounded_stroke(
567        dl,
568        Point::new(ox + 15.2 * u, oy + 15.2 * u),
569        Point::new(ox + 20.2 * u, oy + 20.2 * u),
570        color,
571        sw,
572    );
573}
574
575/// Renders a Lucide / SF-Symbols grade 24x24 Sun icon (hollow center circle + 8 evenly-spaced rounded rays) into `dl`.
576///
577/// # Arguments
578///
579/// - `Rect` - Target logical bounding box.
580/// - `&mut DisplayList` - Destination vector draw command list.
581/// - `Color` - Foreground stroke color.
582pub(crate) fn draw_theme_sun_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
583    let (ox, oy, u, sw): (f32, f32, f32, f32) = topbar_icon_basis(bounds);
584    let cx: f32 = ox + 12.0 * u;
585    let cy: f32 = oy + 12.0 * u;
586    let core_r: f32 = 4.2 * u;
587    dl.push(DrawCommand::FillRoundedRect {
588        rect: Rect::new(cx - core_r, cy - core_r, core_r * 2.0, core_r * 2.0),
589        color: COLOR_TRANSPARENT,
590        radius: CornerRadius::all(RADIUS_PILL),
591        border: Border::new(sw, color),
592    });
593    let r_in: f32 = 7.0 * u;
594    let r_out: f32 = 9.4 * u;
595    for idx in 0..8_u8 {
596        let ang: f32 = (idx as f32) * (PI * 0.25);
597        let (cos_a, sin_a): (f32, f32) = (ang.cos(), ang.sin());
598        push_rounded_stroke(
599            dl,
600            Point::new(cx + r_in * cos_a, cy + r_in * sin_a),
601            Point::new(cx + r_out * cos_a, cy + r_out * sin_a),
602            color,
603            sw,
604        );
605    }
606}
607
608/// Renders a Lucide `MoonStar`-grade 24x24 crescent moon (exact circle-circle analytical arcs + 4-point star sparkle) into `dl`.
609///
610/// # Arguments
611///
612/// - `Rect` - Target logical bounding box.
613/// - `&mut DisplayList` - Destination vector draw command list.
614/// - `Color` - Foreground stroke color.
615pub(crate) fn draw_theme_moon_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
616    let (ox, oy, u, sw): (f32, f32, f32, f32) = topbar_icon_basis(bounds);
617    let c1x: f32 = 11.8;
618    let c1y: f32 = 12.4;
619    let r1: f32 = 8.2;
620    let c2x: f32 = 16.4;
621    let c2y: f32 = 8.2;
622    let r2: f32 = 6.6;
623    let dx: f32 = c2x - c1x;
624    let dy: f32 = c2y - c1y;
625    let dist: f32 = (dx * dx + dy * dy).sqrt();
626    let base_ang: f32 = dy.atan2(dx);
627    let a: f32 = (r1 * r1 - r2 * r2 + dist * dist) / (2.0 * dist);
628    let alpha1: f32 = (a / r1).clamp(-1.0, 1.0).acos();
629    let theta1_top: f32 = base_ang - alpha1;
630    let theta1_bot: f32 = base_ang + alpha1;
631    let theta1_end: f32 = theta1_top + 2.0 * PI;
632    let p_top_x: f32 = c1x + r1 * theta1_top.cos();
633    let p_top_y: f32 = c1y + r1 * theta1_top.sin();
634    let p_bot_x: f32 = c1x + r1 * theta1_bot.cos();
635    let p_bot_y: f32 = c1y + r1 * theta1_bot.sin();
636    let p_top: Point = Point::new(ox + p_top_x * u, oy + p_top_y * u);
637    let p_bot: Point = Point::new(ox + p_bot_x * u, oy + p_bot_y * u);
638    let outer_steps: usize = 20;
639    let mut prev_outer: Point = p_bot;
640    for step in 1..=outer_steps {
641        let next_pt: Point = if step == outer_steps {
642            p_top
643        } else {
644            let t: f32 = (step as f32) / (outer_steps as f32);
645            let ang: f32 = theta1_bot + (theta1_end - theta1_bot) * t;
646            Point::new(
647                ox + (c1x + r1 * ang.cos()) * u,
648                oy + (c1y + r1 * ang.sin()) * u,
649            )
650        };
651        dl.push(DrawCommand::Line {
652            from: prev_outer,
653            to: next_pt,
654            color,
655            width: sw,
656        });
657        prev_outer = next_pt;
658    }
659    let mut theta2_top: f32 = (p_top_y - c2y).atan2(p_top_x - c2x);
660    let theta2_bot: f32 = (p_bot_y - c2y).atan2(p_bot_x - c2x);
661    if theta2_top < theta2_bot {
662        theta2_top += 2.0 * PI;
663    }
664    let inner_steps: usize = 14;
665    let mut prev_inner: Point = p_top;
666    for step in 1..=inner_steps {
667        let next_pt: Point = if step == inner_steps {
668            p_bot
669        } else {
670            let t: f32 = (step as f32) / (inner_steps as f32);
671            let ang: f32 = theta2_top + (theta2_bot - theta2_top) * t;
672            Point::new(
673                ox + (c2x + r2 * ang.cos()) * u,
674                oy + (c2y + r2 * ang.sin()) * u,
675            )
676        };
677        dl.push(DrawCommand::Line {
678            from: prev_inner,
679            to: next_pt,
680            color,
681            width: sw,
682        });
683        prev_inner = next_pt;
684    }
685    let star_x: f32 = ox + 17.8 * u;
686    let star_y: f32 = oy + 6.4 * u;
687    let star_arm: f32 = 2.1 * u;
688    let star_sw: f32 = (1.45 * u).clamp(1.05, 1.75);
689    push_rounded_stroke(
690        dl,
691        Point::new(star_x, star_y - star_arm),
692        Point::new(star_x, star_y + star_arm),
693        color,
694        star_sw,
695    );
696    push_rounded_stroke(
697        dl,
698        Point::new(star_x - star_arm, star_y),
699        Point::new(star_x + star_arm, star_y),
700        color,
701        star_sw,
702    );
703}
704
705/// Renders a Lucide / SF-Symbols grade 24x24 8-tooth precision cog gear icon with concentric hollow hub into `dl`.
706///
707/// # Arguments
708///
709/// - `Rect` - Target logical bounding box.
710/// - `&mut DisplayList` - Destination vector draw command list.
711/// - `Color` - Foreground stroke color.
712pub(crate) fn draw_gear_icon(bounds: Rect, dl: &mut DisplayList, color: Color) {
713    let (ox, oy, u, sw): (f32, f32, f32, f32) = topbar_icon_basis(bounds);
714    let cx: f32 = ox + 12.0 * u;
715    let cy: f32 = oy + 12.0 * u;
716    let body_r: f32 = 6.3 * u;
717    dl.push(DrawCommand::FillRoundedRect {
718        rect: Rect::new(cx - body_r, cy - body_r, body_r * 2.0, body_r * 2.0),
719        color: COLOR_TRANSPARENT,
720        radius: CornerRadius::all(RADIUS_PILL),
721        border: Border::new(sw, color),
722    });
723    let tooth_in: f32 = 6.0 * u;
724    let tooth_out: f32 = 9.0 * u;
725    let tooth_w: f32 = (sw * 1.35).clamp(1.6, 2.7);
726    for idx in 0..8_u8 {
727        let ang: f32 = (idx as f32) * (PI * 0.25);
728        let (cos_a, sin_a): (f32, f32) = (ang.cos(), ang.sin());
729        dl.push(DrawCommand::Line {
730            from: Point::new(cx + tooth_in * cos_a, cy + tooth_in * sin_a),
731            to: Point::new(cx + tooth_out * cos_a, cy + tooth_out * sin_a),
732            color,
733            width: tooth_w,
734        });
735    }
736    let hole_r: f32 = 2.8 * u;
737    dl.push(DrawCommand::FillRoundedRect {
738        rect: Rect::new(cx - hole_r, cy - hole_r, hole_r * 2.0, hole_r * 2.0),
739        color: COLOR_TRANSPARENT,
740        radius: CornerRadius::all(RADIUS_PILL),
741        border: Border::new(sw, color),
742    });
743}
744
745/// Returns the clean human-readable display name for one of the 17 built-in `DesignScheme` presets.
746///
747/// # Arguments
748///
749/// - `DesignScheme` - Target design scheme variant.
750///
751/// # Returns
752///
753/// - `&'static str` - Human-readable scheme title.
754pub(crate) fn scheme_display_label(scheme: DesignScheme) -> &'static str {
755    match scheme {
756        DesignScheme::Shadcn => "Shadcn",
757        DesignScheme::Cupertino => "Cupertino",
758        DesignScheme::Material => "Material",
759        DesignScheme::Fluent => "Fluent",
760        DesignScheme::AntDesign => "Ant Design",
761        DesignScheme::Bootstrap => "Bootstrap",
762        DesignScheme::DaisyUi => "DaisyUI",
763        DesignScheme::Geist => "Geist",
764        DesignScheme::HeroUi => "HeroUI",
765        DesignScheme::Linear => "Linear",
766        DesignScheme::Mantine => "Mantine",
767        DesignScheme::Monochrome => "Monochrome",
768        DesignScheme::Notion => "Notion",
769        DesignScheme::Park => "Park UI",
770        DesignScheme::Radix => "Radix",
771        DesignScheme::Stripe => "Stripe",
772        DesignScheme::Supabase => "Supabase",
773    }
774}
775
776/// Renders a Lucide-grade 24×24 `Palette` vector icon with an active theme accent swatch dot into `dl`.
777///
778/// # Arguments
779///
780/// - `Rect` - Target logical bounding box.
781/// - `&mut DisplayList` - Destination vector draw command list.
782/// - `Color` - Foreground stroke color.
783/// - `Color` - Active theme primary accent color rendered inside the swatch dot.
784pub(crate) fn draw_topbar_palette_icon(
785    bounds: Rect,
786    dl: &mut DisplayList,
787    color: Color,
788    accent: Color,
789) {
790    let (ox, oy, u, sw): (f32, f32, f32, f32) = topbar_icon_basis(bounds);
791    let cx: f32 = ox + 12.0 * u;
792    let cy: f32 = oy + 12.0 * u;
793    let r: f32 = 8.8 * u;
794    let start_ang: f32 = 0.56;
795    let end_ang: f32 = 2.0 * PI - 0.12;
796    let p_start: Point = Point::new(cx + r * start_ang.cos(), cy + r * start_ang.sin());
797    let arc_steps: usize = 22;
798    let mut prev: Point = p_start;
799    for s in 1..=arc_steps {
800        let t: f32 = (s as f32) / (arc_steps as f32);
801        let a: f32 = start_ang + (end_ang - start_ang) * t;
802        let cur: Point = Point::new(cx + r * a.cos(), cy + r * a.sin());
803        dl.push(DrawCommand::Line {
804            from: prev,
805            to: cur,
806            color,
807            width: sw,
808        });
809        prev = cur;
810    }
811    let notch: [Point; 7] = [
812        prev,
813        Point::new(ox + 17.6 * u, oy + 11.4 * u),
814        Point::new(ox + 15.6 * u, oy + 12.2 * u),
815        Point::new(ox + 14.8 * u, oy + 13.6 * u),
816        Point::new(ox + 15.6 * u, oy + 15.0 * u),
817        Point::new(ox + 17.4 * u, oy + 15.8 * u),
818        p_start,
819    ];
820    for i in 0..6usize {
821        dl.push(DrawCommand::Line {
822            from: notch[i],
823            to: notch[i + 1],
824            color,
825            width: sw,
826        });
827    }
828    let dot_r: f32 = (1.35 * u).max(1.0);
829    for &(dx, dy) in [(7.6_f32, 10.0_f32), (11.2, 6.8), (15.6, 8.6)].iter() {
830        dl.push(DrawCommand::Circle {
831            center: Point::new(ox + dx * u, oy + dy * u),
832            radius: dot_r,
833            color,
834        });
835    }
836    let swatch_r: f32 = (2.15 * u).max(1.5);
837    dl.push(DrawCommand::Circle {
838        center: Point::new(ox + 9.2 * u, oy + 15.2 * u),
839        radius: swatch_r,
840        color: accent,
841    });
842}
843
844/// Mounts the viewport-clamped scrollable floating 17-Scheme Theme Color Dropdown portal anchored beneath the showcase topbar Palette icon button.
845///
846/// # Arguments
847///
848/// - `&ShowcaseState` - Shared reactive showcase state.
849/// - `Signal<bool>` - Controlled dropdown open state signal.
850/// - `ThemeTokens` - Base design tokens.
851/// - `Vec<NodeId>` - Desktop and Mobile Palette button node handles.
852///
853/// # Returns
854///
855/// - `NodeId` - Mounted floating scheme dropdown portal handle.
856pub(crate) fn mount_topbar_scheme_dropdown_portal(
857    state: &ShowcaseState,
858    open_sig: Signal<bool>,
859    tokens: ThemeTokens,
860    triggers: Vec<NodeId>,
861) -> NodeId {
862    let mut ctx: Context = current_context();
863    let scheme_sig: Signal<DesignScheme> = state.get_theme().get_scheme();
864    let mode_sig: Signal<ThemeMode> = state.get_theme().get_mode();
865    let vp_sig: Signal<Size> = ctx.get_viewport_size();
866    let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
867    let init_tok: ThemeTokens = live_tokens_untracked(tokens);
868    let p: ThemePalette = init_tok.get_palette();
869    let g: ThemeGeometry = init_tok.get_geometry();
870    let card_s: SurfaceColors = p.surface(SurfaceRole::Card);
871    let menu_r: f32 = g.get_radius_lg();
872    let item_r: f32 = concentric_radius(menu_r, CONTROL_INSET);
873    let all_schemes: [DesignScheme; 17] = DesignScheme::all();
874    let init_scheme: DesignScheme = scheme_sig.get_untracked();
875    let init_mode: ThemeMode = mode_sig.get_untracked();
876    let hovered_idx: Signal<Option<usize>> = Signal::new(None);
877    let mut item_handles: Vec<(DesignScheme, NodeId, NodeId, NodeId, NodeId)> =
878        Vec::with_capacity(all_schemes.len());
879    let mut item_nodes: Vec<NodeId> = Vec::with_capacity(all_schemes.len());
880    for (idx, scheme) in all_schemes.into_iter().enumerate() {
881        let is_sel: bool = scheme == init_scheme;
882        let (init_bg, init_fg): (Color, Color) = if is_sel {
883            let ps: SurfaceColors = p.surface(SurfaceRole::Primary);
884            (ps.get_bg(), ps.get_fg())
885        } else {
886            (COLOR_TRANSPARENT, card_s.get_fg())
887        };
888        let init_swatch: Color = ThemeTokens::resolve(scheme, init_mode)
889            .get_palette()
890            .get_primary();
891        let lbl_str: &'static str = scheme_display_label(scheme);
892        let on_pick = move |_: &UiEvent| {
893            let _: bool = scheme_sig.set_if_changed(scheme);
894            let _: bool = open_sig.set_if_changed(false);
895        };
896        let paint_check = move |bounds: Rect, dl: &mut DisplayList| {
897            if scheme_sig.get_untracked() == scheme {
898                let lp: ThemePalette = live_tokens_untracked(tokens).get_palette();
899                let fg: Color = lp.surface(SurfaceRole::Primary).get_fg();
900                draw_euv_icon(EuvIconName::Check, bounds, dl, fg);
901            }
902        };
903        let mut dot_id: NodeId = NodeId::default();
904        let mut txt_id: NodeId = NodeId::default();
905        let mut chk_id: NodeId = NodeId::default();
906        let row_id: NodeId = view! {
907            row {
908                style: {
909                    width: Length::Percent(100.0)
910                    height: Length::Px(SCHEME_DROPDOWN_ITEM_HEIGHT)
911                    padding: Edges::symmetric(0.0, SPACE_SM)
912                    align: AlignItems::Center
913                    gap: SPACE_SM
914                    background: init_bg
915                    radius: item_r
916                    overflow: Overflow::Hidden
917                    cursor: CursorIcon::Pointer
918                    stop_event_propagation: true
919                }
920                role: A11yRole::MenuItem
921                a11y_label: lbl_str.to_string()
922                on_click: on_pick
923                view {
924                    node_ref: dot_id
925                    style: {
926                        width: Length::Px(12.0)
927                        height: Length::Px(12.0)
928                        flex_shrink: 0.0
929                        background: init_swatch
930                        border: (1.0, p.get_border())
931                        radius: RADIUS_PILL
932                    }
933                }
934                text {
935                    node_ref: txt_id
936                    style: {
937                        flex_grow: 1.0
938                        flex_shrink: 1.0
939                        min_width: Length::Px(0.0)
940                        font_size: 13.0
941                        font_weight: if is_sel { FontWeight::SemiBold } else { FontWeight::Normal }
942                        color: init_fg
943                        overflow: Overflow::Hidden
944                        text_overflow: TextOverflow::Ellipsis
945                    }
946                    { lbl_str }
947                }
948                canvas {
949                    node_ref: chk_id
950                    style: {
951                        width: Length::Px(13.0)
952                        height: Length::Px(13.0)
953                        flex_shrink: 0.0
954                    }
955                    painter: paint_check
956                }
957            }
958        };
959        ctx.on_pointer_enter(row_id, move |_: &UiEvent| {
960            let _: bool = hovered_idx.set_if_changed(Some(idx));
961        });
962        ctx.on_pointer_leave(row_id, move |_: &UiEvent| {
963            if hovered_idx.get_untracked() == Some(idx) {
964                let _: bool = hovered_idx.set_if_changed(None);
965            }
966        });
967        item_handles.push((scheme, row_id, dot_id, txt_id, chk_id));
968        item_nodes.push(row_id);
969    }
970    let mut card: NodeId = NodeId::default();
971    let mut scroll_list: NodeId = NodeId::default();
972    let portal: NodeId = view! {
973        portal {
974            style: {
975                display: Display::None
976                position: Position::Fixed
977                inset: (Some(0.0), Some(0.0), Some(0.0), Some(0.0))
978                width: Length::Percent(100.0)
979                height: Length::Percent(100.0)
980                background: COLOR_TRANSPARENT
981                pointer_events: PointerEvents::None
982                stop_scroll_propagation: true
983                z_index: SCHEME_DROPDOWN_Z_INDEX
984            }
985            column {
986                node_ref: card
987                style: {
988                    position: Position::Absolute
989                    inset: (Some(SHELL_DESKTOP_HEADER_HEIGHT + 6.0), None, None, Some(8.0))
990                    width: Length::Px(SCHEME_DROPDOWN_WIDTH)
991                    padding: Edges::all(CONTROL_INSET)
992                    background: card_s.get_bg()
993                    border: (g.get_border_width(), card_s.get_border())
994                    radius: menu_r
995                    shadow: g.get_shadow_lg()
996                    overflow: Overflow::Hidden
997                    stop_event_propagation: true
998                }
999                role: A11yRole::Menu
1000                a11y_label: BTN_SCHEME_A11Y.to_string()
1001                scroll {
1002                    node_ref: scroll_list
1003                    style: {
1004                        Style::default().column()
1005                        width: Length::Percent(100.0)
1006                        max_height: Length::Px(SCHEME_DROPDOWN_MAX_HEIGHT)
1007                        gap: CONTROL_INSET
1008                    }
1009                    ..item_nodes
1010                }
1011            }
1012        }
1013    };
1014    ctx.on_click(portal, move |ev: &UiEvent| {
1015        if ev.get_target() == portal {
1016            let _: bool = open_sig.set_if_changed(false);
1017        }
1018    });
1019    for key_target in [portal, card].into_iter() {
1020        ctx.on_key(key_target, move |ev: &UiEvent| {
1021            let is_esc: bool = matches!(ev.get_kind(), UiEventKind::KeyDown(KeyCode::Escape, _))
1022                || matches!(ev.get_kind(), UiEventKind::KeyDown(KeyCode::Back, _));
1023            if is_esc && open_sig.get_untracked() {
1024                let _: bool = open_sig.set_if_changed(false);
1025            }
1026        });
1027    }
1028    let sc_pos: SceneHandle = ctx.get_scene().clone();
1029    let sc_paint: SceneHandle = sc_pos.clone();
1030    let owned_nodes: Vec<NodeId> = {
1031        let mut v: Vec<NodeId> = Vec::with_capacity(item_handles.len() * 4 + 3);
1032        v.push(portal);
1033        v.push(card);
1034        v.push(scroll_list);
1035        for &(_, rid, did, tid, cid) in item_handles.iter() {
1036            v.push(rid);
1037            v.push(did);
1038            v.push(tid);
1039            v.push(cid);
1040        }
1041        v
1042    };
1043    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1044        let _: Effect = EuvOverlayStack::bind_signal(
1045            open_sig,
1046            SCHEME_DROPDOWN_OVERLAY_NAME,
1047            SCHEME_DROPDOWN_Z_INDEX,
1048        );
1049        let _: Effect = Effect::new(move || {
1050            let is_open: bool = open_sig.get();
1051            let vp: Size = vp_sig.get();
1052            let safe: SafeAreaInsets = safe_sig.get();
1053            let vp_w: f32 = vp.get_width().max(320.0);
1054            let vp_h: f32 = vp.get_height().max(320.0);
1055            let margin: f32 = SCHEME_DROPDOWN_EDGE_MARGIN;
1056            let safe_l: f32 = safe.get_left().max(0.0);
1057            let safe_r: f32 = safe.get_right().max(0.0);
1058            let safe_t: f32 = safe.get_top().max(0.0);
1059            let safe_b: f32 = safe.get_bottom().max(0.0);
1060            let menu_w: f32 =
1061                SCHEME_DROPDOWN_WIDTH.min((vp_w - safe_l - safe_r - margin * 2.0).max(160.0));
1062            let anchor_opt: Option<Rect> = sc_pos.with_read(
1063                |tree: &SceneTree| {
1064                    for &tid in triggers.iter() {
1065                        if tree.is_node_visible(tid)
1066                            && let Some(r) = tree.node_screen_bounds(tid)
1067                            && r.get_width() > 4.0
1068                            && r.get_height() > 4.0
1069                        {
1070                            return Some(r);
1071                        }
1072                    }
1073                    None
1074                },
1075                None,
1076            );
1077            let (raw_left, raw_top): (f32, f32) = match anchor_opt {
1078                Some(r) => (
1079                    r.get_x() + r.get_width() - menu_w,
1080                    r.get_y() + r.get_height() + 6.0,
1081                ),
1082                None => (
1083                    vp_w - safe_r - menu_w - margin,
1084                    SHELL_DESKTOP_HEADER_HEIGHT + safe_t + 6.0,
1085                ),
1086            };
1087            let min_left: f32 = safe_l + margin;
1088            let max_left: f32 = (vp_w - safe_r - menu_w - margin).max(min_left);
1089            let left: f32 = raw_left.clamp(min_left, max_left);
1090            let min_top: f32 = safe_t + margin;
1091            let top_clamped: f32 = raw_top.max(min_top);
1092            let avail_h: f32 = (vp_h - safe_b - top_clamped - margin).max(120.0);
1093            let max_h: f32 = SCHEME_DROPDOWN_MAX_HEIGHT.min(avail_h).max(120.0);
1094            let max_top: f32 = (vp_h - safe_b - max_h - margin).max(min_top);
1095            let top: f32 = top_clamped.min(max_top);
1096            let inner_max_h: f32 = (max_h - CONTROL_INSET * 2.0).max(96.0);
1097            if !is_open {
1098                let _: bool = hovered_idx.set_if_changed(None);
1099            }
1100            sc_pos.with_write(
1101                |tree: &mut SceneTree| {
1102                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1103                    let dirty_all: u16 = dirty_l | DIRTY_PAINT;
1104                    if let Some(n) = tree.get_node_mut(scroll_list) {
1105                        n.get_mut_style()
1106                            .get_mut_layout()
1107                            .set_max_height(Length::Px(inner_max_h));
1108                        tree.mark_dirty(scroll_list, dirty_all);
1109                    }
1110                    if let Some(n) = tree.get_node_mut(card) {
1111                        let lay: &mut LayoutStyle = n.get_mut_style().get_mut_layout();
1112                        lay.set_left(Some(left))
1113                            .set_top(Some(top))
1114                            .set_width(Length::Px(menu_w));
1115                        tree.mark_dirty(card, dirty_all);
1116                    }
1117                    if let Some(n) = tree.get_node_mut(portal) {
1118                        let st: &mut Style = n.get_mut_style();
1119                        st.get_mut_layout().set_display(if is_open {
1120                            Display::Flex
1121                        } else {
1122                            Display::None
1123                        });
1124                        st.get_mut_paint().set_pointer_events(if is_open {
1125                            PointerEvents::Auto
1126                        } else {
1127                            PointerEvents::None
1128                        });
1129                        tree.mark_dirty(portal, dirty_all);
1130                    }
1131                },
1132                (),
1133            );
1134        });
1135        Effect::new(move || {
1136            let cur_scheme: DesignScheme = scheme_sig.get();
1137            let cur_mode: ThemeMode = mode_sig.get();
1138            let hov: Option<usize> = hovered_idx.get();
1139            let tok: ThemeTokens = use_live_tokens(tokens);
1140            let lp: ThemePalette = tok.get_palette();
1141            let lg: ThemeGeometry = tok.get_geometry();
1142            let cs: SurfaceColors = lp.surface(SurfaceRole::Card);
1143            let ps: SurfaceColors = lp.surface(SurfaceRole::Primary);
1144            let ac: SurfaceColors = lp.surface(SurfaceRole::Accent);
1145            sc_paint.with_write(
1146                |tree: &mut SceneTree| {
1147                    if let Some(n) = tree.get_node_mut(card) {
1148                        n.get_mut_style()
1149                            .get_mut_paint()
1150                            .set_background(Some(cs.get_bg()))
1151                            .set_border(Border::new(lg.get_border_width(), cs.get_border()))
1152                            .set_shadow(Some(lg.get_shadow_lg()));
1153                        tree.mark_dirty(card, DIRTY_PAINT);
1154                    }
1155                    for (idx, &(sc_item, rid, did, tid, cid)) in item_handles.iter().enumerate() {
1156                        let is_sel: bool = sc_item == cur_scheme;
1157                        let is_hov: bool = hov == Some(idx);
1158                        let (bg, fg): (Color, Color) = if is_sel {
1159                            (ps.get_bg(), ps.get_fg())
1160                        } else if is_hov {
1161                            (ac.get_bg(), ac.get_fg())
1162                        } else {
1163                            (COLOR_TRANSPARENT, cs.get_fg())
1164                        };
1165                        let sw_col: Color = ThemeTokens::resolve(sc_item, cur_mode)
1166                            .get_palette()
1167                            .get_primary();
1168                        let sw_border: Color = if is_sel {
1169                            ps.get_fg().with_alpha(160)
1170                        } else {
1171                            lp.get_border()
1172                        };
1173                        if let Some(n) = tree.get_node_mut(rid) {
1174                            n.get_mut_style().get_mut_paint().set_background(Some(bg));
1175                            tree.mark_dirty(rid, DIRTY_PAINT);
1176                        }
1177                        if let Some(n) = tree.get_node_mut(did) {
1178                            n.get_mut_style()
1179                                .get_mut_paint()
1180                                .set_background(Some(sw_col))
1181                                .set_border(Border::new(1.0, sw_border));
1182                            tree.mark_dirty(did, DIRTY_PAINT);
1183                        }
1184                        if let Some(n) = tree.get_node_mut(tid) {
1185                            n.get_mut_style()
1186                                .get_mut_text()
1187                                .set_color(fg)
1188                                .set_weight(if is_sel {
1189                                    FontWeight::SemiBold
1190                                } else {
1191                                    FontWeight::Normal
1192                                });
1193                            tree.mark_dirty(tid, DIRTY_PAINT);
1194                        }
1195                        tree.mark_dirty(cid, DIRTY_PAINT);
1196                    }
1197                },
1198                (),
1199            );
1200        })
1201    });
1202    ctx.get_scene().with_write(
1203        |tree: &mut SceneTree| {
1204            mark_theme_owned(tree, owned_nodes.as_slice());
1205            tree.attach_scope(portal, scope);
1206        },
1207        (),
1208    );
1209    portal
1210}
1211
1212/// Mounts one uniform topbar action cluster (command palette, 17-scheme Palette dropdown trigger, Light/Dark toggle, Settings gear) whose square icon buttons share the shell control-line height and `radius_md`.
1213///
1214/// # Arguments
1215///
1216/// - `&ShowcaseState` - Shared reactive showcase state.
1217/// - `Signal<bool>` - Controlled scheme dropdown visibility signal.
1218/// - `ThemeTokens` - Active design tokens at mount time.
1219///
1220/// # Returns
1221///
1222/// - `(NodeId, NodeId)` - Mounted action row handle and Palette trigger button handle.
1223pub(crate) fn mount_topbar_actions(
1224    state: &ShowcaseState,
1225    scheme_menu_open: Signal<bool>,
1226    tokens: ThemeTokens,
1227    include_settings: bool,
1228) -> (NodeId, NodeId) {
1229    let cmd_open: Signal<bool> = state.get_cmd_palette_open();
1230    let st_mode: ShowcaseState = state.clone();
1231    let route_sig: Signal<String> = state.get_route();
1232    let icon_btn_style = move || -> Style {
1233        let live_tok: ThemeTokens = use_live_tokens(tokens);
1234        let live_p: ThemePalette = live_tok.get_palette();
1235        let live_g: ThemeGeometry = live_tok.get_geometry();
1236        Style::default()
1237            .row()
1238            .width(Length::Px(TOPBAR_CONTROL_SIZE))
1239            .height(Length::Px(TOPBAR_CONTROL_SIZE))
1240            .flex_shrink(0.0)
1241            .justify(JustifyContent::Center)
1242            .align(AlignItems::Center)
1243            .background(live_p.get_background())
1244            .border(live_g.get_border_width(), live_p.get_border())
1245            .radius(live_g.get_radius_md())
1246            .cursor(CursorIcon::Pointer)
1247    };
1248    let paint_search = move |bounds: Rect, dl: &mut DisplayList| {
1249        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1250        draw_topbar_search_icon(bounds, dl, live_p.get_foreground());
1251    };
1252    let paint_palette = move |bounds: Rect, dl: &mut DisplayList| {
1253        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1254        draw_topbar_palette_icon(bounds, dl, live_p.get_foreground(), live_p.get_primary());
1255    };
1256    let paint_mode = move |bounds: Rect, dl: &mut DisplayList| {
1257        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1258        let fg: Color = live_tok.get_palette().get_foreground();
1259        match live_tok.get_mode() {
1260            ThemeMode::Dark => draw_theme_sun_icon(bounds, dl, fg),
1261            ThemeMode::Light => draw_theme_moon_icon(bounds, dl, fg),
1262        }
1263    };
1264    let paint_settings = move |bounds: Rect, dl: &mut DisplayList| {
1265        let live_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1266        draw_gear_icon(bounds, dl, live_p.get_foreground());
1267    };
1268    let on_open_cmd = move |_: &UiEvent| {
1269        let _: bool = scheme_menu_open.set_if_changed(false);
1270        let _: bool = cmd_open.set_if_changed(true);
1271    };
1272    let on_toggle_scheme = move |_: &UiEvent| {
1273        let _: bool = scheme_menu_open.update(|v: &mut bool| *v = !*v);
1274    };
1275    let on_toggle_mode = move |_: &UiEvent| {
1276        st_mode.toggle_theme_mode();
1277    };
1278    let on_open_settings = move |_: &UiEvent| {
1279        let _: bool = scheme_menu_open.set_if_changed(false);
1280        let _: bool = route_sig.set_if_changed(ROUTE_SETTINGS.to_string());
1281    };
1282    let mut palette_btn: NodeId = NodeId::default();
1283    let cluster: NodeId = view! {
1284        row {
1285            style: {
1286                gap: SPACE_XS
1287                align: AlignItems::Center
1288            }
1289            row {
1290                bind_style: icon_btn_style
1291                role: A11yRole::Button
1292                a11y_label: BTN_SEARCH_A11Y.to_string()
1293                on_click: on_open_cmd
1294                canvas {
1295                    style: {
1296                        width: Length::Px(TOPBAR_ICON_SIZE)
1297                        height: Length::Px(TOPBAR_ICON_SIZE)
1298                    }
1299                    caching: CanvasCaching::RetainedStatic
1300                    painter: paint_search
1301                }
1302            }
1303            row {
1304                node_ref: palette_btn
1305                bind_style: icon_btn_style
1306                role: A11yRole::Button
1307                a11y_label: BTN_SCHEME_A11Y.to_string()
1308                on_click: on_toggle_scheme
1309                canvas {
1310                    style: {
1311                        width: Length::Px(TOPBAR_ICON_SIZE)
1312                        height: Length::Px(TOPBAR_ICON_SIZE)
1313                    }
1314                    caching: CanvasCaching::RetainedStatic
1315                    painter: paint_palette
1316                }
1317            }
1318            row {
1319                bind_style: icon_btn_style
1320                role: A11yRole::Button
1321                a11y_label: BTN_MODE_A11Y.to_string()
1322                on_click: on_toggle_mode
1323                canvas {
1324                    style: {
1325                        width: Length::Px(TOPBAR_ICON_SIZE)
1326                        height: Length::Px(TOPBAR_ICON_SIZE)
1327                    }
1328                    caching: CanvasCaching::RetainedStatic
1329                    painter: paint_mode
1330                }
1331            }
1332            if include_settings {
1333                row {
1334                    bind_style: icon_btn_style
1335                    role: A11yRole::Button
1336                    a11y_label: BTN_SETTINGS_A11Y.to_string()
1337                    on_click: on_open_settings
1338                    canvas {
1339                        style: {
1340                            width: Length::Px(TOPBAR_ICON_SIZE)
1341                            height: Length::Px(TOPBAR_ICON_SIZE)
1342                        }
1343                        caching: CanvasCaching::RetainedStatic
1344                        painter: paint_settings
1345                    }
1346                }
1347            }
1348        }
1349    };
1350    (cluster, palette_btn)
1351}