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