Skip to main content

euv_ui/component/form/
impl.rs

1use super::*;
2
3/// Fluent configuration builders for `EuvInput`.
4impl EuvInput {
5    /// Enables or disables password masking fluently.
6    ///
7    /// # Arguments
8    ///
9    /// - `Self` - Source input.
10    /// - `bool` - Whether characters are masked.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Updated input.
15    #[must_use]
16    pub fn password(mut self, password: bool) -> Self {
17        self.set_password(password);
18        self
19    }
20
21    /// Enables or disables interaction fluently.
22    ///
23    /// # Arguments
24    ///
25    /// - `Self` - Source input.
26    /// - `bool` - Whether editing is disabled.
27    ///
28    /// # Returns
29    ///
30    /// - `Self` - Updated input.
31    #[must_use]
32    pub fn disabled(mut self, disabled: bool) -> Self {
33        self.set_disabled(disabled);
34        self
35    }
36
37    /// Removes outer chrome so the input embeds cleanly inside `EuvInputGroup`.
38    ///
39    /// # Arguments
40    ///
41    /// - `Self` - Source input.
42    /// - `bool` - Whether borderless embedding is active.
43    ///
44    /// # Returns
45    ///
46    /// - `Self` - Updated input.
47    #[must_use]
48    pub fn borderless(mut self, borderless: bool) -> Self {
49        self.set_borderless(borderless);
50        self
51    }
52}
53
54/// Declarative `#[component]` implementation for `EuvInput`.
55#[component]
56/// Inherent implementation of [`EuvInput`].
57impl EuvInput {
58    /// Renders `EuvInput` into the ambient framework-managed `Context`.
59    ///
60    /// # Arguments
61    ///
62    /// - `&Self` - Component descriptor reference.
63    ///
64    /// # Returns
65    ///
66    /// - `NodeId` - Mounted root scene node handle.
67    fn render(&self) -> NodeId {
68        let ctx: Context = current_context();
69        let base_tokens: ThemeTokens = self.get_tokens();
70        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
71        let theme_palette: ThemePalette = init_tok.get_palette();
72        let theme_geometry: ThemeGeometry = init_tok.get_geometry();
73        let sig: Signal<String> = self.get_value();
74        let initial: String = sig.get_untracked();
75        let caret: usize = initial.len();
76        let password: bool = self.get_password();
77        let disabled: bool = self.get_disabled();
78        let borderless: bool = self.get_borderless();
79        let Self { placeholder, .. } = self;
80        let placeholder_owned: String = placeholder.clone();
81        let a11y_label: String = placeholder_owned.clone();
82        let card_surface: SurfaceColors = theme_palette.surface(SurfaceRole::Card);
83        let mut style: Style = Style::default();
84        style
85            .get_mut_layout()
86            .set_width(Length::Percent(100.0))
87            .set_height(Length::Px(theme_geometry.get_control_md()))
88            .set_padding(Edges::symmetric(0.0, SPACE_MD))
89            .set_overflow(Overflow::Hidden);
90        style
91            .get_mut_text()
92            .set_color(card_surface.get_fg())
93            .set_font_size(13.0);
94        if borderless {
95            style
96                .get_mut_paint()
97                .set_background(Some(COLOR_TRANSPARENT));
98        } else {
99            style
100                .get_mut_paint()
101                .set_background(Some(card_surface.get_bg()))
102                .set_border(Border::new(
103                    theme_geometry.get_border_width(),
104                    card_surface.get_border(),
105                ))
106                .set_radius(CornerRadius::all(theme_geometry.get_radius_md().max(0.0)))
107                .set_focus_ring(None);
108        }
109        let on_input_change = move |ui_event: &UiEvent| {
110            if let UiEventKind::Change(val) = ui_event.get_kind() {
111                let _: bool = sig.set_if_changed(val.clone());
112            }
113        };
114        let node: NodeId = view! {
115            input {
116                style: style
117                value: initial.clone()
118                placeholder: placeholder_owned
119                caret: caret
120                password: password
121                multiline: false
122                disabled: disabled
123                role: A11yRole::TextInput
124                a11y_label: a11y_label.clone()
125                a11y_value: initial
126                a11y_disabled: disabled
127                on_change: on_input_change
128            }
129        };
130        let handle: SceneHandle = ctx.get_scene().clone();
131        let prev_key: Cell<ThemeKey> = Cell::new(init_tok.key());
132        let a11y_fallback: Rc<str> = Rc::from(a11y_label.as_str());
133        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
134            Effect::new(move || {
135                let next_val: String = sig.get();
136                let live_tok: ThemeTokens = use_live_tokens(base_tokens);
137                let theme_changed: bool = prev_key.replace(live_tok.key()) != live_tok.key();
138                let fallback_label: Rc<str> = a11y_fallback.clone();
139                handle.mutate(move |tree: &mut SceneTree| {
140                    let mut changed: bool = false;
141                    if let Some(item_count) = tree.get_node_mut(node) {
142                        if let NodeKind::Input(input_state) = item_count.get_mut_kind()
143                            && input_state.get_value() != &next_val
144                        {
145                            let len: usize = next_val.len();
146                            input_state.set_value(next_val.clone());
147                            input_state.set_caret(len);
148                            changed = true;
149                        }
150                        if theme_changed {
151                            let live_p: ThemePalette = live_tok.get_palette();
152                            let live_g: ThemeGeometry = live_tok.get_geometry();
153                            let surf: SurfaceColors = live_p.surface(SurfaceRole::Card);
154                            let computed_style: &mut Style = item_count.get_mut_style();
155                            computed_style.get_mut_text().set_color(surf.get_fg());
156                            if !borderless {
157                                computed_style
158                                    .get_mut_paint()
159                                    .set_background(Some(surf.get_bg()))
160                                    .set_border(Border::new(
161                                        live_g.get_border_width(),
162                                        surf.get_border(),
163                                    ))
164                                    .set_focus_ring(None);
165                            }
166                            changed = true;
167                        }
168                        if let Some(a11y) = item_count.get_mut_a11y().as_mut() {
169                            a11y.set_value(next_val);
170                            a11y.set_disabled(disabled);
171                        } else {
172                            let mut next_a11y: A11yProps =
173                                A11yProps::new(A11yRole::TextInput, fallback_label.to_string());
174                            next_a11y.set_value(next_val);
175                            next_a11y.set_disabled(disabled);
176                            item_count.set_a11y(Some(next_a11y));
177                        }
178                    }
179                    if changed {
180                        tree.mark_dirty(node, DIRTY_PAINT);
181                    }
182                });
183            })
184        });
185        ctx.get_scene().mutate(move |tree: &mut SceneTree| {
186            mark_theme_owned(tree, &[node]);
187            tree.attach_scope(node, scope);
188        });
189        node
190    }
191}
192
193/// Fluent configuration builders for `EuvField`.
194impl EuvField {
195    /// Sets a validation error caption rendered beneath the field control.
196    ///
197    /// # Arguments
198    ///
199    /// - `Self` - Source field.
200    /// - `TextValue` - Error message text.
201    ///
202    /// # Returns
203    ///
204    /// - `Self` - Updated field.
205    #[must_use]
206    pub fn error<TextValue>(mut self, error: TextValue) -> Self
207    where
208        TextValue: Into<String>,
209    {
210        self.set_error(error.into());
211        self
212    }
213}
214
215/// Declarative `#[component]` implementation for `EuvField`.
216#[component]
217/// Inherent implementation of [`EuvField`].
218impl EuvField {
219    /// Renders `EuvField` into the ambient framework-managed `Context`.
220    ///
221    /// # Arguments
222    ///
223    /// - `&Self` - Component descriptor reference.
224    ///
225    /// # Returns
226    ///
227    /// - `NodeId` - Mounted root scene node handle.
228    fn render(&self) -> NodeId {
229        let theme_palette: ThemePalette = live_tokens_untracked(self.get_tokens()).get_palette();
230        let control: NodeId = self.get_control();
231        let Self { label, error, .. } = self;
232        let column_style: Style = style! {
233            Width(Length::Percent(100.0))
234            Gap(SPACE_XS)
235        };
236        let text_quaternary_style: Style = style! {
237            FontSize(13.0)
238            FontWeight::Medium
239            TextColor(theme_palette.get_foreground())
240        };
241        let text_fifth_style: Style = style! {
242            FontSize(12.0)
243            TextColor(theme_palette.get_destructive())
244        };
245        view! {
246            column {
247                style: column_style
248                text {
249                    style: text_quaternary_style
250                    { label.clone() }
251                }
252                { control }
253                if !error.is_empty() {
254                    text {
255                        style: text_fifth_style
256                        { error.clone() }
257                    }
258                }
259            }
260        }
261    }
262}
263
264/// Declarative `#[component]` implementation for `EuvSwitch`.
265#[component]
266/// Inherent implementation of [`EuvSwitch`].
267impl EuvSwitch {
268    /// Renders `EuvSwitch` into the ambient framework-managed `Context`.
269    ///
270    /// The pill track and circular thumb use `RADIUS_PILL` with a uniform `2px` inset on all four sides, and their
271    /// state-dependent colors are owned by a reactive `Effect` tracking both `checked` and the live ambient theme, so
272    /// toggling after a theme switch never reverts to stale colors.
273    ///
274    /// # Arguments
275    ///
276    /// - `&Self` - Component descriptor reference.
277    ///
278    /// # Returns
279    ///
280    /// - `NodeId` - Mounted root scene node handle.
281    fn render(&self) -> NodeId {
282        let ctx: Context = current_context();
283        let base_tokens: ThemeTokens = self.get_tokens();
284        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
285        let theme_palette: ThemePalette = init_tok.get_palette();
286        let theme_geometry: ThemeGeometry = init_tok.get_geometry();
287        let checked: Signal<bool> = self.get_checked();
288        let Self { label, .. } = self;
289        let label_owned: String = label.clone();
290        let a11y_label: String = label_owned.clone();
291        let init_on: bool = checked.get_untracked();
292        let (init_track, init_thumb): (Color, Color) = Self::state_colors(theme_palette, init_on);
293        let mut track: NodeId = NodeId::default();
294        let mut thumb: NodeId = NodeId::default();
295        let mut label_node: NodeId = NodeId::default();
296        let on_toggle = move |_: &UiEvent| {
297            let _: bool = checked.set(!checked.get_untracked());
298        };
299        let row_quaternary_style: Style = style! {
300            AlignItems::Center
301            Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
302            Radius(theme_geometry.get_radius_sm())
303            Gap(SPACE_SM)
304            CursorIcon::Pointer
305        };
306        let row_fifth_style: Style = style! {
307            Width(Length::Px(SWITCH_TRACK_WIDTH))
308            Height(Length::Px(SWITCH_TRACK_HEIGHT))
309            FlexShrink(0.0)
310            Padding(Edges::all(SWITCH_TRACK_INSET))
311            AlignItems::Center
312            if init_on { JustifyContent::End } else { JustifyContent::Start }
313            Radius(RADIUS_PILL)
314            Background(init_track)
315        };
316        let view_style: Style = style! {
317            Width(Length::Px(SWITCH_THUMB_SIZE))
318            Height(Length::Px(SWITCH_THUMB_SIZE))
319            Radius(RADIUS_PILL)
320            Background(init_thumb)
321            theme_geometry.get_shadow_xs()
322        };
323        let text_tertiary_style: Style = style! {
324            FlexGrow(1.0)
325            FontSize(13.0)
326            FontWeight::Medium
327            TextColor(theme_palette.get_foreground())
328        };
329        let row: NodeId = view! {
330            row {
331                style: row_quaternary_style
332                on_click: on_toggle
333                row {
334                    node_ref: track
335                    style: row_fifth_style
336                    view {
337                        node_ref: thumb
338                        style: view_style
339                    }
340                }
341                text {
342                    node_ref: label_node
343                    style: text_tertiary_style
344                    { label_owned }
345                }
346            }
347        };
348        let handle: SceneHandle = ctx.get_scene().clone();
349        let prev_state: Cell<(bool, ThemeKey)> = Cell::new((init_on, init_tok.key()));
350        let a11y_fallback: Rc<str> = Rc::from(a11y_label.as_str());
351        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
352            Effect::new(move || {
353                let is_on: bool = checked.get();
354                let tok: ThemeTokens = use_live_tokens(base_tokens);
355                let (prev_on, prev_key): (bool, ThemeKey) = prev_state.replace((is_on, tok.key()));
356                if prev_on == is_on && prev_key == tok.key() {
357                    return;
358                }
359                let live_p: ThemePalette = tok.get_palette();
360                let (track_bg, thumb_bg): (Color, Color) = Self::state_colors(live_p, is_on);
361                let thumb_shadow: Shadow = tok.get_geometry().get_shadow_xs();
362                let theme_changed: bool = prev_key != tok.key();
363                let fallback_label: Rc<str> = a11y_fallback.clone();
364                handle.mutate(move |tree: &mut SceneTree| {
365                    if let Some(item_count) = tree.get_node_mut(track) {
366                        let computed_style: &mut Style = item_count.get_mut_style();
367                        computed_style
368                            .get_mut_layout()
369                            .set_justify_content(if is_on {
370                                JustifyContent::End
371                            } else {
372                                JustifyContent::Start
373                            });
374                        computed_style
375                            .get_mut_paint()
376                            .set_background(Some(track_bg));
377                        let dirty: u16 = if prev_on == is_on {
378                            DIRTY_PAINT
379                        } else {
380                            let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
381                            layout_dirty | DIRTY_PAINT
382                        };
383                        tree.mark_dirty(track, dirty);
384                    }
385                    if let Some(node_entry) = tree.get_node_mut(thumb) {
386                        node_entry
387                            .get_mut_style()
388                            .get_mut_paint()
389                            .set_background(Some(thumb_bg))
390                            .set_shadow(Some(thumb_shadow));
391                        tree.mark_dirty(thumb, DIRTY_PAINT);
392                    }
393                    if theme_changed && let Some(normal_vec) = tree.get_node_mut(label_node) {
394                        normal_vec
395                            .get_mut_style()
396                            .get_mut_text()
397                            .set_color(live_p.get_foreground());
398                        tree.mark_dirty(label_node, DIRTY_PAINT);
399                    }
400                    if let Some(total_len) = tree.get_node_mut(row) {
401                        if let Some(a11y) = total_len.get_mut_a11y().as_mut() {
402                            a11y.set_checked(Some(is_on));
403                        } else {
404                            let mut a11y: A11yProps =
405                                A11yProps::new(A11yRole::Switch, fallback_label.to_string());
406                            a11y.set_checked(Some(is_on));
407                            total_len.set_a11y(Some(a11y));
408                        }
409                    }
410                });
411            })
412        });
413        ctx.get_scene().mutate(move |tree: &mut SceneTree| {
414            if let Some(item_count_primary) = tree.get_node_mut(row) {
415                let mut a11y: A11yProps = A11yProps::new(A11yRole::Switch, a11y_label);
416                a11y.set_checked(Some(init_on));
417                item_count_primary.set_a11y(Some(a11y));
418            }
419            mark_theme_owned(tree, &[track, thumb, label_node]);
420            tree.attach_scope(track, scope);
421        });
422        row
423    }
424}
425
426/// State-dependent palette helpers for `EuvSwitch`.
427impl EuvSwitch {
428    /// Resolves `(track, thumb)` fill colors for the given checked state.
429    ///
430    /// # Arguments
431    ///
432    /// - `ThemePalette` - Live theme palette.
433    /// - `bool` - Whether the switch is on.
434    ///
435    /// # Returns
436    ///
437    /// - `(Color, Color)` - Track and thumb fill colors.
438    #[must_use]
439    pub fn state_colors(palette: ThemePalette, is_on: bool) -> (Color, Color) {
440        if is_on {
441            (palette.get_primary(), palette.get_primary_foreground())
442        } else {
443            (palette.get_switch_track_off(), palette.get_switch_thumb())
444        }
445    }
446}
447
448/// Declarative `#[component]` implementation for `EuvCheckbox`.
449#[component]
450/// Inherent implementation of [`EuvCheckbox`].
451impl EuvCheckbox {
452    /// Renders `EuvCheckbox` into the ambient framework-managed `Context`.
453    ///
454    /// The indicator box is a rounded square (`radius_sm`, never circular) whose fill, border, and check-mark colors
455    /// are owned by a reactive `Effect` tracking both `checked` and the live ambient theme.
456    ///
457    /// # Arguments
458    ///
459    /// - `&Self` - Component descriptor reference.
460    ///
461    /// # Returns
462    ///
463    /// - `NodeId` - Mounted root scene node handle.
464    fn render(&self) -> NodeId {
465        let ctx: Context = current_context();
466        let base_tokens: ThemeTokens = self.get_tokens();
467        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
468        let theme_palette: ThemePalette = init_tok.get_palette();
469        let theme_geometry: ThemeGeometry = init_tok.get_geometry();
470        let checked: Signal<bool> = self.get_checked();
471        let Self { label, .. } = self;
472        let label_owned: String = label.clone();
473        let a11y_label: String = label_owned.clone();
474        let init_on: bool = checked.get_untracked();
475        let init_bg: Color = Self::box_fill(theme_palette, init_on);
476        let box_radius: f32 = Self::box_radius(theme_geometry);
477        let mut indicator: NodeId = NodeId::default();
478        let mut mark: NodeId = NodeId::default();
479        let mut label_node: NodeId = NodeId::default();
480        let on_toggle = move |_: &UiEvent| {
481            let _: bool = checked.set(!checked.get_untracked());
482        };
483        let paint_check = move |bounds: Rect, display_list: &mut DisplayList| {
484            if checked.get_untracked() {
485                let check_fg: Color = live_tokens_untracked(base_tokens)
486                    .get_palette()
487                    .surface(SurfaceRole::Primary)
488                    .get_fg();
489                let x0: f32 = bounds.get_x() + 1.5;
490                let y0: f32 = bounds.get_y() + 6.0;
491                let xm: f32 = bounds.get_x() + 4.8;
492                let ym: f32 = bounds.get_y() + 9.5;
493                let x1: f32 = bounds.get_x() + 10.5;
494                let y1: f32 = bounds.get_y() + 2.5;
495                display_list.push(DrawCommand::Line {
496                    from: Point::new(x0, y0),
497                    to: Point::new(xm, ym),
498                    color: check_fg,
499                    width: 2.0,
500                });
501                display_list.push(DrawCommand::Line {
502                    from: Point::new(xm, ym),
503                    to: Point::new(x1, y1),
504                    color: check_fg,
505                    width: 2.0,
506                });
507            }
508        };
509        let row_secondary_style: Style = style! {
510            AlignItems::Center
511            Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
512            Radius(theme_geometry.get_radius_sm())
513            Gap(SPACE_SM)
514            CursorIcon::Pointer
515        };
516        let row_tertiary_style: Style = style! {
517            JustifyContent::Center
518            AlignItems::Center
519            Width(Length::Px(CHECKBOX_BOX_SIZE))
520            Height(Length::Px(CHECKBOX_BOX_SIZE))
521            FlexShrink(0.0)
522            Background(init_bg)
523            Border::new(theme_geometry.get_border_width(), theme_palette.get_primary())
524            Radius(box_radius)
525        };
526        let canvas_style: Style = style! {
527            Width(Length::Px(12.0))
528            Height(Length::Px(12.0))
529        };
530        let text_secondary_style: Style = style! {
531            FlexGrow(1.0)
532            FontSize(14.0)
533            TextColor(theme_palette.get_foreground())
534        };
535        let row: NodeId = view! {
536            row {
537                style: row_secondary_style
538                on_click: on_toggle
539                row {
540                    node_ref: indicator
541                    style: row_tertiary_style
542                    canvas {
543                        node_ref: mark
544                        style: canvas_style
545                        painter: paint_check
546                    }
547                }
548                text {
549                    node_ref: label_node
550                    style: text_secondary_style
551                    { label_owned }
552                }
553            }
554        };
555        let handle: SceneHandle = ctx.get_scene().clone();
556        let prev_state: Cell<(bool, ThemeKey)> = Cell::new((init_on, init_tok.key()));
557        let a11y_fallback: Rc<str> = Rc::from(a11y_label.as_str());
558        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
559            Effect::new(move || {
560                let is_on: bool = checked.get();
561                let tok: ThemeTokens = use_live_tokens(base_tokens);
562                let (prev_on, prev_key): (bool, ThemeKey) = prev_state.replace((is_on, tok.key()));
563                if prev_on == is_on && prev_key == tok.key() {
564                    return;
565                }
566                let live_p: ThemePalette = tok.get_palette();
567                let live_g: ThemeGeometry = tok.get_geometry();
568                let fill: Color = Self::box_fill(live_p, is_on);
569                let theme_changed: bool = prev_key != tok.key();
570                let fallback_label: Rc<str> = a11y_fallback.clone();
571                handle.mutate(move |tree: &mut SceneTree| {
572                    if let Some(item_count) = tree.get_node_mut(indicator) {
573                        item_count
574                            .get_mut_style()
575                            .get_mut_paint()
576                            .set_background(Some(fill))
577                            .set_border(Border::new(
578                                live_g.get_border_width(),
579                                live_p.get_primary(),
580                            ))
581                            .set_radius(CornerRadius::all(Self::box_radius(live_g)));
582                        tree.mark_dirty(indicator, DIRTY_PAINT);
583                    }
584                    tree.mark_dirty(mark, DIRTY_PAINT);
585                    if theme_changed && let Some(node_entry) = tree.get_node_mut(label_node) {
586                        node_entry
587                            .get_mut_style()
588                            .get_mut_text()
589                            .set_color(live_p.get_foreground());
590                        tree.mark_dirty(label_node, DIRTY_PAINT);
591                    }
592                    if let Some(normal_vec) = tree.get_node_mut(row) {
593                        if let Some(a11y) = normal_vec.get_mut_a11y().as_mut() {
594                            a11y.set_checked(Some(is_on));
595                        } else {
596                            let mut a11y: A11yProps =
597                                A11yProps::new(A11yRole::Checkbox, fallback_label.to_string());
598                            a11y.set_checked(Some(is_on));
599                            normal_vec.set_a11y(Some(a11y));
600                        }
601                    }
602                });
603            })
604        });
605        ctx.get_scene().mutate(move |tree: &mut SceneTree| {
606            if let Some(total_len) = tree.get_node_mut(row) {
607                let mut a11y: A11yProps = A11yProps::new(A11yRole::Checkbox, a11y_label);
608                a11y.set_checked(Some(init_on));
609                total_len.set_a11y(Some(a11y));
610            }
611            mark_theme_owned(tree, &[indicator, mark, label_node]);
612            tree.attach_scope(indicator, scope);
613        });
614        row
615    }
616}
617
618/// State-dependent palette and geometry helpers for `EuvCheckbox`.
619impl EuvCheckbox {
620    /// Resolves the indicator box fill for the given checked state.
621    ///
622    /// # Arguments
623    ///
624    /// - `ThemePalette` - Live theme palette.
625    /// - `bool` - Whether the checkbox is checked.
626    ///
627    /// # Returns
628    ///
629    /// - `Color` - Indicator fill color.
630    #[must_use]
631    pub fn box_fill(palette: ThemePalette, is_on: bool) -> Color {
632        if is_on {
633            palette.get_primary()
634        } else {
635            palette.get_card()
636        }
637    }
638
639    /// Resolves the rounded-square indicator radius, capped so the box can never read as a circular radio.
640    ///
641    /// # Arguments
642    ///
643    /// - `ThemeGeometry` - Live theme geometry.
644    ///
645    /// # Returns
646    ///
647    /// - `f32` - Corner radius in logical pixels.
648    #[must_use]
649    pub fn box_radius(geometry: ThemeGeometry) -> f32 {
650        geometry.get_radius_sm().clamp(2.0, CHECKBOX_MAX_RADIUS)
651    }
652}
653
654/// Declarative `#[component]` implementation for `EuvSegmented`.
655#[component]
656/// Inherent implementation of [`EuvSegmented`].
657impl EuvSegmented {
658    /// Renders `EuvSegmented` into the ambient framework-managed `Context`.
659    ///
660    /// The track uses a uniform `CONTROL_INSET` on all four sides equal to the inter-segment gap, and segment pills
661    /// use the concentric radius `radius_lg - CONTROL_INSET`. Active segment paint is owned by a reactive `Effect`
662    /// tracking both the selection and the live ambient theme.
663    ///
664    /// # Arguments
665    ///
666    /// - `&Self` - Component descriptor reference.
667    ///
668    /// # Returns
669    ///
670    /// - `NodeId` - Mounted root scene node handle.
671    fn render(&self) -> NodeId {
672        let mut ctx: Context = current_context();
673        let base_tokens: ThemeTokens = self.get_tokens();
674        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
675        let theme_palette: ThemePalette = init_tok.get_palette();
676        let theme_geometry: ThemeGeometry = init_tok.get_geometry();
677        let selected: Signal<usize> = self.get_selected();
678        let Self { options, .. } = self;
679        let init_sel: usize = selected.get_untracked();
680        let track_radius: f32 = theme_geometry.get_radius_lg();
681        let segment_radius: f32 = concentric_radius(track_radius, CONTROL_INSET);
682        let hovered_idx: Signal<Option<usize>> = Signal::new(None);
683        let tab_pairs: Vec<(NodeId, NodeId)> = options
684            .iter()
685            .enumerate()
686            .map(|(idx, opt): (usize, &String)| {
687                let active: bool = init_sel == idx;
688                let on_pick = move |_: &UiEvent| {
689                    let _: bool = selected.set_if_changed(idx);
690                };
691                let on_enter = move |_: &UiEvent| {
692                    let _: bool = hovered_idx.set_if_changed(Some(idx));
693                };
694                let on_leave = move |_: &UiEvent| {
695                    if hovered_idx.get_untracked() == Some(idx) {
696                        let _: bool = hovered_idx.set_if_changed(None);
697                    }
698                };
699                let init_surface: SurfaceColors = theme_palette.interaction_colors(
700                    InteractionRole::SegmentedPill,
701                    active,
702                    false,
703                    false,
704                );
705                let segment_pad_x: f32 = if options.len() >= 5 {
706                    SPACE_XS
707                } else {
708                    SPACE_SM
709                };
710                let segment_font_size: f32 = if options.len() >= 6 { 11.5 } else { 13.0 };
711                let mut tab_style: Style = style! {
712                    FlexDirection::Row
713                    FlexGrow(1.0)
714                    FlexShrink(1.0)
715                    FlexBasis(Length::Px(0.0))
716                    MinWidth(Length::Px(0.0))
717                    Height(Length::Px(theme_geometry.get_control_sm()))
718                    JustifyContent::Center
719                    AlignItems::Center
720                    Padding(Edges::symmetric(0.0, segment_pad_x))
721                    Overflow::Hidden
722                    Radius(segment_radius)
723                    CursorIcon::Pointer
724                };
725                Self::apply_segment_paint(tab_style.get_mut_paint(), init_tok, active, false);
726                let mut label_id: NodeId = NodeId::default();
727                let text_style: Style = style! {
728                    FlexShrink(1.0)
729                    MinWidth(Length::Px(0.0))
730                    MaxWidth(Length::Percent(100.0))
731                    FontSize(segment_font_size)
732                    FontWeight::Medium
733                    TextColor(init_surface.get_fg())
734                    TextAlign::Center
735                    TextOverflow::Ellipsis
736                    Overflow::Hidden
737                };
738                let tab_id: NodeId = view! {
739                    row {
740                        style: tab_style
741                        role: A11yRole::Tab
742                        a11y_label: opt.clone()
743                        on_click: on_pick
744                        on_pointer_enter: on_enter
745                        on_pointer_leave: on_leave
746                        text {
747                            node_ref: label_id
748                            style: text_style
749                            { opt.clone() }
750                        }
751                    }
752                };
753                (tab_id, label_id)
754            })
755            .collect();
756        let tab_nodes: Vec<NodeId> = tab_pairs
757            .iter()
758            .map(|&(tab_id, _): &(NodeId, NodeId)| tab_id)
759            .collect();
760        let row_style: Style = style! {
761            FlexWrap::NoWrap
762            Width(Length::Percent(100.0))
763            Padding(Edges::all(CONTROL_INSET))
764            Gap(CONTROL_INSET)
765            Overflow::Hidden
766            Background(theme_palette.get_muted())
767            Radius(track_radius)
768        };
769        let root: NodeId = view! {
770            row {
771                style: row_style
772                role: A11yRole::TabList
773            }
774        };
775        if !tab_nodes.is_empty() {
776            ctx.append_many(root, tab_nodes.as_slice());
777        }
778        let handle: SceneHandle = ctx.get_scene().clone();
779        let app_state_sig: Signal<AppState> = ctx.get_app_state();
780        let mut owned_nodes: Vec<NodeId> = Vec::with_capacity(1 + tab_pairs.len() * 2);
781        owned_nodes.push(root);
782        for &(tab_id, label_id) in tab_pairs.iter() {
783            owned_nodes.push(tab_id);
784            owned_nodes.push(label_id);
785        }
786        let init_pairs: Vec<(NodeId, NodeId)> = tab_pairs.clone();
787        let shared_pairs: Rc<[(NodeId, NodeId)]> = Rc::from(tab_pairs);
788        let prev_state: Cell<(usize, Option<usize>, ThemeKey)> =
789            Cell::new((init_sel, None, init_tok.key()));
790        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
791            let _: Effect = Effect::new(move || {
792                if app_state_sig.get() != AppState::Active {
793                    let _: bool = hovered_idx.set_if_changed(None);
794                }
795            });
796            Effect::new(move || {
797                let next_sel: usize = selected.get();
798                let next_hov: Option<usize> = hovered_idx.get();
799                let tok: ThemeTokens = use_live_tokens(base_tokens);
800                let (old_sel, old_hov, old_key): (usize, Option<usize>, ThemeKey) =
801                    prev_state.replace((next_sel, next_hov, tok.key()));
802                if old_sel == next_sel && old_hov == next_hov && old_key == tok.key() {
803                    return;
804                }
805                let live_p: ThemePalette = tok.get_palette();
806                let theme_changed: bool = old_key != tok.key();
807                let pairs_ref: Rc<[(NodeId, NodeId)]> = shared_pairs.clone();
808                handle.mutate(move |tree: &mut SceneTree| {
809                    if theme_changed && let Some(node_ref) = tree.get_node_mut(root) {
810                        let _: &mut PaintStyle = node_ref
811                            .get_mut_style()
812                            .get_mut_paint()
813                            .set_background(Some(live_p.get_muted()));
814                        tree.mark_dirty(root, DIRTY_PAINT);
815                    }
816                    for (idx, &(tab, label_id)) in pairs_ref.iter().enumerate() {
817                        let is_active: bool = idx == next_sel;
818                        let is_hovered: bool = next_hov == Some(idx);
819                        let seg_surface: SurfaceColors = live_p.interaction_colors(
820                            InteractionRole::SegmentedPill,
821                            is_active,
822                            is_hovered,
823                            false,
824                        );
825                        if let Some(node_ref) = tree.get_node_mut(tab) {
826                            Self::apply_segment_paint(
827                                node_ref.get_mut_style().get_mut_paint(),
828                                tok,
829                                is_active,
830                                is_hovered,
831                            );
832                            let _: &mut SceneNode =
833                                node_ref.set_hover_style(Self::segment_hover_paint(tok, is_active));
834                            tree.mark_dirty(tab, DIRTY_PAINT);
835                        }
836                        if let Some(label_node) = tree.get_node_mut(label_id) {
837                            let _: &mut TextStyle = label_node
838                                .get_mut_style()
839                                .get_mut_text()
840                                .set_color(seg_surface.get_fg());
841                            tree.mark_dirty(label_id, DIRTY_PAINT);
842                        }
843                    }
844                });
845            })
846        });
847        ctx.get_scene().mutate(move |tree: &mut SceneTree| {
848            for (idx, &(tab, _)) in init_pairs.iter().enumerate() {
849                if let Some(node_ref) = tree.get_node_mut(tab) {
850                    let _: &mut SceneNode = node_ref
851                        .set_hover_style(Self::segment_hover_paint(init_tok, idx == init_sel));
852                }
853            }
854            mark_theme_owned(tree, owned_nodes.as_slice());
855            tree.attach_scope(root, scope);
856        });
857        root
858    }
859}
860
861/// Theme-aware paint helpers for `EuvSegmented`.
862impl EuvSegmented {
863    /// Writes active / hovered / inactive segment fill, border, and elevation for `tokens` onto `paint`.
864    ///
865    /// # Arguments
866    ///
867    /// - `&mut PaintStyle` - Segment paint to update.
868    /// - `ThemeTokens` - Live theme tokens.
869    /// - `bool` - Whether the segment is selected.
870    /// - `bool` - Whether the segment is hovered.
871    pub fn apply_segment_paint(
872        paint: &mut PaintStyle,
873        tokens: ThemeTokens,
874        active: bool,
875        hovered: bool,
876    ) {
877        let palette: ThemePalette = tokens.get_palette();
878        let geometry: ThemeGeometry = tokens.get_geometry();
879        let surface: SurfaceColors =
880            palette.interaction_colors(InteractionRole::SegmentedPill, active, hovered, false);
881        let _: &mut PaintStyle = paint
882            .set_background(Some(surface.get_bg()))
883            .set_border(Border::new(
884                geometry.get_border_width(),
885                surface.get_border(),
886            ))
887            .set_shadow(if active {
888                Some(geometry.get_shadow_xs())
889            } else {
890                None
891            });
892    }
893
894    /// Returns the subtle hover paint applied to inactive segments (preserving the uniform `CONTROL_INSET` gap next to the active pill).
895    ///
896    /// # Arguments
897    ///
898    /// - `ThemeTokens` - Live theme tokens.
899    /// - `bool` - Whether the segment is currently active.
900    ///
901    /// # Returns
902    ///
903    /// - `Option<PaintStyle>` - Accent hover surface for inactive segments, `None` for the active segment.
904    #[must_use]
905    pub fn segment_hover_paint(tokens: ThemeTokens, active: bool) -> Option<PaintStyle> {
906        if active {
907            return None;
908        }
909        let palette: ThemePalette = tokens.get_palette();
910        let geometry: ThemeGeometry = tokens.get_geometry();
911        let segment_radius: f32 = concentric_radius(geometry.get_radius_lg(), CONTROL_INSET);
912        let surface: SurfaceColors =
913            palette.interaction_colors(InteractionRole::SegmentedPill, false, true, false);
914        let mut hover_paint: PaintStyle = PaintStyle::default();
915        let _: &mut PaintStyle = hover_paint
916            .set_background(Some(surface.get_bg()))
917            .set_radius(CornerRadius::all(segment_radius))
918            .set_cursor(CursorIcon::Pointer);
919        Some(hover_paint)
920    }
921}