Skip to main content

euv_ui/component/nav_extra/
impl.rs

1use super::*;
2
3/// Fluent interactive selection and theme helpers for `EuvBreadcrumb`.
4impl EuvBreadcrumb {
5    /// Binds a reactive signal capturing the selected breadcrumb segment index when clicked.
6    ///
7    /// # Arguments
8    ///
9    /// - `Self` - Source breadcrumb.
10    /// - `Signal<usize>` - Active segment index signal.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Interactive breadcrumb trail.
15    #[must_use]
16    pub fn active(mut self, active: Signal<usize>) -> Self {
17        self.set_active(Some(active));
18        self
19    }
20
21    /// Resolves `(row_bg, text_fg)` for an interactive breadcrumb segment.
22    ///
23    /// # Arguments
24    ///
25    /// - `ThemePalette` - Live theme palette.
26    /// - `bool` - Whether this segment is active.
27    /// - `bool` - Whether the pointer is currently hovering this segment.
28    ///
29    /// # Returns
30    ///
31    /// - `(Color, Color)` - Paired segment background and readable foreground color.
32    #[must_use]
33    pub fn segment_colors(palette: ThemePalette, active: bool, hovered: bool) -> (Color, Color) {
34        if active {
35            let base: SurfaceColors = palette.surface(SurfaceRole::Background);
36            (COLOR_TRANSPARENT, base.get_fg())
37        } else {
38            let surface: SurfaceColors =
39                palette.interaction_colors(InteractionRole::NavItem, false, hovered, false);
40            (surface.get_bg(), surface.get_fg())
41        }
42    }
43}
44
45/// Declarative `#[component]` implementation for `EuvBreadcrumb`.
46#[component]
47/// Inherent implementation of [`EuvBreadcrumb`].
48impl EuvBreadcrumb {
49    /// Renders `EuvBreadcrumb` into the ambient framework-managed `Context`.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Component descriptor reference.
54    ///
55    /// # Returns
56    ///
57    /// - `NodeId` - Mounted root scene node handle.
58    fn render(&self) -> NodeId {
59        let mut ctx: Context = current_context();
60        let base_tokens: ThemeTokens = self.get_tokens();
61        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
62        let theme_palette: ThemePalette = init_tok.get_palette();
63        let geometry: ThemeGeometry = init_tok.get_geometry();
64        let Self {
65            segments, active, ..
66        } = self;
67        let active: Option<Signal<usize>> = *active;
68        let hovered_idx: Signal<Option<usize>> = Signal::new(None);
69        let last_idx: usize = segments.len().saturating_sub(1);
70        let fg_active: Color = theme_palette.surface(SurfaceRole::Background).get_fg();
71        let fg_muted: Color = theme_palette.get_muted_foreground();
72        let mut seg_nodes: Vec<(NodeId, NodeId)> = Vec::with_capacity(segments.len());
73        let mut owned_nodes: Vec<NodeId> = Vec::with_capacity(segments.len() * 2);
74        let mut row_items: Vec<NodeId> = Vec::with_capacity(segments.len() * 2);
75        let init_active: usize = active
76            .map(|source_val: Signal<usize>| source_val.get_untracked())
77            .unwrap_or(0);
78        for (idx, seg) in segments.iter().enumerate() {
79            if let Some(active_sig) = active {
80                let is_cur: bool = init_active == idx;
81                let (init_bg, init_fg): (Color, Color) =
82                    Self::segment_colors(theme_palette, is_cur, false);
83                let mut row_id: NodeId = NodeId::default();
84                let mut txt_id: NodeId = NodeId::default();
85                let on_pick = move |_: &UiEvent| {
86                    let _: bool = active_sig.set_if_changed(idx);
87                };
88                let on_enter = move |_: &UiEvent| {
89                    let _: bool = hovered_idx.set_if_changed(Some(idx));
90                };
91                let on_leave = move |_: &UiEvent| {
92                    if hovered_idx.get_untracked() == Some(idx) {
93                        let _: bool = hovered_idx.set_if_changed(None);
94                    }
95                };
96                let row_ninth_style: Style = style! {
97                    AlignItems::Center
98                    Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
99                    Radius(geometry.get_radius_sm())
100                    Background(init_bg)
101                    Overflow::Hidden
102                    CursorIcon::Pointer
103                };
104                let text_tenth_style: Style = style! {
105                    FontSize(13.0)
106                    if is_cur { FontWeight::SemiBold } else { FontWeight::Normal }
107                    TextColor(init_fg)
108                };
109                let item: NodeId = view! {
110                    row {
111                        node_ref: row_id
112                        style: row_ninth_style
113                        on_click: on_pick
114                        on_pointer_enter: on_enter
115                        on_pointer_leave: on_leave
116                        text {
117                            node_ref: txt_id
118                            style: text_tenth_style
119                            { seg.as_str() }
120                        }
121                    }
122                };
123                owned_nodes.push(row_id);
124                owned_nodes.push(txt_id);
125                seg_nodes.push((row_id, txt_id));
126                row_items.push(item);
127            } else {
128                row_items.push({
129                    let text_ninth_style: Style = style! {
130                        FontSize(13.0)
131                        TextColor(if idx == last_idx { fg_active } else { fg_muted })
132                    };
133                    view! {
134                        text {
135                            style: text_ninth_style
136                            { seg.as_str() }
137                        }
138                    }
139                });
140            }
141            if idx < last_idx {
142                row_items.push({
143                    let text_eighth_style: Style = style! {
144                        FontSize(12.0)
145                        TextColor(fg_muted)
146                    };
147                    view! {
148                        text {
149                            style: text_eighth_style
150                            { BREADCRUMB_SEP }
151                        }
152                    }
153                });
154            }
155        }
156        let row_eighth_style: Style = style! {
157            FlexWrap::Wrap
158            Width(Length::Percent(100.0))
159            AlignItems::Center
160            Gap(SPACE_XS)
161        };
162        let root: NodeId = view! {
163            row {
164                style: row_eighth_style
165            }
166        };
167        if !row_items.is_empty() {
168            ctx.append_many(root, row_items.as_slice());
169        }
170        if let Some(active_sig) = active {
171            let handle: SceneHandle = ctx.get_scene().clone();
172            let prev_state: Cell<(usize, Option<usize>, ThemeKey)> =
173                Cell::new((init_active, None, init_tok.key()));
174            let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
175                Effect::new(move || {
176                    let next_idx: usize = active_sig.get();
177                    let next_hover: Option<usize> = hovered_idx.get();
178                    let live_tok: ThemeTokens = use_live_tokens(base_tokens);
179                    let (old_idx, old_hover, old_key): (usize, Option<usize>, ThemeKey) =
180                        prev_state.replace((next_idx, next_hover, live_tok.key()));
181                    let theme_changed: bool = old_key != live_tok.key();
182                    if !theme_changed && old_idx == next_idx && old_hover == next_hover {
183                        return;
184                    }
185                    let live_p: ThemePalette = live_tok.get_palette();
186                    handle.with_write(
187                        |tree: &mut SceneTree| {
188                            let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
189                            let dirty_t: u16 = DIRTY_TEXT | DIRTY_PAINT;
190                            for (idx, &(row_id, txt_id)) in seg_nodes.iter().enumerate() {
191                                let affected: bool = theme_changed
192                                    || idx == old_idx
193                                    || idx == next_idx
194                                    || old_hover == Some(idx)
195                                    || next_hover == Some(idx);
196                                if !affected {
197                                    continue;
198                                }
199                                let is_cur: bool = idx == next_idx;
200                                let is_hov: bool = !is_cur && next_hover == Some(idx);
201                                let (bg, fg): (Color, Color) =
202                                    Self::segment_colors(live_p, is_cur, is_hov);
203                                if let Some(item_count) = tree.get_node_mut(row_id) {
204                                    item_count
205                                        .get_mut_style()
206                                        .get_mut_paint()
207                                        .set_background(Some(bg));
208                                    tree.mark_dirty(row_id, DIRTY_PAINT);
209                                }
210                                if let Some(node_entry) = tree.get_node_mut(txt_id) {
211                                    let weight_changed: bool = idx == old_idx || idx == next_idx;
212                                    node_entry
213                                        .get_mut_style()
214                                        .get_mut_text()
215                                        .set_weight(if is_cur {
216                                            FontWeight::SemiBold
217                                        } else {
218                                            FontWeight::Normal
219                                        })
220                                        .set_color(fg);
221                                    let mask: u16 = if weight_changed {
222                                        dirty_l | dirty_t
223                                    } else {
224                                        DIRTY_PAINT
225                                    };
226                                    tree.mark_dirty(txt_id, mask);
227                                }
228                            }
229                        },
230                        (),
231                    );
232                })
233            });
234            ctx.get_scene().with_write(
235                |tree: &mut SceneTree| {
236                    mark_theme_owned(tree, owned_nodes.as_slice());
237                    tree.attach_scope(root, scope);
238                },
239                (),
240            );
241        }
242        root
243    }
244}
245
246/// Declarative `#[component]` implementation for `EuvPagination`.
247#[component]
248/// Inherent implementation of [`EuvPagination`].
249impl EuvPagination {
250    /// Renders `EuvPagination` into the ambient framework-managed `Context`.
251    ///
252    /// # Arguments
253    ///
254    /// - `&Self` - Component descriptor reference.
255    ///
256    /// # Returns
257    ///
258    /// - `NodeId` - Mounted root scene node handle.
259    fn render(&self) -> NodeId {
260        let base_tokens: ThemeTokens = self.get_tokens();
261        let tokens: ThemeTokens = live_tokens_untracked(base_tokens);
262        let theme_palette: ThemePalette = tokens.get_palette();
263        let geometry: ThemeGeometry = tokens.get_geometry();
264        let current: Signal<usize> = self.get_current();
265        let total: usize = self.get_total_pages().max(1);
266        let bar_h: f32 = geometry.get_control_sm();
267        let on_prev = move |_: &UiEvent| {
268            let _: bool = {
269                if let Some(mut updated_value) = current.try_get_untracked() {
270                    {
271                        let item_val: &mut usize = &mut updated_value;
272                        *item_val = item_val.saturating_sub(1).max(1);
273                    }
274                    current.set(updated_value)
275                } else {
276                    false
277                }
278            };
279        };
280        let on_next = move |_: &UiEvent| {
281            let _: bool = {
282                if let Some(mut updated_value) = current.try_get_untracked() {
283                    {
284                        let tex_v: &mut usize = &mut updated_value;
285                        *tex_v = tex_v.saturating_add(1).min(total);
286                    }
287                    current.set(updated_value)
288                } else {
289                    false
290                }
291            };
292        };
293        let page_text = move || -> String { format!("{} / {total}", current.get()) };
294        let row_sixth_style: Style = style! {
295            FlexWrap::Wrap
296            AlignItems::Center
297            Gap(SPACE_SM)
298        };
299        let row_seventh_style: Style = style! {
300            Height(Length::Px(bar_h))
301            Padding(Edges::symmetric(0.0, SPACE_SM))
302            JustifyContent::Center
303            AlignItems::Center
304        };
305        let text_seventh_style: Style = style! {
306            FontSize(13.0)
307            FontWeight::Medium
308            TextColor(theme_palette.get_foreground())
309        };
310        view! {
311            row {
312                style: row_sixth_style
313                EuvButton {
314                    label: PAGE_PREV_LABEL.to_string()
315                    tokens: tokens
316                    outline()
317                    small()
318                    on_click: on_prev
319                }
320                row {
321                    style: row_seventh_style
322                    text {
323                        style: text_seventh_style
324                        { page_text }
325                    }
326                }
327                EuvButton {
328                    label: PAGE_NEXT_LABEL.to_string()
329                    tokens: tokens
330                    outline()
331                    small()
332                    on_click: on_next
333                }
334            }
335        }
336    }
337}
338
339/// Theme-aware contrast-safe paint helpers for `EuvSteps`.
340impl EuvSteps {
341    /// Resolves `(circle_bg, circle_border, number_fg)` for a step indicator circle.
342    ///
343    /// # Arguments
344    ///
345    /// - `ThemeTokens` - Live theme tokens.
346    /// - `bool` - Whether the step is active or completed.
347    ///
348    /// # Returns
349    ///
350    /// - `(Color, Border, Color)` - Paired circle fill, border, and readable step number foreground.
351    #[must_use]
352    pub fn step_colors(tokens: ThemeTokens, done: bool) -> (Color, Border, Color) {
353        let theme_palette: ThemePalette = tokens.get_palette();
354        let geometry: ThemeGeometry = tokens.get_geometry();
355        if done {
356            let primary: SurfaceColors = theme_palette.surface(SurfaceRole::Primary);
357            (
358                primary.get_bg(),
359                Border::new(0.0, primary.get_border()),
360                primary.get_fg(),
361            )
362        } else {
363            let secondary: SurfaceColors = theme_palette.surface(SurfaceRole::Secondary);
364            (
365                secondary.get_bg(),
366                Border::new(geometry.get_border_width(), secondary.get_border()),
367                secondary.get_fg(),
368            )
369        }
370    }
371}
372
373/// Declarative `#[component]` implementation for `EuvSteps`.
374#[component]
375/// Inherent implementation of [`EuvSteps`].
376impl EuvSteps {
377    /// Renders `EuvSteps` into the ambient framework-managed `Context`.
378    ///
379    /// # Arguments
380    ///
381    /// - `&Self` - Component descriptor reference.
382    ///
383    /// # Returns
384    ///
385    /// - `NodeId` - Mounted root scene node handle.
386    fn render(&self) -> NodeId {
387        let mut ctx: Context = current_context();
388        let base_tokens: ThemeTokens = self.get_tokens();
389        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
390        let theme_palette: ThemePalette = init_tok.get_palette();
391        let active: Signal<usize> = self.get_active();
392        let Self { labels, .. } = self;
393        let init_active: usize = active.get_untracked();
394        let mut step_nodes: Vec<(NodeId, NodeId)> = Vec::with_capacity(labels.len());
395        let mut owned_nodes: Vec<NodeId> = Vec::with_capacity(labels.len() * 2);
396        let mut row_items: Vec<NodeId> = Vec::with_capacity(labels.len());
397        for (idx, label_text) in labels.iter().enumerate() {
398            let done: bool = init_active >= idx;
399            let (init_bg, init_border, init_fg): (Color, Border, Color) =
400                Self::step_colors(init_tok, done);
401            let mut circle_id: NodeId = NodeId::default();
402            let mut num_id: NodeId = NodeId::default();
403            let on_pick = move |_: &UiEvent| {
404                let _: bool = active.set_if_changed(idx);
405            };
406            let row_quaternary_style: Style = style! {
407                AlignItems::Center
408                Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
409                Radius(init_tok.get_geometry().get_radius_md())
410                Gap(SPACE_SM)
411                CursorIcon::Pointer
412            };
413            let row_fifth_style: Style = style! {
414                Width(Length::Px(24.0))
415                Height(Length::Px(24.0))
416                FlexShrink(0.0)
417                JustifyContent::Center
418                AlignItems::Center
419                Radius(RADIUS_PILL)
420                Overflow::Hidden
421                Border::new(init_border.get_width(), init_border.get_color())
422                Background(init_bg)
423            };
424            let text_fifth_style: Style = style! {
425                FontSize(12.0)
426                FontWeight::Bold
427                TextColor(init_fg)
428            };
429            let text_sixth_style: Style = style! {
430                FontSize(13.0)
431                FontWeight::Medium
432                TextColor(theme_palette.get_foreground())
433            };
434            let item: NodeId = view! {
435                row {
436                    style: row_quaternary_style
437                    on_click: on_pick
438                    row {
439                        node_ref: circle_id
440                        style: row_fifth_style
441                        text {
442                            node_ref: num_id
443                            style: text_fifth_style
444                            { (idx + 1).to_string() }
445                        }
446                    }
447                    text {
448                        style: text_sixth_style
449                        { label_text.as_str() }
450                    }
451                }
452            };
453            owned_nodes.push(circle_id);
454            owned_nodes.push(num_id);
455            step_nodes.push((circle_id, num_id));
456            row_items.push(item);
457        }
458        let row_tertiary_style: Style = style! {
459            FlexWrap::Wrap
460            Width(Length::Percent(100.0))
461            Gap(SPACE_MD)
462        };
463        let root: NodeId = view! {
464            row {
465                style: row_tertiary_style
466            }
467        };
468        if !row_items.is_empty() {
469            ctx.append_many(root, row_items.as_slice());
470        }
471        let handle: SceneHandle = ctx.get_scene().clone();
472        let prev_state: Cell<(usize, ThemeKey)> = Cell::new((init_active, init_tok.key()));
473        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
474            Effect::new(move || {
475                let next_active: usize = active.get();
476                let live_tok: ThemeTokens = use_live_tokens(base_tokens);
477                let (old_active, old_key): (usize, ThemeKey) =
478                    prev_state.replace((next_active, live_tok.key()));
479                let theme_changed: bool = old_key != live_tok.key();
480                if !theme_changed && old_active == next_active {
481                    return;
482                }
483                let lo: usize = if theme_changed {
484                    0
485                } else {
486                    old_active.min(next_active)
487                };
488                let hi: usize = if theme_changed {
489                    step_nodes.len()
490                } else {
491                    old_active.max(next_active).min(step_nodes.len())
492                };
493                handle.with_write(
494                    |tree: &mut SceneTree| {
495                        for (idx, &(circle_id, num_id)) in step_nodes
496                            .iter()
497                            .enumerate()
498                            .skip(lo)
499                            .take(hi.saturating_sub(lo).saturating_add(1))
500                        {
501                            let done: bool = next_active >= idx;
502                            let (bg, border, fg): (Color, Border, Color) =
503                                Self::step_colors(live_tok, done);
504                            if let Some(item_count) = tree.get_node_mut(circle_id) {
505                                item_count
506                                    .get_mut_style()
507                                    .get_mut_paint()
508                                    .set_border(border)
509                                    .set_background(Some(bg));
510                                tree.mark_dirty(circle_id, DIRTY_PAINT);
511                            }
512                            if let Some(node_entry) = tree.get_node_mut(num_id) {
513                                node_entry.get_mut_style().get_mut_text().set_color(fg);
514                                tree.mark_dirty(num_id, DIRTY_PAINT);
515                            }
516                        }
517                    },
518                    (),
519                );
520            })
521        });
522        ctx.get_scene().with_write(
523            |tree: &mut SceneTree| {
524                mark_theme_owned(tree, owned_nodes.as_slice());
525                tree.attach_scope(root, scope);
526            },
527            (),
528        );
529        root
530    }
531}
532
533/// Theme-aware contrast-safe header helpers for `EuvAccordion`.
534impl EuvAccordion {
535    /// Resolves `(header_bg, title_fg)` for an accordion item header.
536    ///
537    /// # Arguments
538    ///
539    /// - `ThemePalette` - Live theme palette.
540    /// - `bool` - Whether the pointer is currently hovering the header.
541    ///
542    /// # Returns
543    ///
544    /// - `(Color, Color)` - Paired header background and readable title color.
545    #[must_use]
546    pub fn header_colors(palette: ThemePalette, hovered: bool) -> (Color, Color) {
547        let surface: SurfaceColors =
548            palette.interaction_colors(InteractionRole::GhostSurface, false, hovered, false);
549        (surface.get_bg(), surface.get_fg())
550    }
551}
552
553/// Declarative `#[component]` implementation for `EuvAccordion`.
554#[component]
555/// Inherent implementation of [`EuvAccordion`].
556impl EuvAccordion {
557    /// Renders `EuvAccordion` into the ambient framework-managed `Context`.
558    ///
559    /// # Arguments
560    ///
561    /// - `&Self` - Component descriptor reference.
562    ///
563    /// # Returns
564    ///
565    /// - `NodeId` - Mounted root scene node handle.
566    fn render(&self) -> NodeId {
567        let mut ctx: Context = current_context();
568        let base_tokens: ThemeTokens = self.get_tokens();
569        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
570        let theme_palette: ThemePalette = init_tok.get_palette();
571        let geometry: ThemeGeometry = init_tok.get_geometry();
572        let open_index: Signal<Option<usize>> = self.get_open_index();
573        let hovered_idx: Signal<Option<usize>> = Signal::new(None);
574        let Self { items, .. } = self;
575        let init_open: Option<usize> = open_index.get_untracked();
576        let mut entries: Vec<(NodeId, NodeId, NodeId, NodeId)> = Vec::with_capacity(items.len());
577        let mut owned_nodes: Vec<NodeId> = Vec::with_capacity(items.len() * 3);
578        let mut cards: Vec<NodeId> = Vec::with_capacity(items.len());
579        for (idx, item) in items.iter().enumerate() {
580            let is_open: bool = init_open == Some(idx);
581            let (init_hdr_bg, init_title_fg): (Color, Color) =
582                Self::header_colors(theme_palette, false);
583            let mut hdr_id: NodeId = NodeId::default();
584            let mut title_id: NodeId = NodeId::default();
585            let mut chev_id: NodeId = NodeId::default();
586            let mut body_id: NodeId = NodeId::default();
587            let on_toggle = move |_: &UiEvent| {
588                let _: bool = {
589                    if let Some(mut updated_value) = open_index.try_get_untracked() {
590                        {
591                            let cur: &mut Option<usize> = &mut updated_value;
592                            *cur = if *cur == Some(idx) { None } else { Some(idx) };
593                        }
594                        open_index.set(updated_value)
595                    } else {
596                        false
597                    }
598                };
599            };
600            let on_enter = move |_: &UiEvent| {
601                let _: bool = hovered_idx.set_if_changed(Some(idx));
602            };
603            let on_leave = move |_: &UiEvent| {
604                if hovered_idx.get_untracked() == Some(idx) {
605                    let _: bool = hovered_idx.set_if_changed(None);
606                }
607            };
608            let paint_chev = move |bounds: Rect, display_list: &mut DisplayList| {
609                let live_p: ThemePalette = live_tokens_untracked(base_tokens).get_palette();
610                let icon: EuvIconName = if open_index.get_untracked() == Some(idx) {
611                    EuvIconName::ChevronDown
612                } else {
613                    EuvIconName::ArrowRight
614                };
615                draw_euv_icon(icon, bounds, display_list, live_p.get_muted_foreground());
616            };
617            let column_tertiary_style: Style = style! {
618                Width(Length::Percent(100.0))
619                Background(theme_palette.get_card())
620                Border::new(geometry.get_border_width(), theme_palette.get_border())
621                Radius(geometry.get_radius_md())
622                Overflow::Hidden
623            };
624            let row_secondary_style: Style = style! {
625                Width(Length::Percent(100.0))
626                JustifyContent::SpaceBetween
627                AlignItems::Center
628                Gap(SPACE_SM)
629                Padding(Edges::symmetric(SPACE_SM, SPACE_MD))
630                Radius(concentric_radius(geometry.get_radius_md(), geometry.get_border_width()))
631                Background(init_hdr_bg)
632                CursorIcon::Pointer
633                Overflow::Hidden
634            };
635            let text_tertiary_style: Style = style! {
636                FlexGrow(1.0)
637                FlexShrink(1.0)
638                MinWidth(Length::Px(0.0))
639                FontSize(14.0)
640                FontWeight::SemiBold
641                TextColor(init_title_fg)
642            };
643            let canvas_style: Style = style! {
644                Width(Length::Px(12.0))
645                Height(Length::Px(12.0))
646                FlexShrink(0.0)
647            };
648            let column_quaternary_style: Style = style! {
649                if is_open { Display::Flex } else { Display::None }
650                Width(Length::Percent(100.0))
651                Padding(Edges::symmetric(SPACE_SM, SPACE_MD))
652                Overflow::Hidden
653            };
654            let text_quaternary_style: Style = style! {
655                Width(Length::Percent(100.0))
656                FontSize(13.0)
657                TextColor(theme_palette.get_muted_foreground())
658            };
659            let card: NodeId = view! {
660                column {
661                    style: column_tertiary_style
662                    row {
663                        node_ref: hdr_id
664                        style: row_secondary_style
665                        role: A11yRole::Button
666                        a11y_label: item.get_title().clone()
667                        on_click: on_toggle
668                        on_pointer_enter: on_enter
669                        on_pointer_leave: on_leave
670                        text {
671                            node_ref: title_id
672                            style: text_tertiary_style
673                            { item.get_title().as_str() }
674                        }
675                        canvas {
676                            node_ref: chev_id
677                            style: canvas_style
678                            painter: paint_chev
679                        }
680                    }
681                    column {
682                        node_ref: body_id
683                        style: column_quaternary_style
684                        text {
685                            style: text_quaternary_style
686                            { item.get_content().as_str() }
687                        }
688                    }
689                }
690            };
691            owned_nodes.push(hdr_id);
692            owned_nodes.push(title_id);
693            owned_nodes.push(chev_id);
694            entries.push((hdr_id, title_id, chev_id, body_id));
695            cards.push(card);
696        }
697        let column_secondary_style: Style = style! {
698            Width(Length::Percent(100.0))
699            Gap(SPACE_XS)
700        };
701        let root: NodeId = view! {
702            column {
703                style: column_secondary_style
704            }
705        };
706        if !cards.is_empty() {
707            ctx.append_many(root, cards.as_slice());
708        }
709        let handle: SceneHandle = ctx.get_scene().clone();
710        let prev_state: Cell<(Option<usize>, Option<usize>, ThemeKey)> =
711            Cell::new((init_open, None, init_tok.key()));
712        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
713            Effect::new(move || {
714                let next_open: Option<usize> = open_index.get();
715                let next_hover: Option<usize> = hovered_idx.get();
716                let live_tok: ThemeTokens = use_live_tokens(base_tokens);
717                let (old_open, old_hover, old_key): (Option<usize>, Option<usize>, ThemeKey) =
718                    prev_state.replace((next_open, next_hover, live_tok.key()));
719                let theme_changed: bool = old_key != live_tok.key();
720                if !theme_changed && old_open == next_open && old_hover == next_hover {
721                    return;
722                }
723                let live_p: ThemePalette = live_tok.get_palette();
724                handle.with_write(
725                    |tree: &mut SceneTree| {
726                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
727                        if old_open != next_open {
728                            if let Some(old_idx) = old_open
729                                && let Some(&(_, _, old_chev, old_body)) = entries.get(old_idx)
730                            {
731                                if let Some(item_count) = tree.get_node_mut(old_body) {
732                                    item_count
733                                        .get_mut_style()
734                                        .get_mut_layout()
735                                        .set_display(Display::None);
736                                    tree.mark_dirty(old_body, dirty_l | DIRTY_PAINT);
737                                }
738                                tree.mark_dirty(old_chev, DIRTY_PAINT);
739                            }
740                            if let Some(new_idx) = next_open
741                                && let Some(&(_, _, new_chev, new_body)) = entries.get(new_idx)
742                            {
743                                if let Some(node_entry) = tree.get_node_mut(new_body) {
744                                    node_entry
745                                        .get_mut_style()
746                                        .get_mut_layout()
747                                        .set_display(Display::Flex);
748                                    tree.mark_dirty(new_body, dirty_l | DIRTY_PAINT);
749                                }
750                                tree.mark_dirty(new_chev, DIRTY_PAINT);
751                            }
752                        }
753                        for (idx, &(hdr_id, title_id, chev_id, _)) in entries.iter().enumerate() {
754                            let paint_affected: bool =
755                                theme_changed || old_hover == Some(idx) || next_hover == Some(idx);
756                            if !paint_affected {
757                                continue;
758                            }
759                            let (hdr_bg, title_fg): (Color, Color) =
760                                Self::header_colors(live_p, next_hover == Some(idx));
761                            if let Some(normal_vec) = tree.get_node_mut(hdr_id) {
762                                normal_vec
763                                    .get_mut_style()
764                                    .get_mut_paint()
765                                    .set_background(Some(hdr_bg));
766                                tree.mark_dirty(hdr_id, DIRTY_PAINT);
767                            }
768                            if let Some(total_len) = tree.get_node_mut(title_id) {
769                                total_len.get_mut_style().get_mut_text().set_color(title_fg);
770                                tree.mark_dirty(title_id, DIRTY_PAINT);
771                            }
772                            if theme_changed {
773                                tree.mark_dirty(chev_id, DIRTY_PAINT);
774                            }
775                        }
776                    },
777                    (),
778                );
779            })
780        });
781        ctx.get_scene().with_write(
782            |tree: &mut SceneTree| {
783                mark_theme_owned(tree, owned_nodes.as_slice());
784                tree.attach_scope(root, scope);
785            },
786            (),
787        );
788        root
789    }
790}
791
792/// Theme-aware contrast-safe row helpers for `EuvToc`.
793impl EuvToc {
794    /// Resolves `(row_bg, label_fg)` for a table-of-contents row state.
795    ///
796    /// # Arguments
797    ///
798    /// - `ThemePalette` - Live theme palette.
799    /// - `bool` - Whether this heading is active.
800    /// - `bool` - Whether the pointer is currently hovering this row.
801    ///
802    /// # Returns
803    ///
804    /// - `(Color, Color)` - Paired row background and readable label color.
805    #[must_use]
806    pub fn row_colors(palette: ThemePalette, active: bool, hovered: bool) -> (Color, Color) {
807        let surface: SurfaceColors =
808            palette.interaction_colors(InteractionRole::NavItem, active, hovered, false);
809        (surface.get_bg(), surface.get_fg())
810    }
811}
812
813/// Declarative `#[component]` implementation for `EuvToc`.
814#[component]
815/// Inherent implementation of [`EuvToc`].
816impl EuvToc {
817    /// Renders `EuvToc` into the ambient framework-managed `Context`.
818    ///
819    /// # Arguments
820    ///
821    /// - `&Self` - Component descriptor reference.
822    ///
823    /// # Returns
824    ///
825    /// - `NodeId` - Mounted root scene node handle.
826    fn render(&self) -> NodeId {
827        let mut ctx: Context = current_context();
828        let base_tokens: ThemeTokens = self.get_tokens();
829        let init_tok: ThemeTokens = live_tokens_untracked(base_tokens);
830        let theme_palette: ThemePalette = init_tok.get_palette();
831        let geometry: ThemeGeometry = init_tok.get_geometry();
832        let active: Signal<usize> = self.get_active();
833        let hovered_idx: Signal<Option<usize>> = Signal::new(None);
834        let Self { headings, .. } = self;
835        let init_active: usize = active.get_untracked();
836        let outer_radius: f32 = geometry.get_radius_lg();
837        let row_radius: f32 = concentric_radius(outer_radius, CONTROL_INSET);
838        let mut row_entries: Vec<(NodeId, NodeId)> = Vec::with_capacity(headings.len());
839        let mut owned_nodes: Vec<NodeId> = Vec::with_capacity(headings.len() * 2);
840        let mut row_nodes: Vec<NodeId> = Vec::with_capacity(headings.len());
841        for (idx, height_val) in headings.iter().enumerate() {
842            let is_cur: bool = init_active == idx;
843            let (init_bg, init_fg): (Color, Color) = Self::row_colors(theme_palette, is_cur, false);
844            let mut row_id: NodeId = NodeId::default();
845            let mut lbl_id: NodeId = NodeId::default();
846            let on_pick = move |_: &UiEvent| {
847                let _: bool = active.set_if_changed(idx);
848            };
849            let on_enter = move |_: &UiEvent| {
850                let _: bool = hovered_idx.set_if_changed(Some(idx));
851            };
852            let on_leave = move |_: &UiEvent| {
853                if hovered_idx.get_untracked() == Some(idx) {
854                    let _: bool = hovered_idx.set_if_changed(None);
855                }
856            };
857            let row_style: Style = style! {
858                Width(Length::Percent(100.0))
859                AlignItems::Center
860                Padding(Edges::symmetric(SPACE_XS, SPACE_SM))
861                Radius(row_radius)
862                Background(init_bg)
863                Overflow::Hidden
864                CursorIcon::Pointer
865            };
866            let text_secondary_style: Style = style! {
867                FlexGrow(1.0)
868                FlexShrink(1.0)
869                MinWidth(Length::Px(0.0))
870                FontSize(13.0)
871                TextColor(init_fg)
872                Overflow::Hidden
873                TextOverflow::Ellipsis
874            };
875            let row_node: NodeId = view! {
876                row {
877                    node_ref: row_id
878                    style: row_style
879                    on_click: on_pick
880                    on_pointer_enter: on_enter
881                    on_pointer_leave: on_leave
882                    text {
883                        node_ref: lbl_id
884                        style: text_secondary_style
885                        { height_val.as_str() }
886                    }
887                }
888            };
889            owned_nodes.push(row_id);
890            owned_nodes.push(lbl_id);
891            row_entries.push((row_id, lbl_id));
892            row_nodes.push(row_node);
893        }
894        let column_style: Style = style! {
895            Width(Length::Percent(100.0))
896            Padding(Edges::all(SPACE_MD))
897            Gap(CONTROL_INSET)
898            Background(theme_palette.get_muted())
899            Border::new(geometry.get_border_width(), theme_palette.get_border())
900            Radius(outer_radius)
901            Overflow::Hidden
902        };
903        let text_style: Style = style! {
904            Width(Length::Percent(100.0))
905            FontSize(12.0)
906            FontWeight::Bold
907            TextColor(theme_palette.get_muted_foreground())
908        };
909        let root: NodeId = view! {
910            column {
911                style: column_style
912                text {
913                    style: text_style
914                    { TOC_HEADING_DEFAULT }
915                }
916            }
917        };
918        if !row_nodes.is_empty() {
919            ctx.append_many(root, row_nodes.as_slice());
920        }
921        let handle: SceneHandle = ctx.get_scene().clone();
922        let prev_state: Cell<(usize, Option<usize>, ThemeKey)> =
923            Cell::new((init_active, None, init_tok.key()));
924        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
925            Effect::new(move || {
926                let next_active: usize = active.get();
927                let next_hover: Option<usize> = hovered_idx.get();
928                let live_tok: ThemeTokens = use_live_tokens(base_tokens);
929                let (old_active, old_hover, old_key): (usize, Option<usize>, ThemeKey) =
930                    prev_state.replace((next_active, next_hover, live_tok.key()));
931                let theme_changed: bool = old_key != live_tok.key();
932                if !theme_changed && old_active == next_active && old_hover == next_hover {
933                    return;
934                }
935                let live_p: ThemePalette = live_tok.get_palette();
936                handle.with_write(
937                    |tree: &mut SceneTree| {
938                        for (idx, &(row_id, lbl_id)) in row_entries.iter().enumerate() {
939                            let affected: bool = theme_changed
940                                || idx == old_active
941                                || idx == next_active
942                                || old_hover == Some(idx)
943                                || next_hover == Some(idx);
944                            if !affected {
945                                continue;
946                            }
947                            let is_cur: bool = idx == next_active;
948                            let is_hov: bool = !is_cur && next_hover == Some(idx);
949                            let (bg, fg): (Color, Color) = Self::row_colors(live_p, is_cur, is_hov);
950                            if let Some(item_count) = tree.get_node_mut(row_id) {
951                                item_count
952                                    .get_mut_style()
953                                    .get_mut_paint()
954                                    .set_background(Some(bg));
955                                tree.mark_dirty(row_id, DIRTY_PAINT);
956                            }
957                            if let Some(node_entry) = tree.get_node_mut(lbl_id) {
958                                node_entry.get_mut_style().get_mut_text().set_color(fg);
959                                tree.mark_dirty(lbl_id, DIRTY_PAINT);
960                            }
961                        }
962                    },
963                    (),
964                );
965            })
966        });
967        ctx.get_scene().with_write(
968            |tree: &mut SceneTree| {
969                mark_theme_owned(tree, owned_nodes.as_slice());
970                tree.attach_scope(root, scope);
971            },
972            (),
973        );
974        root
975    }
976}