Skip to main content

euv_ui/component/display/
impl.rs

1use super::*;
2
3/// Tone color resolution helper for `EuvTone`.
4impl EuvTone {
5    /// Resolves `(background, foreground)` colors for this tone under `palette`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Semantic tone.
10    /// - `ThemePalette` - Active theme palette.
11    ///
12    /// # Returns
13    ///
14    /// - `(Color, Color)` - Background and foreground colors.
15    #[inline(always)]
16    #[must_use]
17    pub fn colors(&self, palette: ThemePalette) -> (Color, Color) {
18        let role: SurfaceRole = match *self {
19            Self::Neutral => SurfaceRole::Secondary,
20            Self::Primary => SurfaceRole::Primary,
21            Self::Success => SurfaceRole::Success,
22            Self::Warning => SurfaceRole::Warning,
23            Self::Destructive => SurfaceRole::Destructive,
24        };
25        let surface: SurfaceColors = palette.surface(role);
26        (surface.get_bg(), surface.get_fg())
27    }
28}
29
30/// Fluent tone builder for `EuvBadge`.
31impl EuvBadge {
32    /// Overrides the semantic tone fluently.
33    ///
34    /// # Arguments
35    ///
36    /// - `Self` - Source badge.
37    /// - `EuvTone` - Target semantic tone.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Updated badge.
42    #[must_use]
43    pub fn tone(mut self, tone: EuvTone) -> Self {
44        self.set_tone(tone);
45        self
46    }
47}
48
49/// Declarative `#[component]` implementation for `EuvBadge`.
50#[component]
51/// Inherent implementation of [`EuvBadge`].
52impl EuvBadge {
53    /// Renders `EuvBadge` into the ambient framework-managed `Context`.
54    ///
55    /// # Arguments
56    ///
57    /// - `&Self` - Component descriptor reference.
58    ///
59    /// # Returns
60    ///
61    /// - `NodeId` - Mounted root scene node handle.
62    fn render(&self) -> NodeId {
63        let ctx: Context = current_context();
64        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
65        let p: ThemePalette = tokens.get_palette();
66        let g: ThemeGeometry = tokens.get_geometry();
67        let (bg, fg): (Color, Color) = self.get_tone().colors(p);
68        let Self { label, .. } = self;
69        let mut row_st: Style = Style::default();
70        row_st
71            .get_mut_layout()
72            .set_flex_direction(FlexDirection::Row)
73            .set_height(Length::Px(24.0))
74            .set_justify_content(JustifyContent::Center)
75            .set_align_items(AlignItems::Center)
76            .set_padding(Edges::symmetric(0.0, SPACE_SM))
77            .set_overflow(Overflow::Hidden);
78        row_st
79            .get_mut_paint()
80            .set_background(Some(bg))
81            .set_border(Border::new(
82                g.get_border_width(),
83                p.get_border().with_alpha(72),
84            ))
85            .set_radius(CornerRadius::all(RADIUS_PILL));
86        let mut txt_st: Style = Style::default();
87        txt_st
88            .get_mut_text()
89            .set_font_size(11.0)
90            .set_weight(FontWeight::SemiBold)
91            .set_color(fg)
92            .set_align(TextAlign::Center)
93            .set_overflow(TextOverflow::Ellipsis);
94        ctx.get_scene().with_write(
95            |tree: &mut SceneTree| {
96                let root: NodeId = tree.create_view(row_st);
97                let txt_id: NodeId = tree.create_text(label.clone(), txt_st);
98                tree.append_child(root, txt_id);
99                root
100            },
101            NodeId::default(),
102        )
103    }
104}
105
106/// Declarative `#[component]` implementation for `EuvAlert`.
107#[component]
108/// Inherent implementation of [`EuvAlert`].
109impl EuvAlert {
110    /// Renders `EuvAlert` into the ambient framework-managed `Context`.
111    ///
112    /// # Arguments
113    ///
114    /// - `&Self` - Component descriptor reference.
115    ///
116    /// # Returns
117    ///
118    /// - `NodeId` - Mounted root scene node handle.
119    fn render(&self) -> NodeId {
120        let ctx: Context = current_context();
121        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
122        let p: ThemePalette = tokens.get_palette();
123        let g: ThemeGeometry = tokens.get_geometry();
124        let (accent, _): (Color, Color) = self.get_tone().colors(p);
125        let muted_surface: SurfaceColors = p.surface(SurfaceRole::Muted);
126        let border_col: Color = match self.get_tone() {
127            EuvTone::Primary | EuvTone::Neutral => p.get_border(),
128            _ => accent.with_alpha(152),
129        };
130        let Self {
131            title,
132            description,
133            style,
134            ..
135        } = self;
136        let mut col_st: Style = Style::default();
137        col_st
138            .get_mut_layout()
139            .set_flex_direction(FlexDirection::Column)
140            .set_width(Length::Percent(100.0))
141            .set_padding(Edges::all(SPACE_MD))
142            .set_row_gap(SPACE_XS)
143            .set_column_gap(SPACE_XS)
144            .set_overflow(Overflow::Hidden);
145        col_st
146            .get_mut_paint()
147            .set_background(Some(muted_surface.get_bg()))
148            .set_border(Border::new(g.get_border_width().max(0.0), border_col))
149            .set_radius(CornerRadius::all(g.get_radius_md().max(0.0)));
150        col_st = col_st.with_overrides(*style);
151        let mut title_st: Style = Style::default();
152        title_st.get_mut_layout().set_width(Length::Percent(100.0));
153        title_st
154            .get_mut_text()
155            .set_font_size(14.0)
156            .set_weight(FontWeight::SemiBold)
157            .set_color(muted_surface.get_fg());
158        let mut desc_st: Style = Style::default();
159        desc_st.get_mut_layout().set_width(Length::Percent(100.0));
160        desc_st
161            .get_mut_text()
162            .set_font_size(13.0)
163            .set_color(p.get_muted_foreground());
164        ctx.get_scene().with_write(
165            |tree: &mut SceneTree| {
166                let root: NodeId = tree.create_view(col_st);
167                let title_id: NodeId = tree.create_text(title.clone(), title_st);
168                let desc_id: NodeId = tree.create_text(description.clone(), desc_st);
169                tree.append_children(root, &[title_id, desc_id]);
170                root
171            },
172            NodeId::default(),
173        )
174    }
175}
176
177/// Declarative `#[component]` implementation for `EuvProgress`.
178#[component]
179/// Inherent implementation of [`EuvProgress`].
180impl EuvProgress {
181    /// Renders `EuvProgress` into the ambient framework-managed `Context`.
182    ///
183    /// Track and fill share `RADIUS_PILL` with crisp, fringe-free end caps: `pct <= 0.001` renders track only,
184    /// `pct >= 0.999` renders fill only, and intermediate percentages paint non-overlapping clipped pill halves
185    /// while always reading live theme tokens.
186    ///
187    /// # Arguments
188    ///
189    /// - `&Self` - Component descriptor reference.
190    ///
191    /// # Returns
192    ///
193    /// - `NodeId` - Mounted root scene node handle.
194    fn render(&self) -> NodeId {
195        let base_tokens: ThemeTokens = self.get_tokens();
196        let mut track_st: Style = style! {
197            width: Length::Percent(100.0)
198            height: Length::Px(8.0)
199            radius: RADIUS_PILL
200            overflow: Overflow::Hidden
201        };
202        track_st = track_st.with_overrides(self.get_style());
203        if let Length::Px(px) = track_st.get_layout().get_height() {
204            let clamped: f32 = if px > 0.0 { px.max(4.0) } else { 8.0 };
205            let _: &mut LayoutStyle = track_st.get_mut_layout().set_height(Length::Px(clamped));
206        }
207        let frac: f32 = self.get_value().clamp(0.0, 1.0);
208        let paint_progress = move |bounds: Rect, dl: &mut DisplayList| {
209            let p: ThemePalette = live_tokens_untracked(base_tokens).get_palette();
210            let pill: CornerRadius = CornerRadius::all(RADIUS_PILL);
211            if frac <= 0.001 {
212                dl.push(DrawCommand::FillRoundedRect {
213                    rect: bounds,
214                    color: p.get_secondary(),
215                    radius: pill,
216                    border: Border::default(),
217                });
218                return;
219            }
220            if frac >= 0.999 {
221                dl.push(DrawCommand::FillRoundedRect {
222                    rect: bounds,
223                    color: p.get_primary(),
224                    radius: pill,
225                    border: Border::default(),
226                });
227                return;
228            }
229            let total_w: f32 = bounds.get_width();
230            let split_w: f32 = (total_w * frac).round().clamp(0.0, total_w);
231            if split_w <= 0.0 {
232                dl.push(DrawCommand::FillRoundedRect {
233                    rect: bounds,
234                    color: p.get_secondary(),
235                    radius: pill,
236                    border: Border::default(),
237                });
238                return;
239            }
240            if split_w >= total_w {
241                dl.push(DrawCommand::FillRoundedRect {
242                    rect: bounds,
243                    color: p.get_primary(),
244                    radius: pill,
245                    border: Border::default(),
246                });
247                return;
248            }
249            let x: f32 = bounds.get_x();
250            let y: f32 = bounds.get_y();
251            let track_h: f32 = bounds.get_height();
252            dl.push(DrawCommand::PushClip(Rect::new(x, y, split_w, track_h)));
253            dl.push(DrawCommand::FillRoundedRect {
254                rect: bounds,
255                color: p.get_primary(),
256                radius: pill,
257                border: Border::default(),
258            });
259            dl.push(DrawCommand::PopClip);
260            dl.push(DrawCommand::PushClip(Rect::new(
261                x + split_w,
262                y,
263                (total_w - split_w).max(0.0),
264                track_h,
265            )));
266            dl.push(DrawCommand::FillRoundedRect {
267                rect: bounds,
268                color: p.get_secondary(),
269                radius: pill,
270                border: Border::default(),
271            });
272            dl.push(DrawCommand::PopClip);
273        };
274        view! {
275            canvas {
276                style: track_st
277                painter: paint_progress
278            }
279        }
280    }
281}
282
283/// Window calculation, clamped scrolling, and reactive mounting for `EuvVirtualList`.
284impl EuvVirtualList {
285    /// Sets the visible scroll viewport height in logical pixels fluently.
286    ///
287    /// # Arguments
288    ///
289    /// - `Self` - Source virtual list.
290    /// - `f32` - Viewport height in logical pixels.
291    ///
292    /// # Returns
293    ///
294    /// - `Self` - Updated virtual list.
295    #[must_use]
296    pub fn viewport_height(mut self, height: f32) -> Self {
297        self.set_viewport_height(height);
298        self
299    }
300
301    /// Sets the overscan row count mounted above and below the viewport fluently.
302    ///
303    /// # Arguments
304    ///
305    /// - `Self` - Source virtual list.
306    /// - `usize` - Number of extra rows to mount per edge.
307    ///
308    /// # Returns
309    ///
310    /// - `Self` - Updated virtual list.
311    #[must_use]
312    pub fn overscan(mut self, overscan: usize) -> Self {
313        self.set_overscan(overscan);
314        self
315    }
316
317    /// Resolves effective viewport height (defaulting to `320.0` when unset).
318    ///
319    /// # Arguments
320    ///
321    /// - `&Self` - Virtual list configuration.
322    ///
323    /// # Returns
324    ///
325    /// - `f32` - Resolved viewport height in logical pixels.
326    #[must_use]
327    fn resolved_viewport_height(&self) -> f32 {
328        let h: f32 = self.get_viewport_height();
329        if h > 0.0 { h } else { 320.0 }
330    }
331
332    /// Returns the maximum valid scroll Y offset in logical pixels.
333    ///
334    /// # Arguments
335    ///
336    /// - `&Self` - Virtual list configuration.
337    ///
338    /// # Returns
339    ///
340    /// - `f32` - Upper scroll bound `>= 0.0`.
341    #[must_use]
342    pub fn max_scroll_y(&self) -> f32 {
343        let total_h: f32 = (self.get_total_items() as f32) * self.get_item_height().max(1.0);
344        (total_h - self.resolved_viewport_height().max(1.0)).max(0.0)
345    }
346
347    /// Advances the reactive scroll offset by `delta_y`, clamped to `[0.0, max_scroll_y()]`.
348    ///
349    /// # Arguments
350    ///
351    /// - `&Self` - Virtual list configuration.
352    /// - `f32` - Incremental vertical scroll delta in logical pixels.
353    pub fn scroll_by(&self, delta_y: f32) {
354        let max_y: f32 = self.max_scroll_y();
355        let next: f32 = (self.get_scroll_y().get_untracked() + delta_y).clamp(0.0, max_y);
356        let _: bool = self.get_scroll_y().set_if_changed(next);
357    }
358
359    /// Computes the `(start_index, end_index_exclusive)` window of rows visible in the viewport.
360    ///
361    /// # Arguments
362    ///
363    /// - `&Self` - Virtual list configuration.
364    ///
365    /// # Returns
366    ///
367    /// - `(usize, usize)` - Half-open range of indices to materialize.
368    #[must_use]
369    pub fn visible_range(&self) -> (usize, usize) {
370        let total: usize = self.get_total_items();
371        if total == 0 {
372            return (0, 0);
373        }
374        let item_h: f32 = self.get_item_height().max(1.0);
375        let view_h: f32 = self.resolved_viewport_height().max(1.0);
376        let scroll_y: f32 = self
377            .get_scroll_y()
378            .get_untracked()
379            .clamp(0.0, self.max_scroll_y());
380        let overscan: usize = if self.get_overscan() == 0 {
381            3
382        } else {
383            self.get_overscan()
384        };
385        let first_vis: usize = (scroll_y / item_h).floor() as usize;
386        let vis_count: usize = (view_h / item_h).ceil() as usize;
387        let start: usize = first_vis.saturating_sub(overscan);
388        let end: usize = (first_vis + vis_count + overscan).min(total);
389        (start, end)
390    }
391
392    /// Mounts a reactive clipped scrollable list returning a controller handle for O(1) stable-ID single-row patches and refreshes.
393    ///
394    /// # Arguments
395    ///
396    /// - `&Self` - Virtual list configuration.
397    /// - `F` - Zero-context row builder closure taking `usize` row index and returning `NodeId`.
398    ///
399    /// # Returns
400    ///
401    /// - `EuvVirtualListHandle` - Mounted viewport root and targeted single-row update controller.
402    #[must_use]
403    pub fn mount_with_handle<F>(&self, row_builder: F) -> EuvVirtualListHandle
404    where
405        F: FnMut(usize) -> NodeId + 'static,
406    {
407        let mut ctx: Context = current_context();
408        let live_tok: ThemeTokens = live_tokens_untracked(self.get_tokens());
409        let p: ThemePalette = live_tok.get_palette();
410        let g: ThemeGeometry = live_tok.get_geometry();
411        let scroll_sig: Signal<f32> = self.get_scroll_y();
412        let total_items: usize = self.get_total_items();
413        let overscan: usize = if self.get_overscan() == 0 {
414            3
415        } else {
416            self.get_overscan()
417        };
418        let view_h: f32 = self.resolved_viewport_height().max(1.0);
419        let builder_cell: Rc<RefCell<dyn FnMut(usize) -> NodeId + 'static>> =
420            Rc::new(RefCell::new(row_builder));
421        let builder_for_effect: Rc<RefCell<dyn FnMut(usize) -> NodeId + 'static>> =
422            Rc::clone(&builder_cell);
423        let border_w: f32 = g.get_border_width();
424        let inner_view_h: f32 = (view_h - border_w * 2.0).max(1.0);
425        let item_h: f32 = self.get_item_height().max(1.0);
426        let vis_count: usize = (view_h / item_h).ceil() as usize;
427        let total_h: f32 = (total_items as f32) * item_h;
428        let max_scroll: f32 = (total_h - inner_view_h).max(0.0);
429        let max_scroll_range: f32 = self.max_scroll_y();
430        let on_vlist_scroll = move |ev: &UiEvent| {
431            if let UiEventKind::Scroll(delta) = ev.get_kind() {
432                let next: f32 = (scroll_sig.get_untracked() + delta.get_y()).clamp(0.0, max_scroll);
433                let _: bool = scroll_sig.set_if_changed(next);
434            }
435        };
436        let container: NodeId = view! {
437            scroll {
438                style: {
439                    Style::default().column()
440                    width: Length::Percent(100.0)
441                    height: Length::Px(view_h)
442                    background: p.get_card()
443                    border: (border_w, p.get_border())
444                    radius: g.get_radius_md()
445                }
446                on_scroll: on_vlist_scroll
447            }
448        };
449        let mut rows_host_style: Style = Style::default();
450        rows_host_style
451            .get_mut_layout()
452            .set_flex_direction(FlexDirection::Column)
453            .set_width(Length::Percent(100.0));
454        let rows_host: NodeId = ctx.view(rows_host_style);
455        ctx.append(container, rows_host);
456        let init_scroll: f32 = scroll_sig.get_untracked().clamp(0.0, max_scroll);
457        ctx.set_virtual_scroll(container, init_scroll, total_h);
458        let scene_for_rows: SceneHandle = ctx.get_scene().clone();
459        let scene_for_handle: SceneHandle = scene_for_rows.clone();
460        let ctx_for_rows: Context = ctx.clone();
461        let ctx_for_handle: Context = ctx.clone();
462        let window: Rc<RefCell<VecDeque<(usize, Scope, NodeId)>>> =
463            Rc::new(RefCell::new(VecDeque::new()));
464        let window_effect: Rc<RefCell<VecDeque<(usize, Scope, NodeId)>>> = Rc::clone(&window);
465        let window_handle: Rc<RefCell<VecDeque<(usize, Scope, NodeId)>>> = Rc::clone(&window);
466        let (vlist_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
467            let window_cleanup: Rc<RefCell<VecDeque<(usize, Scope, NodeId)>>> = Rc::clone(&window);
468            on_cleanup(move || {
469                if let Ok(mut guard) = window_cleanup.try_borrow_mut() {
470                    while let Some((_, row_scope, _)) = guard.pop_front() {
471                        row_scope.dispose();
472                    }
473                }
474            });
475            let mut current_range: (usize, usize) = (0, 0);
476            let mut initialized: bool = false;
477            let mut retired_scopes: Vec<Scope> = Vec::new();
478            let mut retired_nodes: Vec<NodeId> = Vec::new();
479            let mut built_prefix: Vec<(usize, Scope, NodeId)> = Vec::new();
480            let mut built_suffix: Vec<(usize, Scope, NodeId)> = Vec::new();
481            let mut next_children: Vec<NodeId> = Vec::new();
482            Effect::new(move || {
483                let raw_scroll: f32 = scroll_sig.get();
484                let cur_scroll: f32 = raw_scroll.clamp(0.0, max_scroll);
485                let (new_start, new_end): (usize, usize) = if total_items == 0 {
486                    (0, 0)
487                } else {
488                    let clamped_for_range: f32 = raw_scroll.clamp(0.0, max_scroll_range);
489                    let first_vis: usize = (clamped_for_range / item_h).floor() as usize;
490                    let start: usize = first_vis.saturating_sub(overscan);
491                    let end: usize = (first_vis + vis_count + overscan).min(total_items);
492                    (start, end)
493                };
494                let local_scroll_y: f32 = (cur_scroll - (new_start as f32) * item_h).max(0.0);
495                if initialized && (new_start, new_end) == current_range {
496                    scene_for_rows.with_write(
497                        |tree: &mut SceneTree| {
498                            tree.set_virtual_scroll(container, cur_scroll, total_h);
499                            tree.set_scroll_offset(container, Point::new(0.0, local_scroll_y));
500                        },
501                        (),
502                    );
503                    return;
504                }
505                let (old_start, old_end): (usize, usize) = current_range;
506                let has_overlap: bool = initialized
507                    && old_start < old_end
508                    && new_start < new_end
509                    && new_start < old_end
510                    && old_start < new_end;
511                retired_scopes.clear();
512                retired_nodes.clear();
513                let (prefix_start, prefix_end, suffix_start, suffix_end): (
514                    usize,
515                    usize,
516                    usize,
517                    usize,
518                ) = if has_overlap {
519                    if let Ok(mut guard) = window_effect.try_borrow_mut() {
520                        while let Some(&(idx, _, _)) = guard.front() {
521                            if idx < new_start {
522                                if let Some((_, scope, node_id)) = guard.pop_front() {
523                                    retired_scopes.push(scope);
524                                    retired_nodes.push(node_id);
525                                }
526                            } else {
527                                break;
528                            }
529                        }
530                        while let Some(&(idx, _, _)) = guard.back() {
531                            if idx >= new_end {
532                                if let Some((_, scope, node_id)) = guard.pop_back() {
533                                    retired_scopes.push(scope);
534                                    retired_nodes.push(node_id);
535                                }
536                            } else {
537                                break;
538                            }
539                        }
540                    }
541                    let keep_start: usize = old_start.max(new_start);
542                    let keep_end: usize = old_end.min(new_end);
543                    (new_start, keep_start, keep_end, new_end)
544                } else {
545                    if let Ok(mut guard) = window_effect.try_borrow_mut() {
546                        retired_scopes.reserve(guard.len());
547                        retired_nodes.reserve(guard.len());
548                        while let Some((_, scope, node_id)) = guard.pop_front() {
549                            retired_scopes.push(scope);
550                            retired_nodes.push(node_id);
551                        }
552                    }
553                    (new_start, new_end, new_end, new_end)
554                };
555                for retired in retired_scopes.drain(..) {
556                    retired.dispose();
557                }
558                let prefix_len: usize = prefix_end.saturating_sub(prefix_start);
559                let suffix_len: usize = suffix_end.saturating_sub(suffix_start);
560                built_prefix.clear();
561                built_suffix.clear();
562                if prefix_len > 0 || suffix_len > 0 {
563                    built_prefix.reserve(prefix_len);
564                    built_suffix.reserve(suffix_len);
565                    untracked(|| {
566                        with_context(ctx_for_rows.clone(), || {
567                            if let Ok(mut build_row) = builder_for_effect.try_borrow_mut() {
568                                for idx in prefix_start..prefix_end {
569                                    let (row_scope, row_node): (Scope, NodeId) =
570                                        Scope::run(|_: Scope| build_row(idx));
571                                    built_prefix.push((idx, row_scope, row_node));
572                                }
573                                for idx in suffix_start..suffix_end {
574                                    let (row_scope, row_node): (Scope, NodeId) =
575                                        Scope::run(|_: Scope| build_row(idx));
576                                    built_suffix.push((idx, row_scope, row_node));
577                                }
578                            }
579                        });
580                    });
581                }
582                next_children.clear();
583                next_children.reserve(new_end.saturating_sub(new_start));
584                if let Ok(mut guard) = window_effect.try_borrow_mut() {
585                    for entry in built_prefix.drain(..).rev() {
586                        guard.push_front(entry);
587                    }
588                    for entry in built_suffix.drain(..) {
589                        guard.push_back(entry);
590                    }
591                    for &(_, _, node_id) in guard.iter() {
592                        next_children.push(node_id);
593                    }
594                }
595                current_range = (new_start, new_end);
596                initialized = true;
597                scene_for_rows.with_write(
598                    |tree: &mut SceneTree| {
599                        for old_node in retired_nodes.drain(..) {
600                            tree.dispose_subtree(old_node);
601                        }
602                        let _: bool =
603                            tree.set_children_detached(rows_host, next_children.as_slice());
604                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
605                        let dirty_c: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
606                        tree.mark_dirty(rows_host, dirty_l | dirty_c);
607                        tree.set_virtual_scroll(container, cur_scroll, total_h);
608                        tree.set_scroll_offset(container, Point::new(0.0, local_scroll_y));
609                    },
610                    (),
611                );
612            })
613        });
614        ctx.get_scene().with_write(
615            |tree: &mut SceneTree| {
616                tree.attach_scope(container, vlist_scope);
617            },
618            (),
619        );
620        EuvVirtualListHandle {
621            container,
622            rows_host,
623            scene: scene_for_handle,
624            ctx: ctx_for_handle,
625            window: window_handle,
626            builder: builder_cell,
627        }
628    }
629
630    /// Mounts a reactive clipped scrollable list materializing only the visible row window as `scroll_y` changes.
631    ///
632    /// # Arguments
633    ///
634    /// - `&Self` - Virtual list configuration.
635    /// - `F` - Zero-context row builder closure taking `usize` row index and returning `NodeId`.
636    ///
637    /// # Returns
638    ///
639    /// - `NodeId` - Mounted reactive scroll viewport handle.
640    pub fn mount_with<F>(&self, row_builder: F) -> NodeId
641    where
642        F: FnMut(usize) -> NodeId + 'static,
643    {
644        self.mount_with_handle(row_builder).root()
645    }
646
647    /// Mounts a zero-allocation pooled virtual list that recycles mounted row subtrees and rebinds them in place on scroll.
648    ///
649    /// # Arguments
650    ///
651    /// - `&Self` - Virtual list configuration.
652    /// - `Init` - Factory constructing one reusable row subtree `(row_root, row_state)` per pool slot.
653    /// - `Bind` - In-place binder updating a recycled row's `row_state` for a new item index inside `SceneTree`.
654    ///
655    /// # Returns
656    ///
657    /// - `NodeId` - Mounted reactive scroll viewport handle.
658    pub fn mount_pooled<S, Init, Bind>(&self, mut create_row: Init, mut bind_row: Bind) -> NodeId
659    where
660        S: 'static,
661        Init: FnMut() -> (NodeId, S) + 'static,
662        Bind: FnMut(&mut S, usize, &mut SceneTree) + 'static,
663    {
664        let mut ctx: Context = current_context();
665        let live_tok: ThemeTokens = live_tokens_untracked(self.get_tokens());
666        let p: ThemePalette = live_tok.get_palette();
667        let g: ThemeGeometry = live_tok.get_geometry();
668        let scroll_sig: Signal<f32> = self.get_scroll_y();
669        let total_items: usize = self.get_total_items();
670        let overscan: usize = if self.get_overscan() == 0 {
671            3
672        } else {
673            self.get_overscan()
674        };
675        let view_h: f32 = self.resolved_viewport_height().max(1.0);
676        let border_w: f32 = g.get_border_width();
677        let inner_view_h: f32 = (view_h - border_w * 2.0).max(1.0);
678        let item_h: f32 = self.get_item_height().max(1.0);
679        let vis_count: usize = (view_h / item_h).ceil() as usize;
680        let total_h: f32 = (total_items as f32) * item_h;
681        let max_scroll: f32 = (total_h - inner_view_h).max(0.0);
682        let max_scroll_range: f32 = self.max_scroll_y();
683        let on_vlist_scroll = move |ev: &UiEvent| {
684            if let UiEventKind::Scroll(delta) = ev.get_kind() {
685                let next: f32 = (scroll_sig.get_untracked() + delta.get_y()).clamp(0.0, max_scroll);
686                let _: bool = scroll_sig.set_if_changed(next);
687            }
688        };
689        let container: NodeId = view! {
690            scroll {
691                style: {
692                    Style::default().column()
693                    width: Length::Percent(100.0)
694                    height: Length::Px(view_h)
695                    background: p.get_card()
696                    border: (border_w, p.get_border())
697                    radius: g.get_radius_md()
698                }
699                on_scroll: on_vlist_scroll
700            }
701        };
702        let mut rows_host_style: Style = Style::default();
703        rows_host_style
704            .get_mut_layout()
705            .set_flex_direction(FlexDirection::Column)
706            .set_width(Length::Percent(100.0));
707        let rows_host: NodeId = ctx.view(rows_host_style);
708        ctx.append(container, rows_host);
709        let init_scroll: f32 = scroll_sig.get_untracked().clamp(0.0, max_scroll);
710        ctx.set_virtual_scroll(container, init_scroll, total_h);
711        let _: usize = overscan;
712        let max_pool_slots: usize = vis_count.saturating_add(1).min(total_items);
713        let spare_pool_rc: Rc<RefCell<Vec<(NodeId, S)>>> =
714            Rc::new(RefCell::new(Vec::with_capacity(max_pool_slots)));
715        untracked(|| {
716            with_context(ctx.clone(), || {
717                let mut pool_guard: RefMut<'_, Vec<(NodeId, S)>> = spare_pool_rc.borrow_mut();
718                for _ in 0..max_pool_slots {
719                    pool_guard.push(create_row());
720                }
721            });
722        });
723        let scene_for_rows: SceneHandle = ctx.get_scene().clone();
724        let scene_for_cleanup: SceneHandle = ctx.get_scene().clone();
725        let spare_for_cleanup: Rc<RefCell<Vec<(NodeId, S)>>> = Rc::clone(&spare_pool_rc);
726        let (vlist_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
727            on_cleanup(move || {
728                let detached: Vec<(NodeId, S)> = take(&mut *spare_for_cleanup.borrow_mut());
729                if !detached.is_empty() {
730                    scene_for_cleanup.with_write(
731                        |tree: &mut SceneTree| {
732                            for (node_id, _) in detached.into_iter() {
733                                tree.dispose_subtree(node_id);
734                            }
735                        },
736                        (),
737                    );
738                }
739            });
740            let mut active_window: VecDeque<(usize, NodeId, S)> =
741                VecDeque::with_capacity(max_pool_slots);
742            let mut next_children: Vec<NodeId> = Vec::with_capacity(max_pool_slots);
743            let mut current_range: (usize, usize) = (0, 0);
744            let mut initialized: bool = false;
745            Effect::new(move || {
746                let raw_scroll: f32 = scroll_sig.get();
747                let cur_scroll: f32 = raw_scroll.clamp(0.0, max_scroll);
748                let (new_start, new_end): (usize, usize) = if total_items == 0 {
749                    (0, 0)
750                } else {
751                    let clamped_for_range: f32 = raw_scroll.clamp(0.0, max_scroll_range);
752                    let first_vis: usize = (clamped_for_range / item_h).floor() as usize;
753                    let start: usize = first_vis.min(total_items.saturating_sub(max_pool_slots));
754                    let end: usize = start.saturating_add(max_pool_slots).min(total_items);
755                    (start, end)
756                };
757                let local_scroll_y: f32 = (cur_scroll - (new_start as f32) * item_h).max(0.0);
758                if initialized && (new_start, new_end) == current_range {
759                    scene_for_rows.with_write(
760                        |tree: &mut SceneTree| {
761                            tree.set_virtual_scroll(container, cur_scroll, total_h);
762                            tree.set_scroll_offset(container, Point::new(0.0, local_scroll_y));
763                        },
764                        (),
765                    );
766                    return;
767                }
768                let (old_start, old_end): (usize, usize) = current_range;
769                let new_len: usize = new_end.saturating_sub(new_start);
770                if initialized && new_len == active_window.len() {
771                    current_range = (new_start, new_end);
772                    scene_for_rows.with_write(
773                        |tree: &mut SceneTree| {
774                            for (entry, idx) in active_window.iter_mut().zip(new_start..new_end) {
775                                if entry.0 != idx {
776                                    entry.0 = idx;
777                                    bind_row(&mut entry.2, idx, tree);
778                                }
779                            }
780                            tree.set_virtual_scroll(container, cur_scroll, total_h);
781                            tree.set_scroll_offset(container, Point::new(0.0, local_scroll_y));
782                        },
783                        (),
784                    );
785                    return;
786                }
787                let has_overlap: bool = initialized
788                    && old_start < old_end
789                    && new_start < new_end
790                    && new_start < old_end
791                    && old_start < new_end;
792                let (prefix_start, prefix_end, suffix_start, suffix_end): (
793                    usize,
794                    usize,
795                    usize,
796                    usize,
797                ) = {
798                    let Ok(mut spare_pool) = spare_pool_rc.try_borrow_mut() else {
799                        return;
800                    };
801                    if has_overlap {
802                        while let Some(&(idx, _, _)) = active_window.front() {
803                            if idx < new_start {
804                                if let Some((_, node_id, state)) = active_window.pop_front() {
805                                    spare_pool.push((node_id, state));
806                                }
807                            } else {
808                                break;
809                            }
810                        }
811                        while let Some(&(idx, _, _)) = active_window.back() {
812                            if idx >= new_end {
813                                if let Some((_, node_id, state)) = active_window.pop_back() {
814                                    spare_pool.push((node_id, state));
815                                }
816                            } else {
817                                break;
818                            }
819                        }
820                        let keep_start: usize = old_start.max(new_start);
821                        let keep_end: usize = old_end.min(new_end);
822                        (new_start, keep_start, keep_end, new_end)
823                    } else {
824                        while let Some((_, node_id, state)) = active_window.pop_front() {
825                            spare_pool.push((node_id, state));
826                        }
827                        (new_start, new_end, new_end, new_end)
828                    }
829                };
830                current_range = (new_start, new_end);
831                initialized = true;
832                scene_for_rows.with_write(
833                    |tree: &mut SceneTree| {
834                        if let Ok(mut spare_pool) = spare_pool_rc.try_borrow_mut() {
835                            for idx in (prefix_start..prefix_end).rev() {
836                                if let Some((node_id, mut state)) = spare_pool.pop() {
837                                    bind_row(&mut state, idx, tree);
838                                    active_window.push_front((idx, node_id, state));
839                                }
840                            }
841                            for idx in suffix_start..suffix_end {
842                                if let Some((node_id, mut state)) = spare_pool.pop() {
843                                    bind_row(&mut state, idx, tree);
844                                    active_window.push_back((idx, node_id, state));
845                                }
846                            }
847                        }
848                        next_children.clear();
849                        for &(_, node_id, _) in active_window.iter() {
850                            next_children.push(node_id);
851                        }
852                        let _: bool =
853                            tree.set_children_detached(rows_host, next_children.as_slice());
854                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
855                        let dirty_c: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
856                        tree.mark_dirty(rows_host, dirty_l | dirty_c);
857                        tree.set_virtual_scroll(container, cur_scroll, total_h);
858                        tree.set_scroll_offset(container, Point::new(0.0, local_scroll_y));
859                    },
860                    (),
861                );
862            })
863        });
864        ctx.get_scene().with_write(
865            |tree: &mut SceneTree| {
866                tree.attach_scope(container, vlist_scope);
867            },
868            (),
869        );
870        container
871    }
872}
873
874/// Stable-ID O(1) single-row lookup, surgical patching, and isolated refresh operations for `EuvVirtualListHandle`.
875impl EuvVirtualListHandle {
876    /// Returns the mounted scrollable container `NodeId`.
877    ///
878    /// # Arguments
879    ///
880    /// - `&Self` - Virtual list controller reference.
881    ///
882    /// # Returns
883    ///
884    /// - `NodeId` - Mounted container root handle.
885    #[must_use]
886    pub fn root(&self) -> NodeId {
887        let Self { container, .. } = self;
888        *container
889    }
890
891    /// Resolves the mounted `NodeId` for logical row `index` in O(1) when currently materialized in the viewport window.
892    ///
893    /// # Arguments
894    ///
895    /// - `&Self` - Virtual list controller reference.
896    /// - `usize` - Stable logical row index.
897    ///
898    /// # Returns
899    ///
900    /// - `Option<NodeId>` - Active row node handle if currently visible, or `None` when off-screen.
901    #[must_use]
902    pub fn row_node(&self, index: usize) -> Option<NodeId> {
903        let Self { window, .. } = self;
904        let guard: Ref<'_, VecDeque<(usize, Scope, NodeId)>> = window.try_borrow().ok()?;
905        let &(start_idx, _, _) = guard.front()?;
906        let slot: usize = index.checked_sub(start_idx)?;
907        let &(found_idx, _, node_id) = guard.get(slot)?;
908        if found_idx == index {
909            Some(node_id)
910        } else {
911            None
912        }
913    }
914
915    /// Mutates a single materialized row in place inside one `SceneTree` write lock without rebuilding sibling rows or invalidating `rows_host` children.
916    ///
917    /// # Arguments
918    ///
919    /// - `&Self` - Virtual list controller reference.
920    /// - `usize` - Stable logical row index to patch.
921    /// - `F` - Mutation closure receiving `(&mut SceneTree, NodeId)` for the target row.
922    ///
923    /// # Returns
924    ///
925    /// - `bool` - `true` when `index` was materialized and patched, or `false` when off-screen.
926    pub fn patch_row<F>(&self, index: usize, patch: F) -> bool
927    where
928        F: FnOnce(&mut SceneTree, NodeId),
929    {
930        let Some(target_node) = self.row_node(index) else {
931            return false;
932        };
933        let Self { scene, .. } = self;
934        scene.with_write(
935            |tree: &mut SceneTree| {
936                if tree.get_node(target_node).is_some() {
937                    patch(tree, target_node);
938                    true
939                } else {
940                    false
941                }
942            },
943            false,
944        )
945    }
946
947    /// Rebuilds and swaps only the single materialized row at logical `index` in O(1), leaving all sibling rows and their layout caches untouched.
948    ///
949    /// # Arguments
950    ///
951    /// - `&Self` - Virtual list controller reference.
952    /// - `usize` - Stable logical row index to refresh.
953    ///
954    /// # Returns
955    ///
956    /// - `bool` - `true` when `index` was visible and refreshed, or `false` when off-screen.
957    pub fn update_row(&self, index: usize) -> bool {
958        let Self {
959            rows_host,
960            scene,
961            ctx,
962            window,
963            builder,
964            ..
965        } = self;
966        let slot_opt: Option<usize> = window.try_borrow().ok().and_then(
967            |guard: Ref<'_, VecDeque<(usize, Scope, NodeId)>>| {
968                let &(start_idx, _, _) = guard.front()?;
969                let slot: usize = index.checked_sub(start_idx)?;
970                let &(found_idx, _, _) = guard.get(slot)?;
971                if found_idx == index { Some(slot) } else { None }
972            },
973        );
974        let Some(slot) = slot_opt else {
975            return false;
976        };
977        let built_opt: Option<(Scope, NodeId)> = untracked(|| {
978            with_context(ctx.clone(), || {
979                builder.try_borrow_mut().ok().map(
980                    |mut build_row: RefMut<'_, dyn FnMut(usize) -> NodeId + 'static>| {
981                        Scope::run(|_: Scope| build_row(index))
982                    },
983                )
984            })
985        });
986        let Some((new_scope, new_node)) = built_opt else {
987            return false;
988        };
989        let replaced: Option<(Scope, NodeId)> = window.try_borrow_mut().ok().and_then(
990            |mut guard: RefMut<'_, VecDeque<(usize, Scope, NodeId)>>| {
991                let entry: &mut (usize, Scope, NodeId) = guard.get_mut(slot)?;
992                if entry.0 != index {
993                    return None;
994                }
995                let old_entry: (usize, Scope, NodeId) =
996                    replace(entry, (index, new_scope, new_node));
997                Some((old_entry.1, old_entry.2))
998            },
999        );
1000        let Some((old_scope, old_node)) = replaced else {
1001            new_scope.dispose();
1002            scene.with_write(
1003                |tree: &mut SceneTree| {
1004                    tree.dispose_subtree(new_node);
1005                },
1006                (),
1007            );
1008            return false;
1009        };
1010        old_scope.dispose();
1011        let host_id: NodeId = *rows_host;
1012        scene.with_write(
1013            |tree: &mut SceneTree| {
1014                let _: bool = tree.replace_child(host_id, old_node, new_node);
1015                tree.dispose_subtree(old_node);
1016                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1017                let dirty_c: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1018                tree.mark_dirty(host_id, dirty_l | dirty_c);
1019            },
1020            (),
1021        );
1022        true
1023    }
1024}
1025
1026/// Internal table grid and fullscreen modal builders for `EuvTable`.
1027impl EuvTable {
1028    /// Builds the dynamically sized unclipped table grid node tree directly inside `tree`.
1029    ///
1030    /// # Arguments
1031    ///
1032    /// - `&mut SceneTree` - Mutable retained scene tree.
1033    /// - `&[String]` - Ordered column header labels.
1034    /// - `&[Vec<String>]` - Matrix of row cell strings.
1035    /// - `&[f32]` - Precomputed per-column natural widths in logical pixels.
1036    /// - `(f32, Option<TextSelectMode>)` - Total natural width and optional text selection mode.
1037    /// - `ThemeTokens` - Active design tokens.
1038    ///
1039    /// # Returns
1040    ///
1041    /// - `NodeId` - Mounted table inner column root handle.
1042    fn mount_table_grid_in_tree(
1043        tree: &mut SceneTree,
1044        headers: &[String],
1045        rows: &[Vec<String>],
1046        col_widths: &[f32],
1047        grid_opts: (f32, Option<TextSelectMode>),
1048        tokens: ThemeTokens,
1049    ) -> NodeId {
1050        let (total_w, text_select): (f32, Option<TextSelectMode>) = grid_opts;
1051        let p: ThemePalette = tokens.get_palette();
1052        let g: ThemeGeometry = tokens.get_geometry();
1053        let col_count: usize = col_widths.len();
1054        let safe_total_w: f32 = total_w.max(1.0);
1055        let border_h: f32 = g.get_border_width().max(1.0);
1056        let mut inner_col_st: Style = Style::default();
1057        if let Some(mode) = text_select {
1058            inner_col_st = inner_col_st.text_select(mode);
1059        }
1060        inner_col_st
1061            .get_mut_layout()
1062            .set_flex_direction(FlexDirection::Column)
1063            .set_min_width(Length::Px(safe_total_w))
1064            .set_width(Length::Percent(100.0))
1065            .set_flex_shrink(0.0);
1066        let inner_col: NodeId = tree.create_view(inner_col_st);
1067        let mut head_row_st: Style = Style::default();
1068        head_row_st
1069            .get_mut_layout()
1070            .set_flex_direction(FlexDirection::Row)
1071            .set_width(Length::Percent(100.0))
1072            .set_align_items(AlignItems::Stretch)
1073            .set_overflow(Overflow::Hidden);
1074        head_row_st
1075            .get_mut_paint()
1076            .set_background(Some(p.get_muted()));
1077        let head_row: NodeId = tree.create_view(head_row_st);
1078        let mut hdr_txt_st: Style = Style::default();
1079        hdr_txt_st
1080            .get_mut_layout()
1081            .set_width(Length::Percent(100.0));
1082        hdr_txt_st
1083            .get_mut_text()
1084            .set_font_size(TABLE_HEADER_FONT_SIZE)
1085            .set_weight(FontWeight::SemiBold)
1086            .set_color(p.get_muted_foreground())
1087            .set_overflow(TextOverflow::Wrap);
1088        let mut body_txt_st: Style = Style::default();
1089        body_txt_st
1090            .get_mut_layout()
1091            .set_width(Length::Percent(100.0));
1092        body_txt_st
1093            .get_mut_text()
1094            .set_font_size(TABLE_BODY_FONT_SIZE)
1095            .set_color(p.get_foreground())
1096            .set_overflow(TextOverflow::Wrap);
1097        let mut cell_styles: Vec<Style> = Vec::with_capacity(col_count);
1098        for &cw in col_widths.iter() {
1099            let pct: f32 = (cw / safe_total_w) * 100.0;
1100            let mut st: Style = Style::default();
1101            st.get_mut_layout()
1102                .set_flex_direction(FlexDirection::Row)
1103                .set_width(Length::Percent(pct))
1104                .set_min_width(Length::Px(cw))
1105                .set_flex_shrink(0.0)
1106                .set_align_items(AlignItems::Center)
1107                .set_padding(Edges::symmetric(SPACE_SM, SPACE_MD))
1108                .set_overflow(Overflow::Hidden);
1109            cell_styles.push(st);
1110        }
1111        let mut cell_buf: Vec<NodeId> = Vec::with_capacity(col_count);
1112        for (ci, &cell_style) in cell_styles.iter().enumerate() {
1113            let label: &str = headers.get(ci).map(String::as_str).unwrap_or("");
1114            let cell_node: NodeId = tree.create_view(cell_style);
1115            let txt_node: NodeId = tree.create_text(label.to_string(), hdr_txt_st);
1116            tree.append_child(cell_node, txt_node);
1117            cell_buf.push(cell_node);
1118        }
1119        if !cell_buf.is_empty() {
1120            tree.append_children(head_row, &cell_buf);
1121        }
1122        let mut div_st: Style = Style::default();
1123        div_st
1124            .get_mut_layout()
1125            .set_width(Length::Percent(100.0))
1126            .set_height(Length::Px(border_h));
1127        div_st.get_mut_paint().set_background(Some(p.get_border()));
1128        let mut data_row_st: Style = Style::default();
1129        data_row_st
1130            .get_mut_layout()
1131            .set_flex_direction(FlexDirection::Row)
1132            .set_width(Length::Percent(100.0))
1133            .set_align_items(AlignItems::Stretch)
1134            .set_overflow(Overflow::Hidden);
1135        let even_bg: Color = p.get_card();
1136        let odd_bg: Color = p.get_muted().with_alpha(96);
1137        let mut all_rows: Vec<NodeId> = Vec::with_capacity(rows.len() * 2 + 1);
1138        all_rows.push(head_row);
1139        for (ri, row_cells) in rows.iter().enumerate() {
1140            let div_node: NodeId = tree.create_view(div_st);
1141            let mut row_st: Style = data_row_st;
1142            row_st
1143                .get_mut_paint()
1144                .set_background(Some(if ri % 2 == 1 { odd_bg } else { even_bg }));
1145            let row_node: NodeId = tree.create_view(row_st);
1146            cell_buf.clear();
1147            for (ci, &cell_style) in cell_styles.iter().enumerate() {
1148                let cell_str: &str = row_cells.get(ci).map(String::as_str).unwrap_or("");
1149                let cell_node: NodeId = tree.create_view(cell_style);
1150                let txt_node: NodeId = tree.create_text(cell_str.to_string(), body_txt_st);
1151                tree.append_child(cell_node, txt_node);
1152                cell_buf.push(cell_node);
1153            }
1154            if !cell_buf.is_empty() {
1155                tree.append_children(row_node, &cell_buf);
1156            }
1157            all_rows.push(div_node);
1158            all_rows.push(row_node);
1159        }
1160        tree.append_children(inner_col, &all_rows);
1161        inner_col
1162    }
1163
1164    /// Mounts the full-viewport 2D scrollable fullscreen modal card for `EuvTable` on demand.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&Context` - Active build context.
1169    /// - `ThemeTokens` - Fallback design tokens resolved against live ambient theme.
1170    /// - `&[String]` - Ordered column header labels.
1171    /// - `&[Vec<String>]` - Matrix of row cell strings.
1172    /// - `&[f32]` - Precomputed per-column natural widths in logical pixels.
1173    /// - `(f32, Option<TextSelectMode>, Signal<bool>)` - Tuple of `(total_w, text_select, fs_open)`.
1174    ///
1175    /// # Returns
1176    ///
1177    /// - `NodeId` - Mounted fullscreen modal card root handle.
1178    fn mount_fullscreen_modal_card(
1179        ctx: &Context,
1180        tokens: ThemeTokens,
1181        headers: &[String],
1182        rows: &[Vec<String>],
1183        col_widths: &[f32],
1184        modal_opts: (f32, Option<TextSelectMode>, Signal<bool>),
1185    ) -> NodeId {
1186        let (total_w, text_select, fs_open): (f32, Option<TextSelectMode>, Signal<bool>) =
1187            modal_opts;
1188        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
1189        let live_p: ThemePalette = live_tok.get_palette();
1190        let live_g: ThemeGeometry = live_tok.get_geometry();
1191        let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
1192        let init_safe: SafeAreaInsets = safe_sig.get_untracked();
1193        let summary_text: String = format!(
1194            "{TABLE_HEADER_TITLE} · {} cols × {} rows",
1195            col_widths.len(),
1196            rows.len()
1197        );
1198        let grid_node: NodeId = ctx.get_scene().with_write(
1199            |tree: &mut SceneTree| {
1200                Self::mount_table_grid_in_tree(
1201                    tree,
1202                    headers,
1203                    rows,
1204                    col_widths,
1205                    (total_w, text_select),
1206                    live_tok,
1207                )
1208            },
1209            NodeId::default(),
1210        );
1211        let on_close_click = move |_: &UiEvent| {
1212            let _: bool = fs_open.set_if_changed(false);
1213        };
1214        let paint_close_icon = move |bounds: Rect, dl: &mut DisplayList| {
1215            let cur_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
1216            let close_fg: Color = cur_p.surface(SurfaceRole::Card).get_fg();
1217            draw_euv_icon(EuvIconName::Close, bounds, dl, close_fg);
1218        };
1219        let close_btn_sz: f32 = live_g.get_control_sm();
1220        let mut top_bar_node: NodeId = NodeId::default();
1221        let mut body_scroll_node: NodeId = NodeId::default();
1222        let card: NodeId = view! {
1223            column {
1224                style: {
1225                    width: Length::Percent(100.0)
1226                    height: Length::Percent(100.0)
1227                    margin: Edges::all(0.0)
1228                    padding: Edges::all(0.0)
1229                    background: live_p.get_card()
1230                    radius: 0.0
1231                    overflow: Overflow::Hidden
1232                    stop_scroll_propagation: true
1233                    stop_event_propagation: true
1234                }
1235                row {
1236                    node_ref: top_bar_node
1237                    style: {
1238                        width: Length::Percent(100.0)
1239                        padding: Edges::new(
1240                            SPACE_SM + init_safe.get_top(),
1241                            SPACE_MD + init_safe.get_right(),
1242                            SPACE_SM,
1243                            SPACE_MD + init_safe.get_left()
1244                        )
1245                        justify: JustifyContent::SpaceBetween
1246                        align: AlignItems::Center
1247                        gap: SPACE_SM
1248                        background: live_p.get_muted()
1249                        overflow: Overflow::Hidden
1250                        text_select: TextSelectMode::None
1251                    }
1252                    text {
1253                        style: {
1254                            flex_grow: 1.0
1255                            flex_shrink: 1.0
1256                            min_width: Length::Px(0.0)
1257                            font_size: 13.0
1258                            font_weight: FontWeight::SemiBold
1259                            color: live_p.get_foreground()
1260                            text_overflow: TextOverflow::Ellipsis
1261                        }
1262                        { summary_text }
1263                    }
1264                    row {
1265                        style: {
1266                            width: Length::Px(close_btn_sz)
1267                            height: Length::Px(close_btn_sz)
1268                            flex_shrink: 0.0
1269                            justify: JustifyContent::Center
1270                            align: AlignItems::Center
1271                            background: live_p.get_card()
1272                            border: (live_g.get_border_width(), live_p.get_border())
1273                            radius: live_g.get_radius_sm()
1274                            overflow: Overflow::Hidden
1275                            cursor: CursorIcon::Pointer
1276                        }
1277                        role: A11yRole::Button
1278                        a11y_label: TABLE_BTN_CLOSE.to_string()
1279                        on_click: on_close_click
1280                        canvas {
1281                            style: {
1282                                width: Length::Px(14.0)
1283                                height: Length::Px(14.0)
1284                            }
1285                            painter: paint_close_icon
1286                        }
1287                    }
1288                }
1289                view {
1290                    style: {
1291                        width: Length::Percent(100.0)
1292                        height: Length::Px(live_g.get_border_width().max(1.0))
1293                        background: live_p.get_border()
1294                    }
1295                }
1296                scroll {
1297                    node_ref: body_scroll_node
1298                    style: {
1299                        Style::default().column()
1300                        flex_grow: 1.0
1301                        flex_shrink: 1.0
1302                        min_height: Length::Px(0.0)
1303                        width: Length::Percent(100.0)
1304                        align: AlignItems::Start
1305                        padding: Edges::new(
1306                            SPACE_MD,
1307                            SPACE_MD + init_safe.get_right(),
1308                            SPACE_MD + init_safe.get_bottom(),
1309                            SPACE_MD + init_safe.get_left()
1310                        )
1311                        stop_scroll_propagation: true
1312                    }
1313                    { grid_node }
1314                }
1315            }
1316        };
1317        let handle_safe: SceneHandle = ctx.get_scene().clone();
1318        let (safe_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1319            Effect::new(move || {
1320                let safe: SafeAreaInsets = safe_sig.get();
1321                handle_safe.with_write(
1322                    |tree: &mut SceneTree| {
1323                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1324                        if let Some(n) = tree.get_node_mut(top_bar_node) {
1325                            n.get_mut_style().get_mut_layout().set_padding(Edges::new(
1326                                SPACE_SM + safe.get_top(),
1327                                SPACE_MD + safe.get_right(),
1328                                SPACE_SM,
1329                                SPACE_MD + safe.get_left(),
1330                            ));
1331                            tree.mark_dirty(top_bar_node, dirty_l | DIRTY_PAINT);
1332                        }
1333                        if let Some(n) = tree.get_node_mut(body_scroll_node) {
1334                            n.get_mut_style().get_mut_layout().set_padding(Edges::new(
1335                                SPACE_MD,
1336                                SPACE_MD + safe.get_right(),
1337                                SPACE_MD + safe.get_bottom(),
1338                                SPACE_MD + safe.get_left(),
1339                            ));
1340                            tree.mark_dirty(body_scroll_node, dirty_l | DIRTY_PAINT);
1341                        }
1342                    },
1343                    (),
1344                );
1345            })
1346        });
1347        ctx.get_scene().with_write(
1348            |tree: &mut SceneTree| {
1349                tree.attach_scope(card, safe_scope);
1350            },
1351            (),
1352        );
1353        card
1354    }
1355}
1356
1357/// Declarative `#[component]` implementation for `EuvTable`.
1358#[component]
1359/// Inherent implementation of [`EuvTable`].
1360impl EuvTable {
1361    /// Renders `EuvTable` into the ambient framework-managed `Context` with dynamic unclipped column widths, 2D scrolling, and a fullscreen modal view.
1362    ///
1363    /// # Arguments
1364    ///
1365    /// - `&Self` - Component descriptor reference.
1366    ///
1367    /// # Returns
1368    ///
1369    /// - `NodeId` - Mounted root scene node handle.
1370    fn render(&self) -> NodeId {
1371        let ctx: Context = current_context();
1372        let base_tokens: ThemeTokens = self.get_tokens();
1373        let tokens: ThemeTokens = live_tokens_untracked(base_tokens);
1374        let p: ThemePalette = tokens.get_palette();
1375        let g: ThemeGeometry = tokens.get_geometry();
1376        let Self {
1377            headers,
1378            rows,
1379            style,
1380            ..
1381        } = self;
1382        let table_style: Option<Style> = *style;
1383        let table_text_select: Option<TextSelectMode> =
1384            table_style.and_then(|s: Style| s.get_text().text_select_mode());
1385        let (col_widths, total_w): (Vec<f32>, f32) = compute_table_column_widths(
1386            headers,
1387            rows,
1388            TABLE_HEADER_FONT_SIZE,
1389            TABLE_BODY_FONT_SIZE,
1390        );
1391        let summary_text: String = format!(
1392            "{TABLE_HEADER_TITLE} · {} cols × {} rows",
1393            col_widths.len(),
1394            rows.len()
1395        );
1396        let headers_rc: Rc<[String]> = Rc::from(headers.as_slice());
1397        let rows_rc: Rc<[Vec<String>]> = Rc::from(rows.as_slice());
1398        let col_widths_rc: Rc<[f32]> = Rc::from(col_widths.as_slice());
1399        let fs_open_slot: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
1400        let radius_md: CornerRadius = CornerRadius::all(g.get_radius_md().max(0.0));
1401        let radius_sm: CornerRadius = CornerRadius::all(g.get_radius_sm().max(0.0));
1402        let border_w: f32 = g.get_border_width().max(1.0);
1403        let ctrl_sm: f32 = g.get_control_sm();
1404        ctx.get_scene().with_write(
1405            |tree: &mut SceneTree| {
1406                let mut root_st: Style = Style::default();
1407                root_st
1408                    .get_mut_layout()
1409                    .set_flex_direction(FlexDirection::Column)
1410                    .set_width(Length::Percent(100.0))
1411                    .set_overflow(Overflow::Hidden);
1412                root_st
1413                    .get_mut_paint()
1414                    .set_background(Some(p.get_card()))
1415                    .set_border(Border::new(g.get_border_width(), p.get_border()))
1416                    .set_radius(radius_md);
1417                root_st = root_st.with_overrides(table_style);
1418                let root: NodeId = tree.create_view(root_st);
1419                let mut toolbar_st: Style = Style::default().text_select(TextSelectMode::None);
1420                toolbar_st
1421                    .get_mut_layout()
1422                    .set_flex_direction(FlexDirection::Row)
1423                    .set_width(Length::Percent(100.0))
1424                    .set_padding(Edges::symmetric(SPACE_XS, SPACE_MD))
1425                    .set_justify_content(JustifyContent::SpaceBetween)
1426                    .set_align_items(AlignItems::Center)
1427                    .set_row_gap(SPACE_SM)
1428                    .set_column_gap(SPACE_SM)
1429                    .set_overflow(Overflow::Hidden);
1430                toolbar_st
1431                    .get_mut_paint()
1432                    .set_background(Some(p.get_muted()));
1433                let toolbar_row: NodeId = tree.create_view(toolbar_st);
1434                let mut title_st: Style = Style::default();
1435                title_st
1436                    .get_mut_layout()
1437                    .set_flex_grow(1.0)
1438                    .set_flex_shrink(1.0)
1439                    .set_min_width(Length::Px(0.0));
1440                title_st
1441                    .get_mut_text()
1442                    .set_font_size(11.5)
1443                    .set_weight(FontWeight::SemiBold)
1444                    .set_color(p.get_muted_foreground())
1445                    .set_overflow(TextOverflow::Ellipsis);
1446                let title_node: NodeId = tree.create_text(summary_text, title_st);
1447                let mut fs_btn_st: Style = Style::default();
1448                fs_btn_st
1449                    .get_mut_layout()
1450                    .set_flex_direction(FlexDirection::Row)
1451                    .set_width(Length::Px(ctrl_sm))
1452                    .set_height(Length::Px(ctrl_sm))
1453                    .set_flex_shrink(0.0)
1454                    .set_justify_content(JustifyContent::Center)
1455                    .set_align_items(AlignItems::Center)
1456                    .set_overflow(Overflow::Hidden);
1457                fs_btn_st
1458                    .get_mut_paint()
1459                    .set_background(Some(p.get_card()))
1460                    .set_border(Border::new(g.get_border_width(), p.get_border()))
1461                    .set_radius(radius_sm)
1462                    .set_cursor(CursorIcon::Pointer);
1463                let fs_btn: NodeId = tree.create_view(fs_btn_st);
1464                let mut icon_st: Style = Style::default();
1465                icon_st
1466                    .get_mut_layout()
1467                    .set_width(Length::Px(13.0))
1468                    .set_height(Length::Px(13.0));
1469                let paint_fs_icon: CanvasDrawCallback =
1470                    Rc::new(RefCell::new(move |bounds: Rect, dl: &mut DisplayList| {
1471                        let cur_p: ThemePalette = live_tokens_untracked(base_tokens).get_palette();
1472                        let fg: Color = cur_p.surface(SurfaceRole::Card).get_fg();
1473                        draw_euv_icon(EuvIconName::Maximize, bounds, dl, fg);
1474                    }));
1475                let fs_icon: NodeId = tree.create_canvas(icon_st, paint_fs_icon);
1476                tree.append_child(fs_btn, fs_icon);
1477                tree.append_children(toolbar_row, &[title_node, fs_btn]);
1478                let mut div_st: Style = Style::default();
1479                div_st
1480                    .get_mut_layout()
1481                    .set_width(Length::Percent(100.0))
1482                    .set_height(Length::Px(border_w));
1483                div_st.get_mut_paint().set_background(Some(p.get_border()));
1484                let div_node: NodeId = tree.create_view(div_st);
1485                let mut scroll_st: Style = Style::default();
1486                scroll_st
1487                    .get_mut_layout()
1488                    .set_flex_direction(FlexDirection::Column)
1489                    .set_align_items(AlignItems::Start)
1490                    .set_width(Length::Percent(100.0))
1491                    .set_max_height(Length::Px(TABLE_INLINE_MAX_HEIGHT));
1492                let scroll_node: NodeId = tree.create_scroll_view(scroll_st);
1493                let grid_node: NodeId = Self::mount_table_grid_in_tree(
1494                    tree,
1495                    headers,
1496                    rows,
1497                    &col_widths,
1498                    (total_w, table_text_select),
1499                    tokens,
1500                );
1501                tree.append_child(scroll_node, grid_node);
1502                let mut portal_st: Style = Style::default();
1503                portal_st
1504                    .get_mut_layout()
1505                    .set_display(Display::None)
1506                    .set_flex_direction(FlexDirection::Column)
1507                    .set_position(Position::Fixed)
1508                    .set_top(Some(0.0))
1509                    .set_right(Some(0.0))
1510                    .set_bottom(Some(0.0))
1511                    .set_left(Some(0.0))
1512                    .set_width(Length::Percent(100.0))
1513                    .set_height(Length::Percent(100.0))
1514                    .set_padding(Edges::all(0.0))
1515                    .set_margin(Edges::all(0.0))
1516                    .set_justify_content(JustifyContent::Start)
1517                    .set_align_items(AlignItems::Stretch)
1518                    .set_overflow(Overflow::Hidden)
1519                    .set_z_index(Z_INDEX_FULLSCREEN);
1520                portal_st
1521                    .get_mut_paint()
1522                    .set_background(Some(p.get_card()))
1523                    .set_border(Border::default())
1524                    .set_radius(CornerRadius::all(0.0))
1525                    .set_pointer_events(PointerEvents::None)
1526                    .set_stop_scroll_propagation(true)
1527                    .set_stop_event_propagation(true);
1528                let fs_portal: NodeId = tree.create_portal(portal_st);
1529                let ctx_fs: Context = ctx.clone();
1530                let headers_fs: Rc<[String]> = Rc::clone(&headers_rc);
1531                let rows_fs: Rc<[Vec<String>]> = Rc::clone(&rows_rc);
1532                let widths_fs: Rc<[f32]> = Rc::clone(&col_widths_rc);
1533                let on_open_fs: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
1534                    bind_fullscreen_context(&ctx_fs);
1535                    if let Some(sig) = fs_open_slot.get() {
1536                        if sig.get_untracked() {
1537                            let _: bool = sig.set_if_changed(false);
1538                        }
1539                        let _: bool = sig.set_if_changed(true);
1540                        return;
1541                    }
1542                    let fs_open: Signal<bool> = Signal::new(true);
1543                    fs_open_slot.set(Some(fs_open));
1544                    let handle_ov: SceneHandle = ctx_fs.get_scene().clone();
1545                    let handle_vp: SceneHandle = ctx_fs.get_scene().clone();
1546                    let prev_open: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1547                    let fs_acquired: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1548                    let in_enter_guard: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1549                    let fs_cleanup: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
1550                    let ctx_build: Context = ctx_fs.clone();
1551                    let headers_build: Rc<[String]> = Rc::clone(&headers_fs);
1552                    let rows_build: Rc<[Vec<String>]> = Rc::clone(&rows_fs);
1553                    let widths_build: Rc<[f32]> = Rc::clone(&widths_fs);
1554                    let on_fs_key: UiEventHandler = Rc::new(RefCell::new(move |ev: &UiEvent| {
1555                        if matches!(
1556                            ev.get_kind(),
1557                            UiEventKind::KeyDown(KeyCode::Escape | KeyCode::Back, _)
1558                        ) && fs_open.get_untracked()
1559                        {
1560                            let _: bool = fs_open.set_if_changed(false);
1561                        }
1562                    }));
1563                    ctx_fs.get_scene().with_write(
1564                        |t: &mut SceneTree| {
1565                            if let Some(node) = t.get_node_mut(fs_portal) {
1566                                node.get_mut_handlers().set_on_key_down(Some(on_fs_key));
1567                            }
1568                        },
1569                        (),
1570                    );
1571                    let (ov_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1572                        on_cleanup(move || {
1573                            if fs_cleanup.replace(false) {
1574                                exit_fullscreen();
1575                            }
1576                        });
1577                        let _: Effect = EuvOverlayStack::bind_signal(
1578                            fs_open,
1579                            TABLE_FULLSCREEN_OVERLAY_NAME,
1580                            Z_INDEX_FULLSCREEN,
1581                        );
1582                        let vp_sig: Signal<Size> = ctx_build.get_viewport_size();
1583                        let _: Effect = Effect::new(move || {
1584                            let vp: Size = vp_sig.get();
1585                            if !fs_open.get() {
1586                                return;
1587                            }
1588                            let vw: f32 = vp.get_width().max(1.0);
1589                            let vh: f32 = vp.get_height().max(1.0);
1590                            handle_vp.with_write(
1591                                |t: &mut SceneTree| {
1592                                    if let Some(n) = t.get_node_mut(fs_portal) {
1593                                        n.get_mut_style()
1594                                            .get_mut_layout()
1595                                            .set_width(Length::Px(vw))
1596                                            .set_height(Length::Px(vh));
1597                                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1598                                        t.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
1599                                        notify_frame_needed();
1600                                    }
1601                                },
1602                                (),
1603                            );
1604                        });
1605                        let global_fs_sig: Signal<bool> = use_fullscreen_active();
1606                        let ctx_fs_sig: Signal<bool> = ctx_build.immersive_fullscreen_signal();
1607                        let saw_global_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1608                        let saw_ctx_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1609                        let saw_global_reset: Rc<Cell<bool>> = Rc::clone(&saw_global_fs);
1610                        let saw_ctx_reset: Rc<Cell<bool>> = Rc::clone(&saw_ctx_fs);
1611                        let fs_acquired_sync: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
1612                        let enter_guard_sync: Rc<Cell<bool>> = Rc::clone(&in_enter_guard);
1613                        let _: Effect = Effect::new(move || {
1614                            let g_active: bool = global_fs_sig.get();
1615                            let c_active: bool = ctx_fs_sig.get();
1616                            if enter_guard_sync.get() {
1617                                if g_active {
1618                                    saw_global_fs.set(true);
1619                                }
1620                                if c_active {
1621                                    saw_ctx_fs.set(true);
1622                                }
1623                                return;
1624                            }
1625                            if !fs_acquired_sync.get() {
1626                                saw_global_fs.set(false);
1627                                saw_ctx_fs.set(false);
1628                                return;
1629                            }
1630                            if g_active {
1631                                saw_global_fs.set(true);
1632                            }
1633                            if c_active {
1634                                saw_ctx_fs.set(true);
1635                            }
1636                            let external_exit: bool = (saw_global_fs.get() && !g_active)
1637                                || (saw_ctx_fs.get() && !c_active);
1638                            if external_exit {
1639                                let _: bool = fs_open.set_if_changed(false);
1640                            }
1641                        });
1642                        Effect::new(move || {
1643                            let is_open: bool = fs_open.get();
1644                            if is_open == prev_open.replace(is_open) {
1645                                return;
1646                            }
1647                            if is_open {
1648                                in_enter_guard.set(true);
1649                                saw_global_reset.set(false);
1650                                saw_ctx_reset.set(false);
1651                                let live_bg: Color =
1652                                    live_tokens_untracked(base_tokens).get_palette().get_card();
1653                                let vp_now: Size = vp_sig.get_untracked();
1654                                let vw: f32 = vp_now.get_width().max(1.0);
1655                                let vh: f32 = vp_now.get_height().max(1.0);
1656                                let modal_card: NodeId = with_context(ctx_build.clone(), || {
1657                                    Self::mount_fullscreen_modal_card(
1658                                        &ctx_build,
1659                                        base_tokens,
1660                                        &headers_build,
1661                                        &rows_build,
1662                                        &widths_build,
1663                                        (total_w, table_text_select, fs_open),
1664                                    )
1665                                });
1666                                let portal_shown: bool = modal_card != NodeId::default()
1667                                    && handle_ov.with_write(
1668                                        |t: &mut SceneTree| {
1669                                            if t.get_node(fs_portal).is_none()
1670                                                || t.get_node(modal_card).is_none()
1671                                            {
1672                                                return false;
1673                                            }
1674                                            t.cancel_subtree_transitions(fs_portal);
1675                                            t.replace_children(fs_portal, vec![modal_card]);
1676                                            if let Some(n) = t.get_node_mut(fs_portal) {
1677                                                let st: &mut Style = n.get_mut_style();
1678                                                st.get_mut_layout()
1679                                                    .set_display(Display::Flex)
1680                                                    .set_width(Length::Px(vw))
1681                                                    .set_height(Length::Px(vh));
1682                                                st.get_mut_paint()
1683                                                    .set_background(Some(live_bg))
1684                                                    .set_pointer_events(PointerEvents::Auto)
1685                                                    .set_opacity(1.0)
1686                                                    .set_transform(Transform2D::default());
1687                                            }
1688                                            let _: Vec<(UiEventHandler, UiEvent)> =
1689                                                t.update_focus(Some(fs_portal));
1690                                            let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1691                                            t.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
1692                                            notify_frame_needed();
1693                                            true
1694                                        },
1695                                        false,
1696                                    );
1697                                let entered: bool = portal_shown
1698                                    && (fs_acquired.get()
1699                                        || enter_fullscreen_for_portal(&ctx_build, fs_portal));
1700                                if entered {
1701                                    fs_acquired.set(true);
1702                                } else {
1703                                    handle_ov.dismiss_portal_immediate(fs_portal);
1704                                    if fs_acquired.replace(false) {
1705                                        exit_fullscreen();
1706                                    }
1707                                    prev_open.set(false);
1708                                    let _: bool = fs_open.set_if_changed(false);
1709                                }
1710                                in_enter_guard.set(false);
1711                                notify_frame_needed();
1712                            } else {
1713                                in_enter_guard.set(false);
1714                                if fs_acquired.replace(false) {
1715                                    exit_fullscreen();
1716                                }
1717                                handle_ov.dismiss_portal_immediate(fs_portal);
1718                            }
1719                        })
1720                    });
1721                    ctx_fs.get_scene().with_write(
1722                        |t: &mut SceneTree| {
1723                            t.attach_scope(root, ov_scope);
1724                        },
1725                        (),
1726                    );
1727                }));
1728                if let Some(node) = tree.get_node_mut(fs_btn) {
1729                    node.get_mut_handlers().set_on_click(Some(on_open_fs));
1730                    node.get_mut_interaction().set_focusable(true);
1731                    *node.get_mut_a11y() = Some(A11yProps::new(
1732                        A11yRole::Button,
1733                        TABLE_BTN_FULLSCREEN.to_string(),
1734                    ));
1735                }
1736                tree.append_children(root, &[toolbar_row, div_node, scroll_node, fs_portal]);
1737                root
1738            },
1739            NodeId::default(),
1740        )
1741    }
1742}