Skip to main content

euv_ui/component/markdown/
impl.rs

1use super::*;
2
3/// Zero-allocation language resolver for `CodeLang`.
4impl CodeLang {
5    /// Resolves a raw language hint string into its `CodeLang` variant without heap allocation.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Raw language hint (e.g. `"rust"`, `"JSON"`, `"diff"`).
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Pre-resolved `CodeLang` variant.
14    #[inline(always)]
15    #[must_use]
16    pub fn from_name(language: &str) -> Self {
17        let trimmed: &str = language.trim();
18        if trimmed.eq_ignore_ascii_case(CODE_LANG_RUST) {
19            Self::Rust
20        } else if trimmed.eq_ignore_ascii_case(CODE_LANG_DIFF) {
21            Self::Diff
22        } else if trimmed.eq_ignore_ascii_case(CODE_LANG_JSON) {
23            Self::Json
24        } else if trimmed.eq_ignore_ascii_case(CODE_LANG_TOML) {
25            Self::Toml
26        } else if trimmed.eq_ignore_ascii_case(CODE_LANG_YAML) {
27            Self::Yaml
28        } else {
29            Self::Generic
30        }
31    }
32}
33
34/// Exact VS Code `Eva Light Bold` / `Eva Dark Bold` palette resolution for `CodeThemePalette`.
35impl CodeThemePalette {
36    /// Resolves the exact VS Code `Eva Light Bold` or `Eva Dark Bold` palette for `mode`.
37    ///
38    /// # Arguments
39    ///
40    /// - `ThemeMode` - Active light or dark theme mode.
41    ///
42    /// # Returns
43    ///
44    /// - `Self` - Exact Eva theme color palette.
45    #[inline(always)]
46    #[must_use]
47    pub fn resolve(mode: ThemeMode) -> Self {
48        match mode {
49            ThemeMode::Light => Self {
50                theme_name: CODE_THEME_LABEL_LIGHT,
51                background: Color::hex(EVA_LIGHT_BG),
52                header_bg: Color::hex(EVA_LIGHT_HEADER_BG),
53                border: Color::hex(EVA_LIGHT_BORDER),
54                foreground: Color::hex(EVA_LIGHT_FG),
55                line_number: Color::hex(EVA_LIGHT_LINE_NUM),
56                line_highlight: Color::hex(EVA_LIGHT_LINE_HL),
57                comment: Color::hex(EVA_LIGHT_COMMENT),
58                keyword: Color::hex(EVA_LIGHT_KEYWORD),
59                control: Color::hex(EVA_LIGHT_CONTROL),
60                operator: Color::hex(EVA_LIGHT_OPERATOR),
61                string: Color::hex(EVA_LIGHT_STRING),
62                number: Color::hex(EVA_LIGHT_NUMBER),
63                constant: Color::hex(EVA_LIGHT_CONSTANT),
64                function: Color::hex(EVA_LIGHT_FUNCTION),
65                ty: Color::hex(EVA_LIGHT_TYPE),
66                primitive: Color::hex(EVA_LIGHT_PRIMITIVE),
67                property: Color::hex(EVA_LIGHT_PROPERTY),
68                punctuation: Color::hex(EVA_LIGHT_PUNCT),
69                inline_code_bg: Color::hex(EVA_LIGHT_INLINE_CODE_BG),
70                inline_code_fg: Color::hex(EVA_LIGHT_INLINE_CODE_FG),
71                quote_bg: Color::hex(EVA_LIGHT_QUOTE_BG),
72                quote_border: Color::hex(EVA_LIGHT_QUOTE_BORDER),
73                link: Color::hex(EVA_LIGHT_LINK),
74                diff_add: Color::hex(EVA_LIGHT_DIFF_ADD),
75                diff_del: Color::hex(EVA_LIGHT_DIFF_DEL),
76            },
77            ThemeMode::Dark => Self {
78                theme_name: CODE_THEME_LABEL_DARK,
79                background: Color::hex(EVA_DARK_BG),
80                header_bg: Color::hex(EVA_DARK_HEADER_BG),
81                border: Color::hex(EVA_DARK_BORDER),
82                foreground: Color::hex(EVA_DARK_FG),
83                line_number: Color::hex(EVA_DARK_LINE_NUM),
84                line_highlight: Color::hex(EVA_DARK_LINE_HL),
85                comment: Color::hex(EVA_DARK_COMMENT),
86                keyword: Color::hex(EVA_DARK_KEYWORD),
87                control: Color::hex(EVA_DARK_CONTROL),
88                operator: Color::hex(EVA_DARK_OPERATOR),
89                string: Color::hex(EVA_DARK_STRING),
90                number: Color::hex(EVA_DARK_NUMBER),
91                constant: Color::hex(EVA_DARK_CONSTANT),
92                function: Color::hex(EVA_DARK_FUNCTION),
93                ty: Color::hex(EVA_DARK_TYPE),
94                primitive: Color::hex(EVA_DARK_PRIMITIVE),
95                property: Color::hex(EVA_DARK_PROPERTY),
96                punctuation: Color::hex(EVA_DARK_PUNCT),
97                inline_code_bg: Color::hex(EVA_DARK_INLINE_CODE_BG),
98                inline_code_fg: Color::hex(EVA_DARK_INLINE_CODE_FG),
99                quote_bg: Color::hex(EVA_DARK_QUOTE_BG),
100                quote_border: Color::hex(EVA_DARK_QUOTE_BORDER),
101                link: Color::hex(EVA_DARK_LINK),
102                diff_add: Color::hex(EVA_DARK_DIFF_ADD),
103                diff_del: Color::hex(EVA_DARK_DIFF_DEL),
104            },
105        }
106    }
107
108    /// Returns `(Color, FontWeight)` matching the exact VS Code `Eva Light Bold` / `Eva Dark Bold` TextMate rule for `kind`.
109    ///
110    /// # Arguments
111    ///
112    /// - `&Self` - Resolved Eva palette reference.
113    /// - `CodeTokenKind` - Token classification.
114    ///
115    /// # Returns
116    ///
117    /// - `(Color, FontWeight)` - Exact token color and font weight.
118    #[inline(always)]
119    #[must_use]
120    pub fn token_style(&self, kind: CodeTokenKind) -> (Color, FontWeight) {
121        match kind {
122            CodeTokenKind::Plain => (self.get_foreground(), FontWeight::Normal),
123            CodeTokenKind::Keyword => (self.get_keyword(), FontWeight::Bold),
124            CodeTokenKind::Control | CodeTokenKind::Constant => {
125                (self.get_control(), FontWeight::Bold)
126            }
127            CodeTokenKind::Operator => (self.get_operator(), FontWeight::Normal),
128            CodeTokenKind::Type => (self.get_ty(), FontWeight::Normal),
129            CodeTokenKind::PrimitiveType => (self.get_primitive(), FontWeight::Normal),
130            CodeTokenKind::Function | CodeTokenKind::Macro => {
131                (self.get_function(), FontWeight::Bold)
132            }
133            CodeTokenKind::String => (self.get_string(), FontWeight::Normal),
134            CodeTokenKind::Number => (self.get_number(), FontWeight::Normal),
135            CodeTokenKind::Comment => (self.get_comment(), FontWeight::Normal),
136            CodeTokenKind::Property => (self.get_property(), FontWeight::Normal),
137            CodeTokenKind::Punctuation => (self.get_punctuation(), FontWeight::Normal),
138            CodeTokenKind::DiffAdd => (self.get_diff_add(), FontWeight::Normal),
139            CodeTokenKind::DiffDel => (self.get_diff_del(), FontWeight::Normal),
140        }
141    }
142}
143
144/// Optional checkbox state accessor for `EuvMarkdownListItem`.
145impl EuvMarkdownListItem {
146    /// Returns the optional GFM checkbox state.
147    ///
148    /// # Arguments
149    ///
150    /// - `&Self` - List item reference.
151    ///
152    /// # Returns
153    ///
154    /// - `Option<bool>` - `Some(checked)` for checklist items, `None` otherwise.
155    #[must_use]
156    pub fn checked_state(&self) -> Option<bool> {
157        let Self { checked, .. } = *self;
158        checked
159    }
160}
161
162/// Fluent builder helpers for `EuvCodeBlock`.
163impl EuvCodeBlock {
164    /// Sets the syntax-highlighting language tag (e.g. `"rust"`, `"typescript"`, `"json"`, `"diff"`).
165    ///
166    /// # Arguments
167    ///
168    /// - `Self` - Source code block.
169    /// - `TextValue` - Language hint convertible into `String`.
170    ///
171    /// # Returns
172    ///
173    /// - `Self` - Updated code block.
174    #[must_use]
175    pub fn language<TextValue>(mut self, lang: TextValue) -> Self
176    where
177        TextValue: Into<String>,
178    {
179        self.set_language(lang.into());
180        self
181    }
182
183    /// Sets an optional filename displayed in the code block header bar.
184    ///
185    /// # Arguments
186    ///
187    /// - `Self` - Source code block.
188    /// - `TextValue` - Display filename convertible into `String`.
189    ///
190    /// # Returns
191    ///
192    /// - `Self` - Updated code block.
193    #[must_use]
194    pub fn filename<TextValue>(mut self, name: TextValue) -> Self
195    where
196        TextValue: Into<String>,
197    {
198        self.set_filename(Some(name.into()));
199        self
200    }
201
202    /// Enables or disables the left line-number gutter.
203    ///
204    /// # Arguments
205    ///
206    /// - `Self` - Source code block.
207    /// - `bool` - Whether line numbers are visible.
208    ///
209    /// # Returns
210    ///
211    /// - `Self` - Updated code block.
212    #[must_use]
213    pub fn line_numbers(mut self, show: bool) -> Self {
214        self.set_show_line_numbers(show);
215        self
216    }
217
218    /// Marks specific 1-based line numbers with VS Code Eva active-line highlight tint.
219    ///
220    /// # Arguments
221    ///
222    /// - `Self` - Source code block.
223    /// - `Vec<usize>` - 1-based line indices to highlight.
224    ///
225    /// # Returns
226    ///
227    /// - `Self` - Updated code block.
228    #[must_use]
229    pub fn highlight_lines(mut self, lines: Vec<usize>) -> Self {
230        self.set_highlight_lines(lines);
231        self
232    }
233
234    /// Sets the maximum inline viewport height before vertical scrolling activates in `Fixed` and `AutoExpandWidth` modes.
235    ///
236    /// # Arguments
237    ///
238    /// - `Self` - Source code block.
239    /// - `f32` - Maximum viewport height in logical pixels.
240    ///
241    /// # Returns
242    ///
243    /// - `Self` - Updated code block.
244    #[must_use]
245    pub fn max_height(mut self, height: f32) -> Self {
246        self.set_max_height(height);
247        self
248    }
249
250    /// Sets the inline width and height sizing mode (`EuvCodeBlockSizeMode::AutoExpand` by default).
251    ///
252    /// # Arguments
253    ///
254    /// - `Self` - Source code block.
255    /// - `EuvCodeBlockSizeMode` - Sizing mode controlling automatic width/height expansion vs constrained scrolling.
256    ///
257    /// # Returns
258    ///
259    /// - `Self` - Updated code block.
260    #[must_use]
261    pub fn size_mode(mut self, mode: EuvCodeBlockSizeMode) -> Self {
262        self.set_size_mode(mode);
263        self
264    }
265
266    /// Sets the interactive text selection and copy mode for code lines (`TextSelectMode::SelectAndCopy` by default).
267    ///
268    /// # Arguments
269    ///
270    /// - `Self` - Source code block.
271    /// - `TextSelectMode` - Selection mode applied to code lines (header and line numbers remain non-selectable).
272    ///
273    /// # Returns
274    ///
275    /// - `Self` - Updated code block.
276    #[must_use]
277    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
278        self.set_text_select(Some(mode));
279        self
280    }
281
282    /// Controls whether the code lines inside the block are selectable.
283    ///
284    /// # Arguments
285    ///
286    /// - `Self` - Source code block.
287    /// - `bool` - `true` to enable native text selection, `false` to disable.
288    ///
289    /// # Returns
290    ///
291    /// - `Self` - Updated code block.
292    #[must_use]
293    pub fn selectable(self, enabled: bool) -> Self {
294        let mode: TextSelectMode = if enabled {
295            TextSelectMode::SelectAndCopy
296        } else {
297            TextSelectMode::None
298        };
299        self.text_select(mode)
300    }
301
302    /// Registers a callback invoked when the user clicks the Copy button.
303    ///
304    /// # Arguments
305    ///
306    /// - `Self` - Source code block.
307    /// - `CallbackFn` - Copy handler receiving the raw code string.
308    ///
309    /// # Returns
310    ///
311    /// - `Self` - Updated code block.
312    #[must_use]
313    pub fn on_copy<CallbackFn>(mut self, handler: CallbackFn) -> Self
314    where
315        CallbackFn: Fn(&str) + 'static,
316    {
317        self.set_on_copy(Some(Rc::new(handler)));
318        self
319    }
320    /// Mounts the fullscreen modal card for `EuvCodeBlock` when the user opens the fullscreen overlay.
321    ///
322    /// # Arguments
323    ///
324    /// - `&Context` - Active build context.
325    /// - `ThemeTokens` - Base theme tokens.
326    /// - `&Rc<str>` - Shared raw code string.
327    /// - `&Rc<str>` - Uppercase language badge label.
328    /// - `Option<&str>` - Optional display filename.
329    /// - `(CodeLang, bool, usize, Signal<bool>, NodeId, TextSelectMode)` - Modal metadata `(code_lang, show_nums, line_count, fs_open, inline_copy_txt, select_mode)`.
330    /// - `(&[usize], &Rc<Cell<bool>>, Option<&MarkdownStrCallback>)` - Highlight lines, shared copied flag, and optional copy callback.
331    ///
332    /// # Returns
333    ///
334    /// - `NodeId` - Mounted modal card node handle.
335    fn mount_fullscreen_modal_card(
336        ctx: &Context,
337        tokens: ThemeTokens,
338        modal_code_rc: &Rc<str>,
339        modal_lang: &Rc<str>,
340        modal_filename: Option<&str>,
341        meta: (CodeLang, bool, usize, Signal<bool>, NodeId, TextSelectMode),
342        extra: (&[usize], &Rc<Cell<bool>>, Option<&MarkdownStrCallback>),
343    ) -> NodeId {
344        let (code_lang, show_nums, line_count, fs_open, inline_copy_txt, select_mode): (
345            CodeLang,
346            bool,
347            usize,
348            Signal<bool>,
349            NodeId,
350            TextSelectMode,
351        ) = meta;
352        let (modal_hl, copied_cell, modal_on_copy): (
353            &[usize],
354            &Rc<Cell<bool>>,
355            Option<&MarkdownStrCallback>,
356        ) = extra;
357        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
358        let live_p: ThemePalette = live_tok.get_palette();
359        let live_g: ThemeGeometry = live_tok.get_geometry();
360        let live_eva: CodeThemePalette = CodeThemePalette::resolve(live_tok.get_mode());
361        let (modal_body_row, modal_code_col): (NodeId, NodeId) = mount_code_split_body(
362            modal_code_rc,
363            code_lang,
364            live_eva,
365            modal_hl,
366            (show_nums, CODE_MODAL_FONT_SIZE, select_mode),
367        );
368        let m_copy_str: Rc<str> = Rc::clone(modal_code_rc);
369        let m_copy_cb: Option<MarkdownStrCallback> = modal_on_copy.cloned();
370        let m_ctx: Context = ctx.clone();
371        let m_copied: Rc<Cell<bool>> = Rc::clone(copied_cell);
372        let m_copied_paint: Rc<Cell<bool>> = Rc::clone(copied_cell);
373        let init_copy_label: &'static str = if copied_cell.get() {
374            CODE_BUTTON_COPIED
375        } else {
376            CODE_BUTTON_COPY
377        };
378        let modal_copy_btn_cell: Rc<Cell<NodeId>> = Rc::new(Cell::new(NodeId::default()));
379        let modal_copy_btn_cb: Rc<Cell<NodeId>> = Rc::clone(&modal_copy_btn_cell);
380        let modal_copy_icon_cell: Rc<Cell<NodeId>> = Rc::new(Cell::new(NodeId::default()));
381        let modal_copy_icon_cb: Rc<Cell<NodeId>> = Rc::clone(&modal_copy_icon_cell);
382        let modal_code_col_cell: Rc<Cell<NodeId>> = Rc::new(Cell::new(NodeId::default()));
383        let modal_code_col_cb: Rc<Cell<NodeId>> = Rc::clone(&modal_code_col_cell);
384        let on_modal_copy = move |_: &UiEvent| {
385            let selected_opt: Option<String> = m_ctx
386                .get_scene()
387                .get_selected_text_within(modal_code_col_cb.get());
388            let payload: String = selected_opt.unwrap_or_else(|| m_copy_str.to_string());
389            let _: bool = m_ctx.copy_to_clipboard(payload.as_str());
390            m_copied.set(true);
391            let m_btn: NodeId = modal_copy_btn_cb.get();
392            let m_icon: NodeId = modal_copy_icon_cb.get();
393            m_ctx.get_scene().with_write(
394                |tree: &mut SceneTree| {
395                    if let Some(item_count) = tree.get_node_mut(m_btn) {
396                        *item_count.get_mut_a11y() = Some(A11yProps::new(
397                            A11yRole::Button,
398                            CODE_BUTTON_COPIED.to_string(),
399                        ));
400                    }
401                    tree.mark_dirty(inline_copy_txt, DIRTY_PAINT);
402                    tree.mark_dirty(m_icon, DIRTY_PAINT);
403                },
404                (),
405            );
406            if let Some(callback_fn) = m_copy_cb.as_ref() {
407                callback_fn(payload.as_str());
408            }
409        };
410        let paint_modal_copy_icon = move |bounds: Rect, display_list: &mut DisplayList| {
411            let cur_tok: ThemeTokens = live_tokens_untracked(tokens);
412            let cur_eva: CodeThemePalette = CodeThemePalette::resolve(cur_tok.get_mode());
413            if m_copied_paint.get() {
414                draw_euv_icon(
415                    EuvIconName::Check,
416                    bounds,
417                    display_list,
418                    cur_tok.get_palette().get_success(),
419                );
420            } else {
421                draw_euv_icon(
422                    EuvIconName::Copy,
423                    bounds,
424                    display_list,
425                    cur_eva.get_function(),
426                );
427            }
428        };
429        let paint_close_icon = move |bounds: Rect, draw_commands: &mut DisplayList| {
430            let cur_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
431            let close_fg: Color = cur_p.surface(SurfaceRole::Secondary).get_fg();
432            draw_euv_icon(EuvIconName::Minimize, bounds, draw_commands, close_fg);
433        };
434        let on_close_btn = move |_: &UiEvent| {
435            let _: bool = fs_open.set_if_changed(false);
436        };
437        let close_surface: SurfaceColors = live_p.surface(SurfaceRole::Secondary);
438        let modal_ctrl_h: f32 = live_g.get_control_sm();
439        let m_title: &str = modal_filename.unwrap_or(live_eva.get_theme_name());
440        let m_lang: &str = modal_lang;
441        let lines_badge: String = format!("{line_count} L");
442        let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
443        let vp_sig: Signal<Size> = ctx.get_viewport_size();
444        let init_fs: FullscreenSafeLayout =
445            resolve_fullscreen_safe_layout(vp_sig.get_untracked(), safe_sig.get_untracked());
446        let mut modal_scroll_st: Style = Style::default();
447        modal_scroll_st
448            .get_mut_layout()
449            .set_flex_direction(FlexDirection::Column)
450            .set_align_items(AlignItems::Start);
451        let mut top_bar_node: NodeId = NodeId::default();
452        let mut body_scroll_node: NodeId = NodeId::default();
453        let mut modal_copy_btn: NodeId = NodeId::default();
454        let mut modal_copy_icon: NodeId = NodeId::default();
455        let column_sixth_style: Style = style! {
456            Width(Length::Percent(100.0))
457            Height(Length::Percent(100.0))
458            FlexGrow(1.0)
459            Padding(Edges::all(0.0))
460            Margin(Edges::all(0.0))
461            Background(live_eva.get_background())
462            Border::new(0.0, COLOR_TRANSPARENT)
463            Radius(0.0)
464            Overflow::Hidden
465            TextSelectMode::None
466            StopEventPropagation(true)
467        };
468        let row_eighth_style: Style = style! {
469            Width(Length::Percent(100.0))
470            FlexShrink(0.0)
471            Padding(init_fs.get_header_padding())
472            JustifyContent::SpaceBetween
473            AlignItems::Center
474            Gap(SPACE_SM)
475            Background(live_eva.get_header_bg())
476            Overflow::Hidden
477            TextSelectMode::None
478        };
479        let row_ninth_style: Style = style! {
480            FlexGrow(1.0)
481            FlexShrink(1.0)
482            MinWidth(Length::Px(0.0))
483            AlignItems::Center
484            Gap(SPACE_SM)
485            Overflow::Hidden
486        };
487        let row_tenth_style: Style = style! {
488            FlexShrink(0.0)
489            Gap(5.0)
490            AlignItems::Center
491        };
492        let view_quaternary_style: Style = style! {
493            Width(Length::Px(9.0))
494            Height(Length::Px(9.0))
495            Radius(RADIUS_PILL)
496            Background(Color::hex(CODE_DOT_RED))
497        };
498        let view_fifth_style: Style = style! {
499            Width(Length::Px(9.0))
500            Height(Length::Px(9.0))
501            Radius(RADIUS_PILL)
502            Background(Color::hex(CODE_DOT_YELLOW))
503        };
504        let view_sixth_style: Style = style! {
505            Width(Length::Px(9.0))
506            Height(Length::Px(9.0))
507            Radius(RADIUS_PILL)
508            Background(Color::hex(CODE_DOT_GREEN))
509        };
510        let text_fifth_style: Style = style! {
511            FlexGrow(1.0)
512            FlexShrink(1.0)
513            MinWidth(Length::Px(0.0))
514            Overflow::Hidden
515            TextOverflow::Ellipsis
516            FontSize(13.0)
517            FontWeight::SemiBold
518            TextColor(live_eva.get_foreground())
519        };
520        let row_eleventh_style: Style = style! {
521            FlexShrink(0.0)
522            AlignItems::Center
523            Gap(SPACE_XS)
524        };
525        let row_twelfth_style: Style = style! {
526            Height(Length::Px(modal_ctrl_h))
527            Padding(Edges::symmetric(0.0, SPACE_SM))
528            JustifyContent::Center
529            AlignItems::Center
530            Radius(live_g.get_radius_sm())
531            Overflow::Hidden
532            Background(live_eva.get_background())
533            Border::new(1.0, live_eva.get_border())
534        };
535        let text_sixth_style: Style = style! {
536            FontSize(10.5)
537            FontWeight::Bold
538            TextColor(live_eva.get_keyword())
539            TextOverflow::Clip
540        };
541        let text_seventh_style: Style = style! {
542            FontSize(10.5)
543            FontFamily::Monospace
544            TextColor(live_eva.get_line_number())
545            TextOverflow::Clip
546        };
547        let row_thirteenth_style: Style = style! {
548            Width(Length::Px(modal_ctrl_h))
549            Height(Length::Px(modal_ctrl_h))
550            JustifyContent::Center
551            AlignItems::Center
552            Radius(live_g.get_radius_sm())
553            Overflow::Hidden
554            CursorIcon::Pointer
555            Background(live_eva.get_background())
556            Border::new(1.0, live_eva.get_border())
557        };
558        let canvas_secondary_style: Style = style! {
559            Width(Length::Px(14.0))
560            Height(Length::Px(14.0))
561        };
562        let row_fourteenth_style: Style = style! {
563            Width(Length::Px(modal_ctrl_h))
564            Height(Length::Px(modal_ctrl_h))
565            JustifyContent::Center
566            AlignItems::Center
567            Radius(live_g.get_radius_sm())
568            Overflow::Hidden
569            CursorIcon::Pointer
570            Background(close_surface.get_bg())
571            Border::new(1.0, close_surface.get_border())
572        };
573        let view_seventh_style: Style = style! {
574            Width(Length::Percent(100.0))
575            Height(Length::Px(1.0))
576            Background(live_eva.get_border())
577        };
578        let scroll_secondary_style: Style = style! {
579            modal_scroll_st
580            FlexGrow(1.0)
581            FlexShrink(1.0)
582            MinHeight(Length::Px(0.0))
583            Width(Length::Percent(100.0))
584            Padding(Edges::new(
585                0.0,
586                init_fs.get_body_padding().get_right(),
587                SPACE_MD + init_fs.get_body_padding().get_bottom(),
588                init_fs.get_body_padding().get_left()
589            ))
590            StopScrollPropagation(true)
591        };
592        let card: NodeId = view! {
593            column {
594                style: column_sixth_style
595                row {
596                    node_ref: top_bar_node
597                    style: row_eighth_style
598                    row {
599                        style: row_ninth_style
600                        row {
601                            style: row_tenth_style
602                            view {
603                                style: view_quaternary_style
604                            }
605                            view {
606                                style: view_fifth_style
607                            }
608                            view {
609                                style: view_sixth_style
610                            }
611                        }
612                        text {
613                            style: text_fifth_style
614                            { m_title }
615                        }
616                    }
617                    row {
618                        style: row_eleventh_style
619                        row {
620                            style: row_twelfth_style
621                            text {
622                                style: text_sixth_style
623                                { m_lang }
624                            }
625                        }
626                        row {
627                            style: row_twelfth_style
628                            text {
629                                style: text_seventh_style
630                                { lines_badge }
631                            }
632                        }
633                        row {
634                            node_ref: modal_copy_btn
635                            style: row_thirteenth_style
636                            role: A11yRole::Button
637                            a11y_label: init_copy_label.to_string()
638                            on_click: on_modal_copy
639                            canvas {
640                                node_ref: modal_copy_icon
641                                style: canvas_secondary_style
642                                painter: paint_modal_copy_icon
643                            }
644                        }
645                        row {
646                            style: row_fourteenth_style
647                            role: A11yRole::Button
648                            a11y_label: CODE_BUTTON_CLOSE.to_string()
649                            on_click: on_close_btn
650                            canvas {
651                                style: canvas_secondary_style
652                                painter: paint_close_icon
653                            }
654                        }
655                    }
656                }
657                view {
658                    style: view_seventh_style
659                }
660                scroll {
661                    node_ref: body_scroll_node
662                    style: scroll_secondary_style
663                    { modal_body_row }
664                }
665            }
666        };
667        let handle_safe: SceneHandle = ctx.get_scene().clone();
668        let (safe_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
669            Effect::new(move || {
670                let fs_lay: FullscreenSafeLayout =
671                    resolve_fullscreen_safe_layout(vp_sig.get(), safe_sig.get());
672                handle_safe.with_write(
673                    |tree: &mut SceneTree| {
674                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
675                        if let Some(node_entry) = tree.get_node_mut(top_bar_node) {
676                            node_entry
677                                .get_mut_style()
678                                .get_mut_layout()
679                                .set_padding(fs_lay.get_header_padding());
680                            tree.mark_dirty(top_bar_node, dirty_l | DIRTY_PAINT);
681                        }
682                        if let Some(normal_vec) = tree.get_node_mut(body_scroll_node) {
683                            let fs_body: Edges = fs_lay.get_body_padding();
684                            normal_vec
685                                .get_mut_style()
686                                .get_mut_layout()
687                                .set_padding(Edges::new(
688                                    0.0,
689                                    fs_body.get_right(),
690                                    SPACE_MD + fs_body.get_bottom(),
691                                    fs_body.get_left(),
692                                ));
693                            tree.mark_dirty(body_scroll_node, dirty_l | DIRTY_PAINT);
694                        }
695                    },
696                    (),
697                );
698            })
699        });
700        ctx.get_scene().with_write(
701            |tree: &mut SceneTree| {
702                tree.attach_scope(card, safe_scope);
703            },
704            (),
705        );
706        modal_copy_btn_cell.set(modal_copy_btn);
707        modal_copy_icon_cell.set(modal_copy_icon);
708        modal_code_col_cell.set(modal_code_col);
709        card
710    }
711
712    /// Mounts the complete `EuvCodeBlock` subtree directly into an already-borrowed `SceneTree` with zero eager signals or effects.
713    ///
714    /// # Arguments
715    ///
716    /// - `&Self` - Code block reference.
717    /// - `&mut SceneTree` - Mutable scene tree.
718    /// - `&Context` - Active build context captured by interactive click handlers.
719    ///
720    /// # Returns
721    ///
722    /// - `NodeId` - Mounted code block container handle.
723    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree, ctx: &Context) -> NodeId {
724        let base_tokens: ThemeTokens = self.get_tokens();
725        let tokens: ThemeTokens = live_tokens_untracked(base_tokens);
726        let geometry: ThemeGeometry = tokens.get_geometry();
727        let ctrl_sm: f32 = geometry.get_control_sm();
728        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
729        let Self {
730            code,
731            language,
732            filename,
733            show_line_numbers,
734            highlight_lines,
735            max_height,
736            size_mode,
737            text_select,
738            on_copy,
739            ..
740        } = self;
741        let select_mode: TextSelectMode = text_select.unwrap_or(TextSelectMode::SelectAndCopy);
742        let active_size_mode: EuvCodeBlockSizeMode = *size_mode;
743        let constrain_height: bool = matches!(
744            active_size_mode,
745            EuvCodeBlockSizeMode::AutoExpandWidth | EuvCodeBlockSizeMode::Fixed
746        );
747        let expand_width_unbounded: bool =
748            matches!(active_size_mode, EuvCodeBlockSizeMode::AutoExpandWidth);
749        let inline_max_h: f32 = if *max_height > 0.0 {
750            *max_height
751        } else {
752            CODE_DEFAULT_MAX_HEIGHT
753        };
754        let raw_lang: &str = language.trim();
755        let resolved_lang: &str = if raw_lang.is_empty() {
756            infer_code_language(code)
757        } else {
758            raw_lang
759        };
760        let display_lang_rc: Rc<str> = Rc::from(resolved_lang.to_ascii_uppercase());
761        let code_lang: CodeLang = CodeLang::from_name(resolved_lang);
762        let header_title_str: &str = filename.as_deref().unwrap_or(eva.get_theme_name());
763        let filename_rc: Option<Rc<str>> = filename.as_deref().map(Rc::from);
764        let code_rc: Rc<str> = Rc::from(code.as_str());
765        let show_nums: bool = *show_line_numbers || code.lines().nth(1).is_some();
766        let (natural_w, gutter_w, line_count, gutter_nodes, code_nodes): (
767            f32,
768            f32,
769            usize,
770            Vec<NodeId>,
771            Vec<NodeId>,
772        ) = build_code_split_nodes_in_tree(
773            tree,
774            code,
775            code_lang,
776            eva,
777            highlight_lines,
778            (show_nums, CODE_FONT_SIZE, select_mode),
779        );
780        let copied_cell: Rc<Cell<bool>> = Rc::new(Cell::new(false));
781        let fs_open_slot: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
782        let border_w: f32 = geometry.get_border_width().max(0.0);
783        let outer_radius_px: f32 = geometry.get_radius_md().max(0.0);
784        let inner_radius_px: f32 = concentric_radius(outer_radius_px, border_w);
785        let radius_md: CornerRadius = CornerRadius::all(outer_radius_px);
786        let radius_sm: CornerRadius = CornerRadius::all(geometry.get_radius_sm().max(0.0));
787        let eva_bg: Color = eva.get_background();
788        let eva_border: Border = Border::new(border_w, eva.get_border());
789        let expanded_w: f32 = (natural_w + border_w * 2.0).max(240.0);
790        let mut root_st: Style = style! {
791            TextSelectMode::None
792        };
793        if expand_width_unbounded {
794            root_st
795                .get_mut_layout()
796                .set_flex_direction(FlexDirection::Column)
797                .set_width(Length::Px(expanded_w))
798                .set_min_width(Length::Px(expanded_w))
799                .set_flex_shrink(0.0)
800                .set_overflow(Overflow::Hidden);
801        } else {
802            root_st
803                .get_mut_layout()
804                .set_flex_direction(FlexDirection::Column)
805                .set_width(Length::Percent(100.0))
806                .set_max_width(Length::Percent(100.0))
807                .set_min_width(Length::Px(0.0))
808                .set_overflow(Overflow::Hidden);
809        }
810        root_st
811            .get_mut_paint()
812            .set_background(Some(eva_bg))
813            .set_border(eva_border)
814            .set_radius(radius_md);
815        let root: NodeId = tree.create_view(root_st);
816        let mut header_st: Style = style! {
817            TextSelectMode::None
818        };
819        header_st
820            .get_mut_layout()
821            .set_flex_direction(FlexDirection::Row)
822            .set_width(Length::Percent(100.0))
823            .set_padding(Edges::symmetric(SPACE_SM, SPACE_MD))
824            .set_justify_content(JustifyContent::SpaceBetween)
825            .set_align_items(AlignItems::Center)
826            .set_row_gap(SPACE_SM)
827            .set_column_gap(SPACE_SM)
828            .set_overflow(Overflow::Hidden);
829        header_st
830            .get_mut_paint()
831            .set_radius(CornerRadius::new(
832                inner_radius_px,
833                inner_radius_px,
834                0.0,
835                0.0,
836            ))
837            .set_background(Some(eva.get_header_bg()));
838        let header_row: NodeId = tree.create_view(header_st);
839        let mut left_st: Style = Style::default();
840        left_st
841            .get_mut_layout()
842            .set_flex_direction(FlexDirection::Row)
843            .set_flex_grow(1.0)
844            .set_flex_shrink(1.0)
845            .set_min_width(Length::Px(0.0))
846            .set_align_items(AlignItems::Center)
847            .set_row_gap(SPACE_SM)
848            .set_column_gap(SPACE_SM)
849            .set_overflow(Overflow::Hidden);
850        let left_row: NodeId = tree.create_view(left_st);
851        let mut dots_st: Style = Style::default();
852        dots_st
853            .get_mut_layout()
854            .set_flex_direction(FlexDirection::Row)
855            .set_flex_shrink(0.0)
856            .set_row_gap(5.0)
857            .set_column_gap(5.0)
858            .set_align_items(AlignItems::Center);
859        let dots_row: NodeId = tree.create_view(dots_st);
860        let mut dot_st: Style = Style::default();
861        dot_st
862            .get_mut_layout()
863            .set_width(Length::Px(9.0))
864            .set_height(Length::Px(9.0));
865        dot_st
866            .get_mut_paint()
867            .set_radius(CornerRadius::all(RADIUS_PILL));
868        dot_st
869            .get_mut_paint()
870            .set_background(Some(Color::hex(CODE_DOT_RED)));
871        let dot_r: NodeId = tree.create_view(dot_st);
872        dot_st
873            .get_mut_paint()
874            .set_background(Some(Color::hex(CODE_DOT_YELLOW)));
875        let dot_y: NodeId = tree.create_view(dot_st);
876        dot_st
877            .get_mut_paint()
878            .set_background(Some(Color::hex(CODE_DOT_GREEN)));
879        let dot_g: NodeId = tree.create_view(dot_st);
880        tree.append_children(dots_row, &[dot_r, dot_y, dot_g]);
881        let mut title_st: Style = Style::default();
882        title_st
883            .get_mut_layout()
884            .set_flex_grow(1.0)
885            .set_flex_shrink(1.0)
886            .set_min_width(Length::Px(0.0))
887            .set_overflow(Overflow::Hidden);
888        title_st
889            .get_mut_text()
890            .set_overflow(TextOverflow::Ellipsis)
891            .set_font_size(12.0)
892            .set_weight(FontWeight::SemiBold)
893            .set_color(eva.get_foreground());
894        let title_txt: NodeId = tree.create_text(header_title_str.to_string(), title_st);
895        tree.append_children(left_row, &[dots_row, title_txt]);
896        let mut right_st: Style = Style::default();
897        right_st
898            .get_mut_layout()
899            .set_flex_direction(FlexDirection::Row)
900            .set_flex_shrink(0.0)
901            .set_align_items(AlignItems::Center)
902            .set_row_gap(SPACE_XS)
903            .set_column_gap(SPACE_XS);
904        let right_row: NodeId = tree.create_view(right_st);
905        let mut pill_st: Style = Style::default();
906        pill_st
907            .get_mut_layout()
908            .set_flex_direction(FlexDirection::Row)
909            .set_height(Length::Px(ctrl_sm))
910            .set_padding(Edges::symmetric(0.0, SPACE_SM))
911            .set_justify_content(JustifyContent::Center)
912            .set_align_items(AlignItems::Center)
913            .set_overflow(Overflow::Hidden);
914        pill_st
915            .get_mut_paint()
916            .set_radius(radius_sm)
917            .set_background(Some(eva_bg))
918            .set_border(eva_border);
919        let lang_badge: NodeId = tree.create_view(pill_st);
920        let mut lang_txt_st: Style = Style::default();
921        lang_txt_st
922            .get_mut_text()
923            .set_font_size(10.5)
924            .set_weight(FontWeight::Bold)
925            .set_color(eva.get_keyword())
926            .set_align(TextAlign::Center)
927            .set_overflow(TextOverflow::Clip);
928        let lang_txt: NodeId = tree.create_text(display_lang_rc.to_string(), lang_txt_st);
929        tree.append_child(lang_badge, lang_txt);
930        let mut icon_btn_st: Style = Style::default();
931        icon_btn_st
932            .get_mut_layout()
933            .set_flex_direction(FlexDirection::Row)
934            .set_width(Length::Px(ctrl_sm))
935            .set_height(Length::Px(ctrl_sm))
936            .set_justify_content(JustifyContent::Center)
937            .set_align_items(AlignItems::Center)
938            .set_overflow(Overflow::Hidden);
939        icon_btn_st
940            .get_mut_paint()
941            .set_radius(radius_sm)
942            .set_background(Some(eva_bg))
943            .set_border(eva_border)
944            .set_cursor(CursorIcon::Pointer);
945        let fs_btn: NodeId = tree.create_view(icon_btn_st);
946        let mut icon_st: Style = Style::default();
947        icon_st
948            .get_mut_layout()
949            .set_width(Length::Px(13.0))
950            .set_height(Length::Px(13.0));
951        let paint_fs_icon: CanvasDrawCallback = Rc::new(RefCell::new(
952            move |bounds: Rect, display_list: &mut DisplayList| {
953                let live_eva: CodeThemePalette =
954                    CodeThemePalette::resolve(live_tokens_untracked(base_tokens).get_mode());
955                draw_code_fullscreen_icon(bounds, display_list, live_eva.get_function());
956            },
957        ));
958        let fs_icon: NodeId = tree.create_canvas(icon_st, paint_fs_icon);
959        tree.append_child(fs_btn, fs_icon);
960        let copy_btn: NodeId = tree.create_view(icon_btn_st);
961        let copied_for_icon: Rc<Cell<bool>> = Rc::clone(&copied_cell);
962        let paint_copy_icon: CanvasDrawCallback = Rc::new(RefCell::new(
963            move |bounds: Rect, draw_commands: &mut DisplayList| {
964                let cur_tok: ThemeTokens = live_tokens_untracked(base_tokens);
965                let cur_eva: CodeThemePalette = CodeThemePalette::resolve(cur_tok.get_mode());
966                if copied_for_icon.get() {
967                    draw_euv_icon(
968                        EuvIconName::Check,
969                        bounds,
970                        draw_commands,
971                        cur_tok.get_palette().get_success(),
972                    );
973                } else {
974                    draw_euv_icon(
975                        EuvIconName::Copy,
976                        bounds,
977                        draw_commands,
978                        cur_eva.get_function(),
979                    );
980                }
981            },
982        ));
983        let copy_txt_node: NodeId = tree.create_canvas(icon_st, paint_copy_icon);
984        tree.append_child(copy_btn, copy_txt_node);
985        tree.append_children(right_row, &[lang_badge, fs_btn, copy_btn]);
986        tree.append_children(header_row, &[left_row, right_row]);
987        let mut div_st: Style = Style::default();
988        div_st
989            .get_mut_layout()
990            .set_width(Length::Percent(100.0))
991            .set_height(Length::Px(1.0));
992        div_st
993            .get_mut_paint()
994            .set_background(Some(eva.get_border()));
995        let div_node: NodeId = tree.create_view(div_st);
996        let mut scroll_st: Style = Style::default();
997        scroll_st
998            .get_mut_layout()
999            .set_flex_direction(FlexDirection::Column)
1000            .set_align_items(AlignItems::Stretch)
1001            .set_width(Length::Percent(100.0))
1002            .set_padding(Edges::all(0.0));
1003        scroll_st.get_mut_paint().set_radius(CornerRadius::new(
1004            0.0,
1005            0.0,
1006            inner_radius_px,
1007            inner_radius_px,
1008        ));
1009        if constrain_height {
1010            scroll_st
1011                .get_mut_layout()
1012                .set_max_height(Length::Px(inline_max_h));
1013        }
1014        let scroll_node: NodeId = tree.create_scroll_view(scroll_st);
1015        let (body_row, _, code_col): (NodeId, NodeId, NodeId) = mount_code_split_body_in_tree(
1016            tree,
1017            eva,
1018            (gutter_w, show_nums, select_mode, false),
1019            (gutter_nodes, code_nodes),
1020        );
1021        tree.append_child(scroll_node, body_row);
1022        let mut portal_st: Style = Style::default();
1023        portal_st
1024            .get_mut_layout()
1025            .set_display(Display::None)
1026            .set_flex_direction(FlexDirection::Column)
1027            .set_position(Position::Fixed)
1028            .set_top(Some(0.0))
1029            .set_right(Some(0.0))
1030            .set_bottom(Some(0.0))
1031            .set_left(Some(0.0))
1032            .set_width(Length::Percent(100.0))
1033            .set_height(Length::Percent(100.0))
1034            .set_padding(Edges::all(0.0))
1035            .set_margin(Edges::all(0.0))
1036            .set_justify_content(JustifyContent::Start)
1037            .set_align_items(AlignItems::Stretch)
1038            .set_overflow(Overflow::Hidden)
1039            .set_z_index(Z_INDEX_FULLSCREEN);
1040        portal_st
1041            .get_mut_paint()
1042            .set_background(Some(eva_bg))
1043            .set_border(Border::default())
1044            .set_radius(CornerRadius::all(0.0))
1045            .set_pointer_events(PointerEvents::None)
1046            .set_stop_scroll_propagation(true)
1047            .set_stop_event_propagation(true);
1048        let fs_portal: NodeId = tree.create_portal(portal_st);
1049        if let Some(node) = tree.get_node_mut(fs_portal) {
1050            node.get_mut_interaction().set_focusable(true);
1051        }
1052        let ctx_copy: Context = ctx.clone();
1053        let on_copy_inline: Option<MarkdownStrCallback> = on_copy.clone();
1054        let code_for_copy: Rc<str> = Rc::clone(&code_rc);
1055        let copied_for_copy: Rc<Cell<bool>> = Rc::clone(&copied_cell);
1056        let on_copy_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
1057            let selected_opt: Option<String> =
1058                ctx_copy.get_scene().get_selected_text_within(code_col);
1059            let payload: String = selected_opt.unwrap_or_else(|| code_for_copy.to_string());
1060            let _: bool = ctx_copy.copy_to_clipboard(payload.as_str());
1061            copied_for_copy.set(true);
1062            ctx_copy.get_scene().with_write(
1063                |scene_tree: &mut SceneTree| {
1064                    if let Some(item_count) = scene_tree.get_node_mut(copy_btn) {
1065                        *item_count.get_mut_a11y() = Some(A11yProps::new(
1066                            A11yRole::Button,
1067                            CODE_BUTTON_COPIED.to_string(),
1068                        ));
1069                    }
1070                    scene_tree.mark_dirty(copy_txt_node, DIRTY_PAINT);
1071                },
1072                (),
1073            );
1074            if let Some(callback_fn) = on_copy_inline.as_ref() {
1075                callback_fn(payload.as_str());
1076            }
1077        }));
1078        if let Some(node) = tree.get_node_mut(copy_btn) {
1079            node.get_mut_handlers().set_on_click(Some(on_copy_handler));
1080            node.get_mut_interaction().set_focusable(true);
1081            *node.get_mut_a11y() = Some(A11yProps::new(
1082                A11yRole::Button,
1083                CODE_BUTTON_COPY.to_string(),
1084            ));
1085        }
1086        let modal_hl: Vec<usize> = if highlight_lines.is_empty() {
1087            Vec::new()
1088        } else {
1089            highlight_lines.clone()
1090        };
1091        let modal_filename: Option<Rc<str>> = filename_rc;
1092        let modal_lang: Rc<str> = display_lang_rc;
1093        let modal_code_rc: Rc<str> = code_rc;
1094        let modal_on_copy: Option<MarkdownStrCallback> = on_copy.clone();
1095        let ctx_fs: Context = ctx.clone();
1096        let on_open_fs_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
1097            bind_fullscreen_context(&ctx_fs);
1098            if let Some(sig) = fs_open_slot.get() {
1099                if sig.get_untracked() {
1100                    let _: bool = sig.set_if_changed(false);
1101                }
1102                let _: bool = sig.set_if_changed(true);
1103                return;
1104            }
1105            let fs_open: Signal<bool> = Signal::new(true);
1106            fs_open_slot.set(Some(fs_open));
1107            let handle_ov: SceneHandle = ctx_fs.get_scene().clone();
1108            let handle_vp: SceneHandle = ctx_fs.get_scene().clone();
1109            let prev_open: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1110            let fs_acquired: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1111            let in_enter_guard: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1112            let fs_cleanup: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
1113            let ctx_build: Context = ctx_fs.clone();
1114            let code_build: Rc<str> = Rc::clone(&modal_code_rc);
1115            let lang_build: Rc<str> = Rc::clone(&modal_lang);
1116            let file_build: Option<Rc<str>> = modal_filename.clone();
1117            let hl_build: Vec<usize> = modal_hl.clone();
1118            let cb_build: Option<MarkdownStrCallback> = modal_on_copy.clone();
1119            let copied_build: Rc<Cell<bool>> = Rc::clone(&copied_cell);
1120            let on_fs_key: UiEventHandler = Rc::new(RefCell::new(move |ui_event: &UiEvent| {
1121                if matches!(
1122                    ui_event.get_kind(),
1123                    UiEventKind::KeyDown(KeyCode::Escape | KeyCode::Back, _)
1124                ) && fs_open.get_untracked()
1125                {
1126                    let _: bool = fs_open.set_if_changed(false);
1127                }
1128            }));
1129            ctx_fs.get_scene().with_write(
1130                |tree_ref: &mut SceneTree| {
1131                    if let Some(node) = tree_ref.get_node_mut(fs_portal) {
1132                        node.get_mut_handlers().set_on_key_down(Some(on_fs_key));
1133                    }
1134                },
1135                (),
1136            );
1137            let (ov_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1138                on_cleanup(move || {
1139                    if fs_cleanup.replace(false) {
1140                        exit_fullscreen();
1141                    }
1142                });
1143                let _: Effect = EuvOverlayStack::bind_signal(
1144                    fs_open,
1145                    CODE_FULLSCREEN_OVERLAY_NAME,
1146                    Z_INDEX_FULLSCREEN,
1147                );
1148                let vp_sig: Signal<Size> = ctx_build.get_viewport_size();
1149                let _: Effect = Effect::new(move || {
1150                    let box_size: Size = vp_sig.get();
1151                    if !fs_open.get() {
1152                        return;
1153                    }
1154                    let vw: f32 = box_size.get_width().max(1.0);
1155                    let vh: f32 = box_size.get_height().max(1.0);
1156                    handle_vp.with_write(
1157                        |blend_factor: &mut SceneTree| {
1158                            if let Some(node_entry) = blend_factor.get_node_mut(fs_portal) {
1159                                node_entry
1160                                    .get_mut_style()
1161                                    .get_mut_layout()
1162                                    .set_width(Length::Px(vw))
1163                                    .set_height(Length::Px(vh));
1164                                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1165                                blend_factor.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
1166                                notify_frame_needed();
1167                            }
1168                        },
1169                        (),
1170                    );
1171                });
1172                let global_fs_sig: Signal<bool> = use_fullscreen_active();
1173                let ctx_fs_sig: Signal<bool> = ctx_build.immersive_fullscreen_signal();
1174                let saw_global_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1175                let saw_ctx_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
1176                let saw_global_reset: Rc<Cell<bool>> = Rc::clone(&saw_global_fs);
1177                let saw_ctx_reset: Rc<Cell<bool>> = Rc::clone(&saw_ctx_fs);
1178                let fs_acquired_sync: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
1179                let enter_guard_sync: Rc<Cell<bool>> = Rc::clone(&in_enter_guard);
1180                let _: Effect = Effect::new(move || {
1181                    let g_active: bool = global_fs_sig.get();
1182                    let c_active: bool = ctx_fs_sig.get();
1183                    if enter_guard_sync.get() {
1184                        if g_active {
1185                            saw_global_fs.set(true);
1186                        }
1187                        if c_active {
1188                            saw_ctx_fs.set(true);
1189                        }
1190                        return;
1191                    }
1192                    if !fs_acquired_sync.get() {
1193                        saw_global_fs.set(false);
1194                        saw_ctx_fs.set(false);
1195                        return;
1196                    }
1197                    if g_active {
1198                        saw_global_fs.set(true);
1199                    }
1200                    if c_active {
1201                        saw_ctx_fs.set(true);
1202                    }
1203                    let external_exit: bool =
1204                        (saw_global_fs.get() && !g_active) || (saw_ctx_fs.get() && !c_active);
1205                    if external_exit {
1206                        let _: bool = fs_open.set_if_changed(false);
1207                    }
1208                });
1209                Effect::new(move || {
1210                    let is_open: bool = fs_open.get();
1211                    if is_open == prev_open.replace(is_open) {
1212                        return;
1213                    }
1214                    if is_open {
1215                        in_enter_guard.set(true);
1216                        saw_global_reset.set(false);
1217                        saw_ctx_reset.set(false);
1218                        let live_eva: CodeThemePalette = CodeThemePalette::resolve(
1219                            live_tokens_untracked(base_tokens).get_mode(),
1220                        );
1221                        let vp_now: Size = vp_sig.get_untracked();
1222                        let vw: f32 = vp_now.get_width().max(1.0);
1223                        let vh: f32 = vp_now.get_height().max(1.0);
1224                        let modal_card: NodeId = with_context(ctx_build.clone(), || {
1225                            Self::mount_fullscreen_modal_card(
1226                                &ctx_build,
1227                                base_tokens,
1228                                &code_build,
1229                                &lang_build,
1230                                file_build.as_deref(),
1231                                (
1232                                    code_lang,
1233                                    show_nums,
1234                                    line_count,
1235                                    fs_open,
1236                                    copy_txt_node,
1237                                    select_mode,
1238                                ),
1239                                (&hl_build, &copied_build, cb_build.as_ref()),
1240                            )
1241                        });
1242                        let portal_shown: bool = modal_card != NodeId::default()
1243                            && handle_ov.with_write(
1244                                |time_step: &mut SceneTree| {
1245                                    if time_step.get_node(fs_portal).is_none()
1246                                        || time_step.get_node(modal_card).is_none()
1247                                    {
1248                                        return false;
1249                                    }
1250                                    time_step.cancel_subtree_transitions(fs_portal);
1251                                    time_step.replace_children(fs_portal, vec![modal_card]);
1252                                    if let Some(normal_vec) = time_step.get_node_mut(fs_portal) {
1253                                        let computed_style: &mut Style = normal_vec.get_mut_style();
1254                                        computed_style
1255                                            .get_mut_layout()
1256                                            .set_display(Display::Flex)
1257                                            .set_width(Length::Px(vw))
1258                                            .set_height(Length::Px(vh));
1259                                        computed_style
1260                                            .get_mut_paint()
1261                                            .set_background(Some(live_eva.get_background()))
1262                                            .set_pointer_events(PointerEvents::Auto)
1263                                            .set_opacity(1.0)
1264                                            .set_transform(Transform2D::default());
1265                                    }
1266                                    let _: Vec<(UiEventHandler, UiEvent)> =
1267                                        time_step.update_focus(Some(fs_portal));
1268                                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1269                                    time_step.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
1270                                    notify_frame_needed();
1271                                    true
1272                                },
1273                                false,
1274                            );
1275                        let entered: bool = portal_shown
1276                            && (fs_acquired.get()
1277                                || enter_fullscreen_for_portal(&ctx_build, fs_portal));
1278                        if entered {
1279                            fs_acquired.set(true);
1280                        } else {
1281                            handle_ov.dismiss_portal_immediate(fs_portal);
1282                            if fs_acquired.replace(false) {
1283                                exit_fullscreen();
1284                            }
1285                            prev_open.set(false);
1286                            let _: bool = fs_open.set_if_changed(false);
1287                        }
1288                        in_enter_guard.set(false);
1289                        notify_frame_needed();
1290                    } else {
1291                        in_enter_guard.set(false);
1292                        if fs_acquired.replace(false) {
1293                            exit_fullscreen();
1294                        }
1295                        handle_ov.dismiss_portal_immediate(fs_portal);
1296                    }
1297                })
1298            });
1299            ctx_fs.get_scene().with_write(
1300                |token_val: &mut SceneTree| {
1301                    token_val.attach_scope(root, ov_scope);
1302                },
1303                (),
1304            );
1305        }));
1306        if let Some(node) = tree.get_node_mut(fs_btn) {
1307            node.get_mut_handlers()
1308                .set_on_click(Some(on_open_fs_handler));
1309            node.get_mut_interaction().set_focusable(true);
1310            *node.get_mut_a11y() = Some(A11yProps::new(
1311                A11yRole::Button,
1312                CODE_BUTTON_FULLSCREEN.to_string(),
1313            ));
1314        }
1315        tree.append_children(root, &[header_row, div_node, scroll_node, fs_portal]);
1316        root
1317    }
1318}
1319
1320/// Declarative `#[component]` implementation for `EuvCodeBlock`.
1321#[component]
1322/// Inherent implementation of [`EuvCodeBlock`].
1323impl EuvCodeBlock {
1324    /// Renders the syntax-highlighted Eva-themed code block with true H+V scrolling, header chrome, gutter, interactive Copy pill, and Fullscreen modal portal.
1325    ///
1326    /// # Arguments
1327    ///
1328    /// - `&Self` - Code block reference.
1329    ///
1330    /// # Returns
1331    ///
1332    /// - `NodeId` - Mounted code block container handle.
1333    fn render(&self) -> NodeId {
1334        let ctx: Context = current_context();
1335        ctx.get_scene().with_write(
1336            |tree: &mut SceneTree| self.mount_in_tree(tree, &ctx),
1337            NodeId::default(),
1338        )
1339    }
1340}
1341
1342/// Fluent builder helpers for `EuvMarkdownHeading`.
1343impl EuvMarkdownHeading {
1344    /// Sets the interactive text selection and copy mode for the heading (`TextSelectMode::None` by default).
1345    ///
1346    /// # Arguments
1347    ///
1348    /// - `Self` - Source heading.
1349    /// - `TextSelectMode` - Selection mode applied to the heading text.
1350    ///
1351    /// # Returns
1352    ///
1353    /// - `Self` - Updated heading.
1354    #[must_use]
1355    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
1356        self.set_text_select(Some(mode));
1357        self
1358    }
1359
1360    /// Controls whether the heading text is selectable.
1361    ///
1362    /// # Arguments
1363    ///
1364    /// - `Self` - Source heading.
1365    /// - `bool` - Whether selection is enabled.
1366    ///
1367    /// # Returns
1368    ///
1369    /// - `Self` - Updated heading.
1370    #[must_use]
1371    pub fn selectable(self, enabled: bool) -> Self {
1372        let mode: TextSelectMode = if enabled {
1373            TextSelectMode::SelectAndCopy
1374        } else {
1375            TextSelectMode::None
1376        };
1377        self.text_select(mode)
1378    }
1379    /// Mounts a Markdown heading (`H1`–`H6`) directly into an already-borrowed `SceneTree`.
1380    ///
1381    /// # Arguments
1382    ///
1383    /// - `&Self` - Heading component reference.
1384    /// - `&mut SceneTree` - Mutable scene tree.
1385    ///
1386    /// # Returns
1387    ///
1388    /// - `NodeId` - Mounted heading node handle.
1389    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree) -> NodeId {
1390        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
1391        let palette: ThemePalette = tokens.get_palette();
1392        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
1393        let lvl: u8 = self.get_level().clamp(1, 6);
1394        let size: f32 = match lvl {
1395            1 => 24.0,
1396            2 => 19.5,
1397            3 => 16.5,
1398            4 => 15.0,
1399            5 => 13.5,
1400            _ => 12.5,
1401        };
1402        let Self {
1403            text, text_select, ..
1404        } = self;
1405        let show_rule: bool = lvl <= 2;
1406        let heading_str: String = if text.contains(':') {
1407            expand_emoji_shortcodes(text.as_str())
1408        } else {
1409            text.clone()
1410        };
1411        let a11y_heading_title: String = if has_inline_markdown_trigger(text.as_str()) {
1412            let expanded_inlines: Vec<EuvMarkdownInline> = parse_markdown_inlines(text.as_str());
1413            let mut plain_buf: String = String::with_capacity(text.len());
1414            for seg in expanded_inlines.into_iter() {
1415                match seg {
1416                    EuvMarkdownInline::Text(source_val)
1417                    | EuvMarkdownInline::Bold(source_val)
1418                    | EuvMarkdownInline::Italic(source_val)
1419                    | EuvMarkdownInline::BoldItalic(source_val)
1420                    | EuvMarkdownInline::Code(source_val)
1421                    | EuvMarkdownInline::Strike(source_val)
1422                    | EuvMarkdownInline::Highlight(source_val)
1423                    | EuvMarkdownInline::Superscript(source_val)
1424                    | EuvMarkdownInline::Subscript(source_val)
1425                    | EuvMarkdownInline::Math(source_val)
1426                    | EuvMarkdownInline::Kbd(source_val) => plain_buf.push_str(&source_val),
1427                    EuvMarkdownInline::Link { label, .. } => plain_buf.push_str(&label),
1428                    EuvMarkdownInline::Image { alt, .. }
1429                    | EuvMarkdownInline::LinkedImage { alt, .. } => plain_buf.push_str(&alt),
1430                    EuvMarkdownInline::FootnoteRef(id) => plain_buf.push_str(&format!("[{id}]")),
1431                    EuvMarkdownInline::HardBreak => plain_buf.push(' '),
1432                }
1433            }
1434            plain_buf.trim().to_string()
1435        } else {
1436            heading_str.trim().to_string()
1437        };
1438        let mut col_st: Style = Style::default();
1439        col_st
1440            .get_mut_layout()
1441            .set_flex_direction(FlexDirection::Column)
1442            .set_width(Length::Percent(100.0))
1443            .set_row_gap(SPACE_XS)
1444            .set_column_gap(SPACE_XS)
1445            .set_padding(Edges::new(
1446                if lvl == 1 {
1447                    0.0
1448                } else if lvl == 2 {
1449                    SPACE_SM
1450                } else {
1451                    SPACE_XS
1452                },
1453                0.0,
1454                0.0,
1455                0.0,
1456            ));
1457        let root: NodeId = tree.create_view(col_st);
1458        let mut row_st: Style = Style::default();
1459        row_st
1460            .get_mut_layout()
1461            .set_flex_direction(FlexDirection::Row)
1462            .set_width(Length::Percent(100.0))
1463            .set_align_items(AlignItems::Center)
1464            .set_row_gap(SPACE_SM)
1465            .set_column_gap(SPACE_SM);
1466        let row_id: NodeId = tree.create_view(row_st);
1467        let heading_fg: Color = if lvl == 6 {
1468            palette.get_muted_foreground()
1469        } else {
1470            palette.get_foreground()
1471        };
1472        let heading_content_id: NodeId = if has_inline_markdown_trigger(text.as_str()) {
1473            let inlines: Vec<EuvMarkdownInline> = parse_markdown_inlines(text.as_str());
1474            let has_rich: bool = inlines
1475                .iter()
1476                .any(|seg: &EuvMarkdownInline| !matches!(seg, EuvMarkdownInline::Text(_)));
1477            if !has_rich {
1478                let mut txt_st: Style = Style::default();
1479                if let Some(mode) = *text_select {
1480                    txt_st = txt_st.text_select(mode);
1481                }
1482                txt_st
1483                    .get_mut_layout()
1484                    .set_flex_grow(1.0)
1485                    .set_flex_shrink(1.0)
1486                    .set_min_width(Length::Px(0.0));
1487                txt_st
1488                    .get_mut_text()
1489                    .set_font_size(size)
1490                    .set_weight(FontWeight::Bold)
1491                    .set_color(heading_fg);
1492                let plain: String = inlines
1493                    .into_iter()
1494                    .map(|seg: EuvMarkdownInline| match seg {
1495                        EuvMarkdownInline::Text(scale_val) => scale_val,
1496                        _ => String::new(),
1497                    })
1498                    .collect();
1499                tree.create_text(plain, txt_st)
1500            } else {
1501                let geometry: ThemeGeometry = tokens.get_geometry();
1502                let mut wrap_st: Style = Style::default();
1503                if let Some(mode) = *text_select {
1504                    wrap_st = wrap_st.text_select(mode);
1505                }
1506                wrap_st
1507                    .get_mut_layout()
1508                    .set_flex_direction(FlexDirection::Row)
1509                    .set_flex_grow(1.0)
1510                    .set_flex_shrink(1.0)
1511                    .set_min_width(Length::Px(0.0))
1512                    .set_flex_wrap(FlexWrap::Wrap)
1513                    .set_align_items(AlignItems::Center)
1514                    .set_row_gap(4.0)
1515                    .set_column_gap(0.0);
1516                let wrap_id: NodeId = tree.create_view(wrap_st);
1517                let expanded_inlines: Vec<EuvMarkdownInline> =
1518                    expand_inline_words_for_wrap(&inlines);
1519                let mut kids: Vec<NodeId> = Vec::with_capacity(expanded_inlines.len());
1520                for seg in expanded_inlines.into_iter() {
1521                    let kid: NodeId = match seg {
1522                        EuvMarkdownInline::Code(code) => {
1523                            let mut chip_st: Style = Style::default();
1524                            chip_st
1525                                .get_mut_layout()
1526                                .set_flex_direction(FlexDirection::Row)
1527                                .set_align_items(AlignItems::Center)
1528                                .set_max_width(Length::Percent(100.0))
1529                                .set_padding(Edges::symmetric(1.0, 6.0))
1530                                .set_overflow(Overflow::Hidden);
1531                            chip_st
1532                                .get_mut_paint()
1533                                .set_background(Some(eva.get_inline_code_bg()))
1534                                .set_border(Border::new(1.0, eva.get_border()))
1535                                .set_radius(CornerRadius::all(geometry.get_radius_sm()));
1536                            let mut code_txt_st: Style = Style::default();
1537                            if let Some(mode) = *text_select {
1538                                code_txt_st = code_txt_st.text_select(mode);
1539                            }
1540                            code_txt_st
1541                                .get_mut_text()
1542                                .set_font_size((size * 0.86).max(12.0))
1543                                .set_family(FontFamily::Monospace)
1544                                .set_weight(FontWeight::Bold)
1545                                .set_color(eva.get_inline_code_fg());
1546                            let chip_id: NodeId = tree.create_view(chip_st);
1547                            let ctxt_id: NodeId = tree.create_text(code, code_txt_st);
1548                            tree.append_child(chip_id, ctxt_id);
1549                            chip_id
1550                        }
1551                        EuvMarkdownInline::Italic(blend_factor)
1552                        | EuvMarkdownInline::BoldItalic(blend_factor) => {
1553                            let mut computed_style: Style = Style::default();
1554                            if let Some(mode) = *text_select {
1555                                computed_style = computed_style.text_select(mode);
1556                            }
1557                            computed_style
1558                                .get_mut_layout()
1559                                .set_max_width(Length::Percent(100.0));
1560                            computed_style
1561                                .get_mut_text()
1562                                .set_font_size(size)
1563                                .set_weight(FontWeight::Bold)
1564                                .set_italic(true)
1565                                .set_overflow(inline_word_overflow(blend_factor.as_str()))
1566                                .set_color(heading_fg);
1567                            tree.create_text(blend_factor, computed_style)
1568                        }
1569                        EuvMarkdownInline::Strike(time_step) => {
1570                            let mut element_style: Style = Style::default();
1571                            if let Some(mode) = *text_select {
1572                                element_style = element_style.text_select(mode);
1573                            }
1574                            element_style
1575                                .get_mut_layout()
1576                                .set_max_width(Length::Percent(100.0));
1577                            element_style
1578                                .get_mut_text()
1579                                .set_font_size(size)
1580                                .set_weight(FontWeight::Bold)
1581                                .set_strikethrough(true)
1582                                .set_overflow(inline_word_overflow(time_step.as_str()))
1583                                .set_color(palette.get_muted_foreground());
1584                            tree.create_text(time_step, element_style)
1585                        }
1586                        EuvMarkdownInline::Link { label, .. } => {
1587                            let clean_lbl: String = if has_inline_markdown_trigger(label.as_str()) {
1588                                parse_markdown_inlines(label.as_str())
1589                                    .into_iter()
1590                                    .map(|sub: EuvMarkdownInline| match sub {
1591                                        EuvMarkdownInline::Text(series_item)
1592                                        | EuvMarkdownInline::Bold(series_item)
1593                                        | EuvMarkdownInline::Italic(series_item)
1594                                        | EuvMarkdownInline::BoldItalic(series_item)
1595                                        | EuvMarkdownInline::Code(series_item) => series_item,
1596                                        _ => String::new(),
1597                                    })
1598                                    .collect()
1599                            } else {
1600                                label
1601                            };
1602                            let pieces: Vec<String> = split_inline_wrap_pieces(clean_lbl.as_str());
1603                            if pieces.len() <= 1 {
1604                                let piece: String = pieces.into_iter().next().unwrap_or(clean_lbl);
1605                                let mut resolved_style: Style = Style::default();
1606                                if let Some(mode) = *text_select {
1607                                    resolved_style = resolved_style.text_select(mode);
1608                                }
1609                                resolved_style
1610                                    .get_mut_layout()
1611                                    .set_max_width(Length::Percent(100.0));
1612                                resolved_style
1613                                    .get_mut_text()
1614                                    .set_font_size(size)
1615                                    .set_weight(FontWeight::Bold)
1616                                    .set_underline(true)
1617                                    .set_overflow(inline_word_overflow(piece.as_str()))
1618                                    .set_color(eva.get_link());
1619                                tree.create_text(piece, resolved_style)
1620                            } else {
1621                                let mut last_id: NodeId = NodeId::default();
1622                                let last_idx: usize = pieces.len() - 1;
1623                                for (p_idx, piece) in pieces.into_iter().enumerate() {
1624                                    let mut resolved_style: Style = Style::default();
1625                                    if let Some(mode) = *text_select {
1626                                        resolved_style = resolved_style.text_select(mode);
1627                                    }
1628                                    resolved_style
1629                                        .get_mut_layout()
1630                                        .set_max_width(Length::Percent(100.0));
1631                                    resolved_style
1632                                        .get_mut_text()
1633                                        .set_font_size(size)
1634                                        .set_weight(FontWeight::Bold)
1635                                        .set_underline(true)
1636                                        .set_overflow(inline_word_overflow(piece.as_str()))
1637                                        .set_color(eva.get_link());
1638                                    let nid: NodeId = tree.create_text(piece, resolved_style);
1639                                    if p_idx == last_idx {
1640                                        last_id = nid;
1641                                    } else {
1642                                        kids.push(nid);
1643                                    }
1644                                }
1645                                last_id
1646                            }
1647                        }
1648                        EuvMarkdownInline::Text(token_val)
1649                        | EuvMarkdownInline::Bold(token_val)
1650                        | EuvMarkdownInline::Highlight(token_val)
1651                        | EuvMarkdownInline::Superscript(token_val)
1652                        | EuvMarkdownInline::Subscript(token_val)
1653                        | EuvMarkdownInline::Math(token_val)
1654                        | EuvMarkdownInline::Kbd(token_val) => {
1655                            let mut node_style: Style = Style::default();
1656                            if let Some(mode) = *text_select {
1657                                node_style = node_style.text_select(mode);
1658                            }
1659                            node_style
1660                                .get_mut_layout()
1661                                .set_max_width(Length::Percent(100.0));
1662                            node_style
1663                                .get_mut_text()
1664                                .set_font_size(size)
1665                                .set_weight(FontWeight::Bold)
1666                                .set_overflow(inline_word_overflow(token_val.as_str()))
1667                                .set_color(heading_fg);
1668                            tree.create_text(token_val, node_style)
1669                        }
1670                        EuvMarkdownInline::FootnoteRef(id) => {
1671                            let mut active_style: Style = Style::default();
1672                            active_style
1673                                .get_mut_text()
1674                                .set_font_size((size * 0.65).max(10.0))
1675                                .set_weight(FontWeight::Bold)
1676                                .set_color(palette.get_primary());
1677                            tree.create_text(format!("[{id}]"), active_style)
1678                        }
1679                        EuvMarkdownInline::Image { alt, .. }
1680                        | EuvMarkdownInline::LinkedImage { alt, .. } => {
1681                            let mut state_val: Style = Style::default();
1682                            state_val
1683                                .get_mut_text()
1684                                .set_font_size(size)
1685                                .set_weight(FontWeight::Bold)
1686                                .set_color(heading_fg);
1687                            tree.create_text(alt, state_val)
1688                        }
1689                        EuvMarkdownInline::HardBreak => {
1690                            let mut computed_style_primary: Style = Style::default();
1691                            computed_style_primary
1692                                .get_mut_layout()
1693                                .set_width(Length::Px(0.0))
1694                                .set_height(Length::Px(0.0));
1695                            tree.create_view(computed_style_primary)
1696                        }
1697                    };
1698                    kids.push(kid);
1699                }
1700                if !kids.is_empty() {
1701                    tree.append_children(wrap_id, &kids);
1702                }
1703                wrap_id
1704            }
1705        } else {
1706            let mut txt_st: Style = Style::default();
1707            if let Some(mode) = *text_select {
1708                txt_st = txt_st.text_select(mode);
1709            }
1710            txt_st
1711                .get_mut_layout()
1712                .set_flex_grow(1.0)
1713                .set_flex_shrink(1.0)
1714                .set_min_width(Length::Px(0.0));
1715            txt_st
1716                .get_mut_text()
1717                .set_font_size(size)
1718                .set_weight(FontWeight::Bold)
1719                .set_color(heading_fg);
1720            tree.create_text(heading_str, txt_st)
1721        };
1722        if lvl == 1 {
1723            let mut bar_st: Style = Style::default();
1724            bar_st
1725                .get_mut_layout()
1726                .set_width(Length::Px(4.0))
1727                .set_height(Length::Px(22.0));
1728            bar_st
1729                .get_mut_paint()
1730                .set_radius(CornerRadius::all(RADIUS_PILL))
1731                .set_background(Some(eva.get_keyword()));
1732            let bar_id: NodeId = tree.create_view(bar_st);
1733            tree.append_children(row_id, &[bar_id, heading_content_id]);
1734        } else {
1735            tree.append_child(row_id, heading_content_id);
1736        }
1737        if let Some(root_node) = tree.get_node_mut(root) {
1738            *root_node.get_mut_a11y() = Some(A11yProps::new(A11yRole::Heading, a11y_heading_title));
1739        }
1740        if show_rule {
1741            let mut rule_st: Style = Style::default();
1742            rule_st
1743                .get_mut_layout()
1744                .set_width(Length::Percent(100.0))
1745                .set_height(Length::Px(1.0));
1746            rule_st
1747                .get_mut_paint()
1748                .set_background(Some(palette.get_border()));
1749            let rule_id: NodeId = tree.create_view(rule_st);
1750            tree.append_children(root, &[row_id, rule_id]);
1751        } else {
1752            tree.append_child(root, row_id);
1753        }
1754        root
1755    }
1756}
1757
1758/// Declarative `#[component]` implementation for `EuvMarkdownHeading`.
1759#[component]
1760/// Inherent implementation of [`EuvMarkdownHeading`].
1761impl EuvMarkdownHeading {
1762    /// Renders a Markdown heading (`H1`–`H6`) with crisp scale and subtle bottom rule for `H1`/`H2`.
1763    ///
1764    /// # Arguments
1765    ///
1766    /// - `&Self` - Heading component reference.
1767    ///
1768    /// # Returns
1769    ///
1770    /// - `NodeId` - Mounted heading node handle.
1771    fn render(&self) -> NodeId {
1772        let ctx: Context = current_context();
1773        ctx.get_scene().with_write(
1774            |tree: &mut SceneTree| self.mount_in_tree(tree),
1775            NodeId::default(),
1776        )
1777    }
1778}
1779
1780/// Direct tree mounting helper for `EuvMarkdownInlineCode`.
1781impl EuvMarkdownInlineCode {
1782    /// Mounts an inline monospace code pill directly into an already-borrowed `SceneTree`.
1783    ///
1784    /// # Arguments
1785    ///
1786    /// - `&mut SceneTree` - Mutable scene tree.
1787    /// - `&str` - Inline code snippet slice.
1788    /// - `ThemeTokens` - Active theme tokens.
1789    /// - `CodeThemePalette` - Resolved Eva palette.
1790    ///
1791    /// # Returns
1792    ///
1793    /// - `NodeId` - Mounted inline code pill handle.
1794    pub(crate) fn mount_in_tree(
1795        tree: &mut SceneTree,
1796        snippet: &str,
1797        tokens: ThemeTokens,
1798        eva: CodeThemePalette,
1799    ) -> NodeId {
1800        let geometry: ThemeGeometry = tokens.get_geometry();
1801        let mut row_st: Style = Style::default();
1802        row_st
1803            .get_mut_layout()
1804            .set_flex_direction(FlexDirection::Row)
1805            .set_align_self(AlignSelf::Start)
1806            .set_max_width(Length::Percent(100.0))
1807            .set_padding(Edges::symmetric(1.0, SPACE_XS))
1808            .set_justify_content(JustifyContent::Center)
1809            .set_align_items(AlignItems::Center)
1810            .set_overflow(Overflow::Hidden);
1811        row_st
1812            .get_mut_paint()
1813            .set_radius(CornerRadius::all(geometry.get_radius_sm()))
1814            .set_background(Some(eva.get_inline_code_bg()))
1815            .set_border(Border::new(1.0, eva.get_border()));
1816        let mut txt_st: Style = Style::default();
1817        txt_st
1818            .get_mut_layout()
1819            .set_max_width(Length::Percent(100.0))
1820            .set_overflow(Overflow::Hidden);
1821        txt_st
1822            .get_mut_text()
1823            .set_overflow(TextOverflow::Clip)
1824            .set_align(TextAlign::Center)
1825            .set_font_size(12.0)
1826            .set_family(FontFamily::Monospace)
1827            .set_weight(FontWeight::Normal)
1828            .set_color(eva.get_inline_code_fg());
1829        let root: NodeId = tree.create_view(row_st);
1830        let txt_id: NodeId = tree.create_text(snippet.to_string(), txt_st);
1831        tree.append_child(root, txt_id);
1832        root
1833    }
1834}
1835
1836/// Declarative `#[component]` implementation for `EuvMarkdownInlineCode`.
1837#[component]
1838/// Inherent implementation of [`EuvMarkdownInlineCode`].
1839impl EuvMarkdownInlineCode {
1840    /// Renders an inline monospace code pill styled with exact VS Code Eva inline-code colors.
1841    ///
1842    /// # Arguments
1843    ///
1844    /// - `&Self` - Inline code component reference.
1845    ///
1846    /// # Returns
1847    ///
1848    /// - `NodeId` - Mounted inline code pill handle.
1849    fn render(&self) -> NodeId {
1850        let ctx: Context = current_context();
1851        bind_fullscreen_context(&ctx);
1852        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
1853        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
1854        let snippet: &str = self.get_code().as_str();
1855        ctx.get_scene().with_write(
1856            |tree: &mut SceneTree| Self::mount_in_tree(tree, snippet, tokens, eva),
1857            NodeId::default(),
1858        )
1859    }
1860}
1861
1862/// Fluent builder helpers for `EuvMarkdownMath`.
1863impl EuvMarkdownMath {
1864    /// Sets the interactive text selection and copy mode for the math block (`TextSelectMode::None` by default).
1865    ///
1866    /// # Arguments
1867    ///
1868    /// - `Self` - Source math block.
1869    /// - `TextSelectMode` - Selection mode applied to the formula text.
1870    ///
1871    /// # Returns
1872    ///
1873    /// - `Self` - Updated math block.
1874    #[must_use]
1875    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
1876        self.set_text_select(Some(mode));
1877        self
1878    }
1879
1880    /// Controls whether the math expression text is selectable.
1881    ///
1882    /// # Arguments
1883    ///
1884    /// - `Self` - Source math block.
1885    /// - `bool` - Whether selection is enabled.
1886    ///
1887    /// # Returns
1888    ///
1889    /// - `Self` - Updated math block.
1890    #[must_use]
1891    pub fn selectable(self, enabled: bool) -> Self {
1892        let mode: TextSelectMode = if enabled {
1893            TextSelectMode::SelectAndCopy
1894        } else {
1895            TextSelectMode::None
1896        };
1897        self.text_select(mode)
1898    }
1899}
1900
1901/// Declarative `#[component]` implementation for `EuvMarkdownMath`.
1902#[component]
1903/// Inherent implementation of [`EuvMarkdownMath`].
1904impl EuvMarkdownMath {
1905    /// Renders a display LaTeX/math formula card formatted with crisp Unicode mathematical typography.
1906    ///
1907    /// # Arguments
1908    ///
1909    /// - `&Self` - Math block component reference.
1910    ///
1911    /// # Returns
1912    ///
1913    /// - `NodeId` - Mounted display math card handle.
1914    fn render(&self) -> NodeId {
1915        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
1916        let palette: ThemePalette = tokens.get_palette();
1917        let geometry: ThemeGeometry = tokens.get_geometry();
1918        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
1919        let Self {
1920            expression,
1921            text_select,
1922            ..
1923        } = self;
1924        let math_select: Option<TextSelectMode> = *text_select;
1925        let formatted_lines: Vec<String> = expression
1926            .lines()
1927            .map(format_latex_math)
1928            .filter(|text_value: &String| !text_value.is_empty())
1929            .collect();
1930        let display_lines: Vec<String> = if formatted_lines.is_empty() {
1931            vec![format_latex_math(expression)]
1932        } else {
1933            formatted_lines
1934        };
1935        let mut line_base_st: Style = style! {
1936            Width(Length::Percent(100.0))
1937            FontSize(16.0)
1938            FontFamily::Monospace
1939            FontWeight::Medium
1940            TextColor(palette.get_foreground())
1941            TextAlign::Center
1942        };
1943        if let Some(mode) = math_select {
1944            line_base_st = line_base_st.text_select(mode);
1945        }
1946        let line_nodes: Vec<NodeId> = display_lines
1947            .into_iter()
1948            .map(|line_str: String| {
1949                view! {
1950                    text {
1951                        style: line_base_st
1952                        { line_str }
1953                    }
1954                }
1955            })
1956            .collect();
1957        let column_fifth_style: Style = style! {
1958            Width(Length::Percent(100.0))
1959            Padding(Edges::symmetric(SPACE_MD, SPACE_MD))
1960            Gap(SPACE_XS)
1961            Background(eva.get_header_bg())
1962            Border::new(1.0, eva.get_border())
1963            Radius(geometry.get_radius_md())
1964            Overflow::Hidden
1965        };
1966        let row_sixth_style: Style = style! {
1967            Width(Length::Percent(100.0))
1968            JustifyContent::End
1969            TextSelectMode::None
1970        };
1971        let row_seventh_style: Style = style! {
1972            FlexShrink(0.0)
1973            Padding(Edges::symmetric(2.0, 6.0))
1974            Radius(geometry.get_radius_sm())
1975            Background(eva.get_background())
1976            Border::new(1.0, eva.get_border())
1977        };
1978        let text_quaternary_style: Style = style! {
1979            FontSize(9.5)
1980            FontWeight::Bold
1981            TextColor(eva.get_keyword())
1982            TextOverflow::Clip
1983        };
1984        view! {
1985            column {
1986                style: column_fifth_style
1987                row {
1988                    style: row_sixth_style
1989                    row {
1990                        style: row_seventh_style
1991                        text {
1992                            style: text_quaternary_style
1993                            { MD_MATH_BADGE }
1994                        }
1995                    }
1996                }
1997                ..line_nodes
1998            }
1999        }
2000    }
2001}
2002
2003/// Fluent builder helpers for `EuvMarkdownParagraph`.
2004impl EuvMarkdownParagraph {
2005    /// Sets the interactive text selection and copy mode for the paragraph (`TextSelectMode::None` by default).
2006    ///
2007    /// # Arguments
2008    ///
2009    /// - `Self` - Source paragraph.
2010    /// - `TextSelectMode` - Selection mode applied to the paragraph text.
2011    ///
2012    /// # Returns
2013    ///
2014    /// - `Self` - Updated paragraph.
2015    #[must_use]
2016    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
2017        self.set_text_select(Some(mode));
2018        self
2019    }
2020
2021    /// Controls whether paragraph text is selectable.
2022    ///
2023    /// # Arguments
2024    ///
2025    /// - `Self` - Source paragraph.
2026    /// - `bool` - Whether text selection is enabled.
2027    ///
2028    /// # Returns
2029    ///
2030    /// - `Self` - Updated paragraph.
2031    #[must_use]
2032    pub fn selectable(self, enabled: bool) -> Self {
2033        let mode: TextSelectMode = if enabled {
2034            TextSelectMode::SelectAndCopy
2035        } else {
2036            TextSelectMode::None
2037        };
2038        self.text_select(mode)
2039    }
2040
2041    /// Registers a hyperlink click handler.
2042    ///
2043    /// # Arguments
2044    ///
2045    /// - `Self` - Source paragraph.
2046    /// - `CallbackFn` - Callback invoked with clicked link URL.
2047    ///
2048    /// # Returns
2049    ///
2050    /// - `Self` - Updated paragraph.
2051    #[must_use]
2052    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
2053    where
2054        CallbackFn: Fn(&str) + 'static,
2055    {
2056        self.set_on_link(Some(Rc::new(handler)));
2057        self
2058    }
2059
2060    /// Sets the optional relative asset base prefix used when resolving local inline image URLs.
2061    ///
2062    /// # Arguments
2063    ///
2064    /// - `Self` - Source paragraph.
2065    /// - `TextValue` - Relative asset base prefix (for example `"./"` or `"../"`).
2066    ///
2067    /// # Returns
2068    ///
2069    /// - `Self` - Updated paragraph.
2070    #[must_use]
2071    pub fn asset_base<TextValue>(mut self, base: TextValue) -> Self
2072    where
2073        TextValue: Into<String>,
2074    {
2075        self.set_asset_base(base.into());
2076        self
2077    }
2078
2079    /// Computes proportional display dimensions for a decoded image constrained to `(max_w, max_h)`.
2080    ///
2081    /// # Arguments
2082    ///
2083    /// - `u32` - Decoded image width in pixels.
2084    /// - `u32` - Decoded image height in pixels.
2085    /// - `f32` - Maximum logical display width.
2086    /// - `f32` - Maximum logical display height.
2087    ///
2088    /// # Returns
2089    ///
2090    /// - `(f32, f32)` - Aspect-preserving logical `(width, height)`.
2091    #[must_use]
2092    pub(crate) fn fit_image_dims(img_w: u32, img_h: u32, max_w: f32, max_h: f32) -> (f32, f32) {
2093        let width_val: f32 = (img_w.max(1)) as f32;
2094        let height_val: f32 = (img_h.max(1)) as f32;
2095        let scale_w: f32 = if width_val > max_w {
2096            max_w / width_val
2097        } else {
2098            1.0
2099        };
2100        let scale_h: f32 = if height_val > max_h {
2101            max_h / height_val
2102        } else {
2103            1.0
2104        };
2105        let scale: f32 = scale_w.min(scale_h);
2106        ((width_val * scale).max(1.0), (height_val * scale).max(1.0))
2107    }
2108
2109    /// Returns `true` when `url` points to a known badge image host or badge SVG endpoint.
2110    ///
2111    /// # Arguments
2112    ///
2113    /// - `&str` - Raw or resolved Markdown image URL.
2114    ///
2115    /// # Returns
2116    ///
2117    /// - `bool` - Whether the URL matches a badge provider pattern.
2118    #[must_use]
2119    pub(crate) fn is_badge_image_url(url: &str) -> bool {
2120        let lower: String = url.to_ascii_lowercase();
2121        MD_BADGE_HOST_PATTERNS
2122            .iter()
2123            .any(|pat: &&str| lower.contains(pat))
2124    }
2125
2126    /// Computes uniform fixed-height (`MD_BADGE_HEIGHT`) aspect-preserving dimensions for inline badges, or standard constrained inline dimensions for non-badge inline images.
2127    ///
2128    /// # Arguments
2129    ///
2130    /// - `u32` - Decoded image natural width in pixels.
2131    /// - `u32` - Decoded image natural height in pixels.
2132    /// - `&str` - Resolved image URL.
2133    /// - `bool` - Whether the surrounding inline context explicitly marks this image as a badge.
2134    ///
2135    /// # Returns
2136    ///
2137    /// - `(f32, f32)` - Logical `(width, height)` preserving badge height parity.
2138    #[must_use]
2139    pub(crate) fn fit_inline_image_dims(
2140        img_w: u32,
2141        img_h: u32,
2142        url: &str,
2143        force_badge: bool,
2144    ) -> (f32, f32) {
2145        let is_badge: bool = force_badge
2146            || Self::is_badge_image_url(url)
2147            || (img_h <= MD_BADGE_MAX_NATURAL_HEIGHT && img_w >= img_h);
2148        if is_badge {
2149            let nat_w: f32 = img_w.max(1) as f32;
2150            let nat_h: f32 = img_h.max(1) as f32;
2151            let width: f32 =
2152                (MD_BADGE_HEIGHT * (nat_w / nat_h)).clamp(MD_BADGE_MIN_WIDTH, MD_BADGE_MAX_WIDTH);
2153            return (width, MD_BADGE_HEIGHT);
2154        }
2155        Self::fit_image_dims(
2156            img_w,
2157            img_h,
2158            MD_IMAGE_MAX_DISPLAY_WIDTH,
2159            MD_IMAGE_INLINE_MAX_HEIGHT,
2160        )
2161    }
2162
2163    /// Mounts a decoded or asynchronously loaded inline image node into `tree`.
2164    ///
2165    /// # Arguments
2166    ///
2167    /// - `&mut SceneTree` - Mutable scene tree.
2168    /// - `&str` - Accessible alt caption.
2169    /// - `&str` - Raw Markdown image URI.
2170    /// - `&str` - Relative asset base prefix.
2171    /// - `(ThemeTokens, CodeThemePalette)` - Active theme tokens and Eva palette.
2172    /// - `bool` - Whether clicking the rendered image opens the interactive lightbox preview portal.
2173    /// - `bool` - Whether this inline image belongs to a badge context requiring fixed `MD_BADGE_HEIGHT`.
2174    ///
2175    /// # Returns
2176    ///
2177    /// - `NodeId` - Mounted inline image host container handle.
2178    fn mount_inline_image_in_tree(
2179        tree: &mut SceneTree,
2180        alt: &str,
2181        raw_url: &str,
2182        asset_base: &str,
2183        theme: (ThemeTokens, CodeThemePalette),
2184        enable_lightbox: bool,
2185        force_badge: bool,
2186    ) -> NodeId {
2187        let (tokens, eva): (ThemeTokens, CodeThemePalette) = theme;
2188        let palette: ThemePalette = tokens.get_palette();
2189        let geometry: ThemeGeometry = tokens.get_geometry();
2190        let ctx: Context = current_context();
2191        let resolved: String = resolve_markdown_asset_url(raw_url, asset_base);
2192        let is_badge_hint: bool = force_badge || Self::is_badge_image_url(&resolved);
2193        let mut host_st: Style = Style::default();
2194        host_st
2195            .get_mut_layout()
2196            .set_flex_direction(FlexDirection::Row)
2197            .set_flex_shrink(0.0)
2198            .set_max_width(Length::Percent(100.0))
2199            .set_align_items(AlignItems::Center)
2200            .set_overflow(Overflow::Hidden);
2201        if is_badge_hint {
2202            host_st
2203                .get_mut_layout()
2204                .set_height(Length::Px(MD_BADGE_HEIGHT));
2205        }
2206        let host_id: NodeId = tree.create_view(host_st);
2207        let lb_portal_opt: Option<NodeId> = if enable_lightbox {
2208            Some(create_image_lightbox_portal(tree))
2209        } else {
2210            None
2211        };
2212        if let Some(buf) = cached_network_image(&resolved) {
2213            let (dw, dh): (f32, f32) = Self::fit_inline_image_dims(
2214                buf.get_width(),
2215                buf.get_height(),
2216                &resolved,
2217                is_badge_hint,
2218            );
2219            let mut img_st: Style = Style::default();
2220            img_st
2221                .get_mut_layout()
2222                .set_width(Length::Px(dw))
2223                .set_height(Length::Px(dh))
2224                .set_flex_shrink(0.0)
2225                .set_max_width(Length::Percent(100.0));
2226            img_st
2227                .get_mut_paint()
2228                .set_radius(CornerRadius::all(geometry.get_radius_sm()));
2229            let buf_slot: Rc<RefCell<Option<ImageBuffer>>> =
2230                Rc::new(RefCell::new(Some(buf.clone())));
2231            let img_node: NodeId = tree.create_image(buf, img_st);
2232            if !alt.is_empty()
2233                && let Some(node) = tree.get_node_mut(img_node)
2234            {
2235                *node.get_mut_a11y() = Some(A11yProps::new(A11yRole::Image, alt.to_string()));
2236            }
2237            if let Some(lb_portal) = lb_portal_opt {
2238                attach_image_lightbox_trigger(
2239                    tree,
2240                    ctx,
2241                    img_node,
2242                    lb_portal,
2243                    buf_slot,
2244                    (alt.to_string(), tokens),
2245                );
2246                tree.append_children(host_id, &[img_node, lb_portal]);
2247            } else {
2248                tree.append_child(host_id, img_node);
2249            }
2250            return host_id;
2251        }
2252        let fallback_label: String = if alt.is_empty() {
2253            MD_IMAGE_LOADING_LABEL.to_string()
2254        } else {
2255            alt.to_string()
2256        };
2257        let mut chip_st: Style = Style::default();
2258        chip_st
2259            .get_mut_layout()
2260            .set_flex_direction(FlexDirection::Row)
2261            .set_flex_shrink(0.0)
2262            .set_max_width(Length::Percent(100.0))
2263            .set_padding(if is_badge_hint {
2264                Edges::symmetric(0.0, 6.0)
2265            } else {
2266                Edges::symmetric(2.0, 6.0)
2267            })
2268            .set_align_items(AlignItems::Center)
2269            .set_overflow(Overflow::Hidden);
2270        if is_badge_hint {
2271            chip_st
2272                .get_mut_layout()
2273                .set_height(Length::Px(MD_BADGE_HEIGHT));
2274        }
2275        chip_st
2276            .get_mut_paint()
2277            .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2278            .set_background(Some(eva.get_header_bg()))
2279            .set_border(Border::new(1.0, eva.get_border()));
2280        let mut cap_st: Style = Style::default();
2281        cap_st
2282            .get_mut_layout()
2283            .set_max_width(Length::Percent(100.0));
2284        cap_st
2285            .get_mut_text()
2286            .set_font_size(if is_badge_hint { 11.0 } else { 12.0 })
2287            .set_color(palette.get_muted_foreground());
2288        let chip_id: NodeId = tree.create_view(chip_st);
2289        let cap_id: NodeId = tree.create_text(fallback_label, cap_st);
2290        tree.append_child(chip_id, cap_id);
2291        if let Some(lb_portal) = lb_portal_opt {
2292            tree.append_children(host_id, &[chip_id, lb_portal]);
2293        } else {
2294            tree.append_child(host_id, chip_id);
2295        }
2296        let scene: SceneHandle = ctx.get_scene().clone();
2297        let alt_owned: String = alt.to_string();
2298        let resolved_cb: String = resolved.clone();
2299        let radius_sm: f32 = geometry.get_radius_sm();
2300        let ctx_cb: Context = ctx;
2301        request_network_image(
2302            &resolved,
2303            Rc::new(move |loaded: Option<ImageBuffer>| {
2304                if let Some(buf) = loaded {
2305                    let (dw, dh): (f32, f32) = Self::fit_inline_image_dims(
2306                        buf.get_width(),
2307                        buf.get_height(),
2308                        &resolved_cb,
2309                        is_badge_hint,
2310                    );
2311                    let alt_c: String = alt_owned.clone();
2312                    let ctx_inner: Context = ctx_cb.clone();
2313                    scene.with_write(
2314                        |scene_tree: &mut SceneTree| {
2315                            if scene_tree.get_node(host_id).is_none() {
2316                                return;
2317                            }
2318                            let mut img_st: Style = Style::default();
2319                            img_st
2320                                .get_mut_layout()
2321                                .set_width(Length::Px(dw))
2322                                .set_height(Length::Px(dh))
2323                                .set_flex_shrink(0.0)
2324                                .set_max_width(Length::Percent(100.0));
2325                            img_st
2326                                .get_mut_paint()
2327                                .set_radius(CornerRadius::all(radius_sm));
2328                            let buf_slot: Rc<RefCell<Option<ImageBuffer>>> =
2329                                Rc::new(RefCell::new(Some(buf.clone())));
2330                            let img_node: NodeId = scene_tree.create_image(buf, img_st);
2331                            if !alt_c.is_empty()
2332                                && let Some(node) = scene_tree.get_node_mut(img_node)
2333                            {
2334                                *node.get_mut_a11y() =
2335                                    Some(A11yProps::new(A11yRole::Image, alt_c.clone()));
2336                            }
2337                            if let Some(lb_portal) = lb_portal_opt
2338                                && scene_tree.get_node(lb_portal).is_some()
2339                            {
2340                                attach_image_lightbox_trigger(
2341                                    scene_tree,
2342                                    ctx_inner,
2343                                    img_node,
2344                                    lb_portal,
2345                                    buf_slot,
2346                                    (alt_c, tokens),
2347                                );
2348                                scene_tree.replace_children(host_id, vec![img_node, lb_portal]);
2349                            } else {
2350                                scene_tree.replace_children(host_id, vec![img_node]);
2351                            }
2352                            notify_frame_needed();
2353                        },
2354                        (),
2355                    );
2356                }
2357            }),
2358        );
2359        host_id
2360    }
2361
2362    /// Mounts a plain body text paragraph node directly into an already-borrowed `SceneTree`.
2363    ///
2364    /// # Arguments
2365    ///
2366    /// - `&mut SceneTree` - Mutable scene tree.
2367    /// - `&str` - Plain body text slice.
2368    /// - `ThemePalette` - Resolved active theme palette.
2369    /// - `Option<TextSelectMode>` - Optional explicit text selection mode.
2370    ///
2371    /// # Returns
2372    ///
2373    /// - `NodeId` - Mounted body text node handle.
2374    #[inline(always)]
2375    pub(crate) fn mount_plain_in_tree(
2376        tree: &mut SceneTree,
2377        text: &str,
2378        palette: ThemePalette,
2379        text_select: Option<TextSelectMode>,
2380    ) -> NodeId {
2381        let mut computed_style: Style = Style::default();
2382        if let Some(mode) = text_select {
2383            computed_style = computed_style.text_select(mode);
2384        }
2385        computed_style
2386            .get_mut_layout()
2387            .set_width(Length::Percent(100.0));
2388        computed_style
2389            .get_mut_text()
2390            .set_font_size(14.0)
2391            .set_color(palette.get_foreground());
2392        tree.create_text(text.to_string(), computed_style)
2393    }
2394
2395    /// Mounts a plain body text paragraph node directly without allocating an inline AST.
2396    ///
2397    /// # Arguments
2398    ///
2399    /// - `&str` - Plain body text slice.
2400    /// - `ThemePalette` - Resolved active theme palette.
2401    /// - `Option<TextSelectMode>` - Optional explicit text selection mode.
2402    ///
2403    /// # Returns
2404    ///
2405    /// - `NodeId` - Mounted body text node handle.
2406    #[inline(always)]
2407    pub(crate) fn mount_plain_text(
2408        text: &str,
2409        palette: ThemePalette,
2410        text_select: Option<TextSelectMode>,
2411    ) -> NodeId {
2412        let ctx: Context = current_context();
2413        ctx.get_scene().with_write(
2414            |tree: &mut SceneTree| Self::mount_plain_in_tree(tree, text, palette, text_select),
2415            NodeId::default(),
2416        )
2417    }
2418
2419    /// Mounts a single parsed `EuvMarkdownInline` segment directly into an already-borrowed `SceneTree`.
2420    ///
2421    /// # Arguments
2422    ///
2423    /// - `&mut SceneTree` - Mutable scene tree.
2424    /// - `&EuvMarkdownInline` - Borrowed inline segment.
2425    /// - `(ThemeTokens, CodeThemePalette, (Color, Color))` - Active theme tokens, Eva palette, and highlight `(bg, fg)` colors.
2426    /// - `Option<TextSelectMode>` - Optional explicit text selection mode.
2427    /// - `&str` - Relative asset base prefix for resolving local image URIs.
2428    /// - `Option<&MarkdownStrCallback>` - Optional link-click handler.
2429    ///
2430    /// # Returns
2431    ///
2432    /// - `NodeId` - Mounted inline node handle.
2433    fn render_inline_in_tree(
2434        tree: &mut SceneTree,
2435        seg: &EuvMarkdownInline,
2436        theme: (ThemeTokens, CodeThemePalette, (Color, Color)),
2437        text_select: Option<TextSelectMode>,
2438        asset_base: &str,
2439        on_link: Option<&MarkdownStrCallback>,
2440    ) -> NodeId {
2441        let (tokens, eva, hl_colors): (ThemeTokens, CodeThemePalette, (Color, Color)) = theme;
2442        let palette: ThemePalette = tokens.get_palette();
2443        let geometry: ThemeGeometry = tokens.get_geometry();
2444        let (hl_bg, hl_fg): (Color, Color) = hl_colors;
2445        let base_sel_st: Style = match text_select {
2446            Some(mode) => style! {
2447                mode
2448            },
2449            None => Style::default(),
2450        };
2451        match seg {
2452            EuvMarkdownInline::Text(blend_factor) => {
2453                let mut computed_style: Style = base_sel_st;
2454                computed_style
2455                    .get_mut_layout()
2456                    .set_max_width(Length::Percent(100.0));
2457                computed_style
2458                    .get_mut_text()
2459                    .set_font_size(14.0)
2460                    .set_overflow(inline_word_overflow(blend_factor.as_str()))
2461                    .set_color(palette.get_foreground());
2462                tree.create_text(blend_factor.clone(), computed_style)
2463            }
2464            EuvMarkdownInline::Bold(time_step) => {
2465                let mut element_style: Style = base_sel_st;
2466                element_style
2467                    .get_mut_layout()
2468                    .set_max_width(Length::Percent(100.0));
2469                element_style
2470                    .get_mut_text()
2471                    .set_font_size(14.0)
2472                    .set_weight(FontWeight::Bold)
2473                    .set_overflow(inline_word_overflow(time_step.as_str()))
2474                    .set_color(palette.get_foreground());
2475                tree.create_text(time_step.clone(), element_style)
2476            }
2477            EuvMarkdownInline::Italic(token_val) => {
2478                let mut resolved_style: Style = base_sel_st;
2479                resolved_style
2480                    .get_mut_layout()
2481                    .set_max_width(Length::Percent(100.0));
2482                resolved_style
2483                    .get_mut_text()
2484                    .set_font_size(14.0)
2485                    .set_italic(true)
2486                    .set_overflow(inline_word_overflow(token_val.as_str()))
2487                    .set_color(palette.get_foreground());
2488                tree.create_text(token_val.clone(), resolved_style)
2489            }
2490            EuvMarkdownInline::BoldItalic(target_val) => {
2491                let mut node_style: Style = base_sel_st;
2492                node_style
2493                    .get_mut_layout()
2494                    .set_max_width(Length::Percent(100.0));
2495                node_style
2496                    .get_mut_text()
2497                    .set_font_size(14.0)
2498                    .set_weight(FontWeight::Bold)
2499                    .set_italic(true)
2500                    .set_overflow(inline_word_overflow(target_val.as_str()))
2501                    .set_color(palette.get_foreground());
2502                tree.create_text(target_val.clone(), node_style)
2503            }
2504            EuvMarkdownInline::Strike(blend_factor_primary) => {
2505                let mut active_style: Style = base_sel_st;
2506                active_style
2507                    .get_mut_layout()
2508                    .set_max_width(Length::Percent(100.0));
2509                active_style
2510                    .get_mut_text()
2511                    .set_font_size(14.0)
2512                    .set_overflow(inline_word_overflow(blend_factor_primary.as_str()))
2513                    .set_color(palette.get_muted_foreground())
2514                    .set_strikethrough(true);
2515                tree.create_text(blend_factor_primary.clone(), active_style)
2516            }
2517            EuvMarkdownInline::Highlight(blend_factor_secondary) => {
2518                let mut row_st: Style = Style::default();
2519                row_st
2520                    .get_mut_layout()
2521                    .set_flex_direction(FlexDirection::Row)
2522                    .set_align_self(AlignSelf::Start)
2523                    .set_justify_content(JustifyContent::Center)
2524                    .set_align_items(AlignItems::Center)
2525                    .set_max_width(Length::Percent(100.0))
2526                    .set_padding(Edges::symmetric(1.0, SPACE_XS))
2527                    .set_overflow(Overflow::Hidden);
2528                row_st
2529                    .get_mut_paint()
2530                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2531                    .set_background(Some(hl_bg));
2532                let mut txt_st: Style = base_sel_st;
2533                txt_st
2534                    .get_mut_layout()
2535                    .set_max_width(Length::Percent(100.0));
2536                txt_st
2537                    .get_mut_text()
2538                    .set_font_size(13.5)
2539                    .set_weight(FontWeight::Medium)
2540                    .set_align(TextAlign::Center)
2541                    .set_overflow(inline_word_overflow(blend_factor_secondary.as_str()))
2542                    .set_color(hl_fg);
2543                let row_id: NodeId = tree.create_view(row_st);
2544                let txt_id: NodeId = tree.create_text(blend_factor_secondary.clone(), txt_st);
2545                tree.append_child(row_id, txt_id);
2546                row_id
2547            }
2548            EuvMarkdownInline::Superscript(blend_factor_next) => {
2549                let mut row_st: Style = Style::default();
2550                row_st
2551                    .get_mut_layout()
2552                    .set_flex_direction(FlexDirection::Row)
2553                    .set_padding(Edges::new(0.0, 1.0, 6.0, 1.0));
2554                let mut txt_st: Style = base_sel_st;
2555                txt_st
2556                    .get_mut_text()
2557                    .set_font_size(10.5)
2558                    .set_weight(FontWeight::SemiBold)
2559                    .set_color(palette.get_foreground());
2560                let row_id: NodeId = tree.create_view(row_st);
2561                let txt_id: NodeId = tree.create_text(blend_factor_next.clone(), txt_st);
2562                tree.append_child(row_id, txt_id);
2563                row_id
2564            }
2565            EuvMarkdownInline::Subscript(blend_factor_alt) => {
2566                let mut row_st: Style = Style::default();
2567                row_st
2568                    .get_mut_layout()
2569                    .set_flex_direction(FlexDirection::Row)
2570                    .set_padding(Edges::new(6.0, 1.0, 0.0, 1.0));
2571                let mut txt_st: Style = base_sel_st;
2572                txt_st
2573                    .get_mut_text()
2574                    .set_font_size(10.5)
2575                    .set_weight(FontWeight::SemiBold)
2576                    .set_color(palette.get_foreground());
2577                let row_id: NodeId = tree.create_view(row_st);
2578                let txt_id: NodeId = tree.create_text(blend_factor_alt.clone(), txt_st);
2579                tree.append_child(row_id, txt_id);
2580                row_id
2581            }
2582            EuvMarkdownInline::Code(code) => {
2583                EuvMarkdownInlineCode::mount_in_tree(tree, code.as_str(), tokens, eva)
2584            }
2585            EuvMarkdownInline::Math(expr) => {
2586                let mut row_st: Style = Style::default();
2587                row_st
2588                    .get_mut_layout()
2589                    .set_flex_direction(FlexDirection::Row)
2590                    .set_align_self(AlignSelf::Start)
2591                    .set_justify_content(JustifyContent::Center)
2592                    .set_align_items(AlignItems::Center)
2593                    .set_max_width(Length::Percent(100.0))
2594                    .set_padding(Edges::symmetric(1.0, SPACE_XS))
2595                    .set_overflow(Overflow::Hidden);
2596                row_st
2597                    .get_mut_paint()
2598                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2599                    .set_background(Some(eva.get_inline_code_bg()))
2600                    .set_border(Border::new(1.0, eva.get_border()));
2601                let mut txt_st: Style = base_sel_st;
2602                txt_st
2603                    .get_mut_layout()
2604                    .set_max_width(Length::Percent(100.0));
2605                txt_st
2606                    .get_mut_text()
2607                    .set_font_size(13.0)
2608                    .set_family(FontFamily::Monospace)
2609                    .set_align(TextAlign::Center)
2610                    .set_overflow(inline_word_overflow(expr.as_str()))
2611                    .set_color(eva.get_keyword());
2612                let row_id: NodeId = tree.create_view(row_st);
2613                let txt_id: NodeId = tree.create_text(expr.clone(), txt_st);
2614                tree.append_child(row_id, txt_id);
2615                row_id
2616            }
2617            EuvMarkdownInline::FootnoteRef(id) => {
2618                let fn_bg: Color = palette.get_primary().with_alpha(28);
2619                let fn_fg: Color = palette.readable_foreground_with(
2620                    palette.get_primary(),
2621                    blend_over(fn_bg, palette.get_background()),
2622                );
2623                let mut row_st: Style = Style::default();
2624                row_st
2625                    .get_mut_layout()
2626                    .set_flex_direction(FlexDirection::Row)
2627                    .set_align_self(AlignSelf::Start)
2628                    .set_justify_content(JustifyContent::Center)
2629                    .set_align_items(AlignItems::Center)
2630                    .set_padding(Edges::symmetric(1.0, SPACE_XS))
2631                    .set_margin(Edges::new(0.0, 2.0, SPACE_XS, 2.0))
2632                    .set_overflow(Overflow::Hidden);
2633                row_st
2634                    .get_mut_paint()
2635                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2636                    .set_background(Some(fn_bg));
2637                let mut txt_st: Style = Style::default();
2638                txt_st
2639                    .get_mut_text()
2640                    .set_font_size(10.0)
2641                    .set_weight(FontWeight::Bold)
2642                    .set_align(TextAlign::Center)
2643                    .set_overflow(TextOverflow::Clip)
2644                    .set_color(fn_fg);
2645                let row_id: NodeId = tree.create_view(row_st);
2646                let txt_id: NodeId = tree.create_text(format!("[{id}]"), txt_st);
2647                tree.append_child(row_id, txt_id);
2648                row_id
2649            }
2650            EuvMarkdownInline::Image { alt, url } => Self::mount_inline_image_in_tree(
2651                tree,
2652                alt.as_str(),
2653                url.as_str(),
2654                asset_base,
2655                (tokens, eva),
2656                true,
2657                false,
2658            ),
2659            EuvMarkdownInline::LinkedImage {
2660                alt,
2661                image_url,
2662                link_url,
2663            } => {
2664                let cb_opt: Option<MarkdownStrCallback> = on_link.cloned();
2665                let url_owned: String = link_url.clone();
2666                let click_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
2667                    if let Some(callback_fn) = cb_opt.as_ref() {
2668                        callback_fn(&url_owned);
2669                    } else {
2670                        let _: bool = open_external_url(&url_owned);
2671                    }
2672                }));
2673                let mut row_st: Style = Style::default();
2674                row_st
2675                    .get_mut_layout()
2676                    .set_flex_direction(FlexDirection::Row)
2677                    .set_flex_shrink(0.0)
2678                    .set_max_width(Length::Percent(100.0))
2679                    .set_padding(Edges::all(SPACE_XS))
2680                    .set_align_items(AlignItems::Center)
2681                    .set_overflow(Overflow::Hidden);
2682                row_st
2683                    .get_mut_paint()
2684                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2685                    .set_cursor(CursorIcon::Pointer);
2686                let row_id: NodeId = tree.create_view(row_st);
2687                if let Some(node) = tree.get_node_mut(row_id) {
2688                    node.get_mut_handlers().set_on_click(Some(click_handler));
2689                    node.get_mut_interaction().set_focusable(true);
2690                    if !alt.is_empty() {
2691                        *node.get_mut_a11y() = Some(A11yProps::new(A11yRole::Link, alt.clone()));
2692                    }
2693                }
2694                let img_host: NodeId = Self::mount_inline_image_in_tree(
2695                    tree,
2696                    alt.as_str(),
2697                    image_url.as_str(),
2698                    asset_base,
2699                    (tokens, eva),
2700                    false,
2701                    true,
2702                );
2703                tree.append_child(row_id, img_host);
2704                row_id
2705            }
2706            EuvMarkdownInline::Kbd(key) => {
2707                let mut row_st: Style = Style::default();
2708                row_st
2709                    .get_mut_layout()
2710                    .set_flex_direction(FlexDirection::Row)
2711                    .set_align_self(AlignSelf::Start)
2712                    .set_justify_content(JustifyContent::Center)
2713                    .set_align_items(AlignItems::Center)
2714                    .set_padding(Edges::symmetric(2.0, 6.0))
2715                    .set_overflow(Overflow::Hidden);
2716                row_st
2717                    .get_mut_paint()
2718                    .set_background(Some(palette.get_muted()))
2719                    .set_border(Border::new(
2720                        geometry.get_border_width().max(0.0),
2721                        palette.get_border(),
2722                    ))
2723                    .set_radius(CornerRadius::all(geometry.get_radius_sm()));
2724                let mut txt_st: Style = Style::default();
2725                txt_st
2726                    .get_mut_text()
2727                    .set_family(FontFamily::Monospace)
2728                    .set_font_size(11.0)
2729                    .set_color(palette.get_foreground())
2730                    .set_align(TextAlign::Center)
2731                    .set_overflow(TextOverflow::Clip);
2732                let row_id: NodeId = tree.create_view(row_st);
2733                let txt_id: NodeId = tree.create_text(key.clone(), txt_st);
2734                tree.append_child(row_id, txt_id);
2735                row_id
2736            }
2737            EuvMarkdownInline::Link { label, url } => {
2738                let cb_opt: Option<MarkdownStrCallback> = on_link.cloned();
2739                let url_owned: String = url.clone();
2740                let click_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
2741                    if let Some(handler_cb) = cb_opt.as_ref() {
2742                        handler_cb(&url_owned);
2743                    } else {
2744                        let _: bool = open_external_url(&url_owned);
2745                    }
2746                }));
2747                let mut row_st: Style = Style::default();
2748                row_st
2749                    .get_mut_layout()
2750                    .set_flex_direction(FlexDirection::Row)
2751                    .set_align_self(AlignSelf::Start)
2752                    .set_flex_wrap(FlexWrap::Wrap)
2753                    .set_align_items(AlignItems::Center)
2754                    .set_max_width(Length::Percent(100.0))
2755                    .set_padding(Edges::symmetric(2.0, SPACE_XS))
2756                    .set_overflow(Overflow::Hidden);
2757                row_st
2758                    .get_mut_paint()
2759                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
2760                    .set_cursor(CursorIcon::Pointer);
2761                let mut hover_paint: PaintStyle = row_st.get_paint();
2762                let _: &mut PaintStyle = hover_paint
2763                    .set_background(Some(eva.get_link().with_alpha(MD_LINK_HOVER_ALPHA)));
2764                let mut link_st: Style = base_sel_st;
2765                link_st
2766                    .get_mut_layout()
2767                    .set_max_width(Length::Percent(100.0));
2768                link_st
2769                    .get_mut_text()
2770                    .set_font_size(14.0)
2771                    .set_weight(FontWeight::SemiBold)
2772                    .set_overflow(inline_word_overflow(label.as_str()))
2773                    .set_color(eva.get_link())
2774                    .set_underline(true);
2775                let row_id: NodeId = tree.create_view(row_st);
2776                if let Some(node) = tree.get_node_mut(row_id) {
2777                    node.get_mut_handlers().set_on_click(Some(click_handler));
2778                    node.get_mut_interaction().set_focusable(true);
2779                    let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
2780                    let link_a11y_label: String = if label.trim().is_empty() {
2781                        url.clone()
2782                    } else {
2783                        label.clone()
2784                    };
2785                    *node.get_mut_a11y() = Some(A11yProps::new(A11yRole::Link, link_a11y_label));
2786                }
2787                if has_inline_markdown_trigger(label.as_str()) {
2788                    let raw_subs: Vec<EuvMarkdownInline> = parse_markdown_inlines(label.as_str());
2789                    let sub_spans: Vec<EuvMarkdownInline> = expand_inline_words_for_wrap(&raw_subs);
2790                    let mut kids: Vec<NodeId> = Vec::with_capacity(sub_spans.len());
2791                    for sub in sub_spans.into_iter() {
2792                        let kid: NodeId = match sub {
2793                            EuvMarkdownInline::Code(code) => {
2794                                let mut chip_st: Style = Style::default();
2795                                chip_st
2796                                    .get_mut_layout()
2797                                    .set_flex_direction(FlexDirection::Row)
2798                                    .set_align_items(AlignItems::Center)
2799                                    .set_max_width(Length::Percent(100.0))
2800                                    .set_padding(Edges::symmetric(1.0, 5.0))
2801                                    .set_overflow(Overflow::Hidden);
2802                                chip_st
2803                                    .get_mut_paint()
2804                                    .set_background(Some(eva.get_inline_code_bg()))
2805                                    .set_border(Border::new(1.0, eva.get_border()))
2806                                    .set_radius(CornerRadius::all(geometry.get_radius_sm()));
2807                                let mut c_st: Style = base_sel_st;
2808                                c_st.get_mut_text()
2809                                    .set_font_size(12.5)
2810                                    .set_family(FontFamily::Monospace)
2811                                    .set_weight(FontWeight::SemiBold)
2812                                    .set_color(eva.get_link())
2813                                    .set_underline(true);
2814                                let chip_id: NodeId = tree.create_view(chip_st);
2815                                let c_id: NodeId = tree.create_text(code, c_st);
2816                                tree.append_child(chip_id, c_id);
2817                                chip_id
2818                            }
2819                            EuvMarkdownInline::Bold(source_val) => {
2820                                let mut b_st: Style = link_st;
2821                                b_st.get_mut_text()
2822                                    .set_weight(FontWeight::Bold)
2823                                    .set_overflow(inline_word_overflow(source_val.as_str()));
2824                                tree.create_text(source_val, b_st)
2825                            }
2826                            EuvMarkdownInline::Italic(scale_val) => {
2827                                let mut i_st: Style = link_st;
2828                                i_st.get_mut_text()
2829                                    .set_italic(true)
2830                                    .set_overflow(inline_word_overflow(scale_val.as_str()));
2831                                tree.create_text(scale_val, i_st)
2832                            }
2833                            EuvMarkdownInline::BoldItalic(series_item) => {
2834                                let mut bi_st: Style = link_st;
2835                                bi_st
2836                                    .get_mut_text()
2837                                    .set_weight(FontWeight::Bold)
2838                                    .set_italic(true)
2839                                    .set_overflow(inline_word_overflow(series_item.as_str()));
2840                                tree.create_text(series_item, bi_st)
2841                            }
2842                            EuvMarkdownInline::Strike(text_slice) => {
2843                                let mut s_st: Style = link_st;
2844                                s_st.get_mut_text()
2845                                    .set_strikethrough(true)
2846                                    .set_overflow(inline_word_overflow(text_slice.as_str()));
2847                                tree.create_text(text_slice, s_st)
2848                            }
2849                            EuvMarkdownInline::Text(source_val_primary)
2850                            | EuvMarkdownInline::Highlight(source_val_primary)
2851                            | EuvMarkdownInline::Superscript(source_val_primary)
2852                            | EuvMarkdownInline::Subscript(source_val_primary)
2853                            | EuvMarkdownInline::Math(source_val_primary)
2854                            | EuvMarkdownInline::Kbd(source_val_primary) => {
2855                                let mut t_st: Style = link_st;
2856                                t_st.get_mut_text().set_overflow(inline_word_overflow(
2857                                    source_val_primary.as_str(),
2858                                ));
2859                                tree.create_text(source_val_primary, t_st)
2860                            }
2861                            EuvMarkdownInline::Image { alt, url: img_u } => {
2862                                Self::mount_inline_image_in_tree(
2863                                    tree,
2864                                    alt.as_str(),
2865                                    img_u.as_str(),
2866                                    asset_base,
2867                                    (tokens, eva),
2868                                    false,
2869                                    true,
2870                                )
2871                            }
2872                            _ => continue,
2873                        };
2874                        kids.push(kid);
2875                    }
2876                    if kids.is_empty() {
2877                        let txt_id: NodeId = tree.create_text(label.clone(), link_st);
2878                        tree.append_child(row_id, txt_id);
2879                    } else {
2880                        tree.append_children(row_id, &kids);
2881                    }
2882                } else {
2883                    let txt_id: NodeId = tree.create_text(label.clone(), link_st);
2884                    tree.append_child(row_id, txt_id);
2885                }
2886                row_id
2887            }
2888            EuvMarkdownInline::HardBreak => {
2889                let mut state_val: Style = Style::default();
2890                state_val
2891                    .get_mut_layout()
2892                    .set_width(Length::Px(0.0))
2893                    .set_height(Length::Px(0.0));
2894                tree.create_view(state_val)
2895            }
2896        }
2897    }
2898
2899    /// Mounts a plain-text Markdown hyperlink as one or more wrap-friendly segments sharing a unified whole-link hover state, flush interior joins, and outer-only padding and corner radii.
2900    ///
2901    /// # Arguments
2902    ///
2903    /// - `&mut SceneTree` - Mutable scene tree.
2904    /// - `&str` - Full link display label.
2905    /// - `&str` - Link destination URL.
2906    /// - `(ThemeTokens, CodeThemePalette)` - Active theme and Eva syntax palette.
2907    /// - `Option<TextSelectMode>` - Optional inherited text selection mode.
2908    /// - `Option<&MarkdownStrCallback>` - Optional link activation callback.
2909    /// - `&mut Vec<NodeId>` - Output vector receiving all mounted segment nodes.
2910    fn mount_plain_link_segments_in_tree(
2911        tree: &mut SceneTree,
2912        label: &str,
2913        url: &str,
2914        style_ctx: (ThemeTokens, CodeThemePalette),
2915        text_select: Option<TextSelectMode>,
2916        on_link: Option<&MarkdownStrCallback>,
2917        out: &mut Vec<NodeId>,
2918    ) {
2919        let (tokens, eva): (ThemeTokens, CodeThemePalette) = style_ctx;
2920        let geometry: ThemeGeometry = tokens.get_geometry();
2921        let radius_px: f32 = geometry.get_radius_sm();
2922        let mut pieces: Vec<String> = split_inline_wrap_pieces(label);
2923        if pieces.is_empty() {
2924            pieces.push(label.to_string());
2925        }
2926        let cb_opt: Option<MarkdownStrCallback> = on_link.cloned();
2927        let url_owned: String = url.to_string();
2928        let click_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
2929            if let Some(handler_cb) = cb_opt.as_ref() {
2930                handler_cb(&url_owned);
2931            } else {
2932                let _: bool = open_external_url(&url_owned);
2933            }
2934        }));
2935        let base_sel_st: Style = match text_select {
2936            Some(mode) => style! {
2937                mode
2938            },
2939            None => Style::default(),
2940        };
2941        let link_a11y_label: String = if label.trim().is_empty() {
2942            url.to_string()
2943        } else {
2944            label.to_string()
2945        };
2946        let hover_bg: Color = eva.get_link().with_alpha(MD_LINK_HOVER_ALPHA);
2947        let piece_count: usize = pieces.len();
2948        let mut group_ids: Vec<NodeId> = Vec::with_capacity(piece_count);
2949        for (idx, piece) in pieces.into_iter().enumerate() {
2950            let is_first: bool = idx == 0;
2951            let is_last: bool = idx + 1 == piece_count;
2952            let pad_left: f32 = if is_first { SPACE_XS } else { 0.0 };
2953            let pad_right: f32 = if is_last { SPACE_XS } else { 0.0 };
2954            let seg_radius: CornerRadius = match (is_first, is_last) {
2955                (true, true) => CornerRadius::all(radius_px),
2956                (true, false) => CornerRadius::new(radius_px, 0.0, 0.0, radius_px),
2957                (false, true) => CornerRadius::new(0.0, radius_px, radius_px, 0.0),
2958                (false, false) => CornerRadius::all(0.0),
2959            };
2960            let mut row_st: Style = Style::default();
2961            row_st
2962                .get_mut_layout()
2963                .set_flex_direction(FlexDirection::Row)
2964                .set_align_self(AlignSelf::Start)
2965                .set_align_items(AlignItems::Center)
2966                .set_max_width(Length::Percent(100.0))
2967                .set_padding(Edges::new(2.0, pad_right, 2.0, pad_left))
2968                .set_overflow(Overflow::Hidden);
2969            row_st
2970                .get_mut_paint()
2971                .set_radius(seg_radius)
2972                .set_cursor(CursorIcon::Pointer);
2973            let mut hover_paint: PaintStyle = row_st.get_paint();
2974            let _: &mut PaintStyle = hover_paint.set_background(Some(hover_bg));
2975            let mut link_st: Style = base_sel_st;
2976            link_st
2977                .get_mut_layout()
2978                .set_max_width(Length::Percent(100.0));
2979            link_st
2980                .get_mut_text()
2981                .set_font_size(14.0)
2982                .set_weight(FontWeight::SemiBold)
2983                .set_overflow(inline_word_overflow(piece.as_str()))
2984                .set_color(eva.get_link())
2985                .set_underline(true);
2986            let seg_id: NodeId = tree.create_view(row_st);
2987            if let Some(node) = tree.get_node_mut(seg_id) {
2988                node.get_mut_handlers()
2989                    .set_on_click(Some(Rc::clone(&click_handler)));
2990                node.get_mut_interaction().set_focusable(true);
2991                let _: &mut SceneNode = node.set_hover_style(Some(hover_paint));
2992                *node.get_mut_a11y() =
2993                    Some(A11yProps::new(A11yRole::Link, link_a11y_label.clone()));
2994            }
2995            let txt_id: NodeId = tree.create_text(piece, link_st);
2996            tree.append_child(seg_id, txt_id);
2997            group_ids.push(seg_id);
2998        }
2999        if group_ids.len() > 1 {
3000            let scene_handle: SceneHandle = current_context().get_scene().clone();
3001            let shared_ids: Rc<Vec<NodeId>> = Rc::new(group_ids.clone());
3002            let hover_count: Rc<Cell<u32>> = Rc::new(Cell::new(0));
3003            for &seg_id in shared_ids.iter() {
3004                let ids_enter: Rc<Vec<NodeId>> = Rc::clone(&shared_ids);
3005                let cnt_enter: Rc<Cell<u32>> = Rc::clone(&hover_count);
3006                let scene_enter: SceneHandle = scene_handle.clone();
3007                let enter_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
3008                    let next_cnt: u32 = cnt_enter.get().saturating_add(1);
3009                    cnt_enter.set(next_cnt);
3010                    let live_tok: ThemeTokens = live_tokens_untracked(tokens);
3011                    let live_eva: CodeThemePalette = CodeThemePalette::resolve(live_tok.get_mode());
3012                    let live_bg: Color = live_eva.get_link().with_alpha(MD_LINK_HOVER_ALPHA);
3013                    scene_enter.with_write(
3014                        |scene_tree: &mut SceneTree| {
3015                            for &member_id in ids_enter.iter() {
3016                                if let Some(member) = scene_tree.get_node_mut(member_id) {
3017                                    let _: &mut PaintStyle = member
3018                                        .get_mut_style()
3019                                        .get_mut_paint()
3020                                        .set_background(Some(live_bg));
3021                                    let mut next_hover_p: PaintStyle =
3022                                        member.style_ref().get_paint();
3023                                    let _: &mut PaintStyle =
3024                                        next_hover_p.set_background(Some(live_bg));
3025                                    let _: &mut SceneNode =
3026                                        member.set_hover_style(Some(next_hover_p));
3027                                    scene_tree.mark_dirty(member_id, DIRTY_PAINT);
3028                                }
3029                            }
3030                        },
3031                        (),
3032                    );
3033                }));
3034                let ids_leave: Rc<Vec<NodeId>> = Rc::clone(&shared_ids);
3035                let cnt_leave: Rc<Cell<u32>> = Rc::clone(&hover_count);
3036                let scene_leave: SceneHandle = scene_handle.clone();
3037                let leave_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
3038                    let next_cnt: u32 = cnt_leave.get().saturating_sub(1);
3039                    cnt_leave.set(next_cnt);
3040                    if next_cnt == 0 {
3041                        scene_leave.with_write(
3042                            |scene_tree: &mut SceneTree| {
3043                                for &member_id in ids_leave.iter() {
3044                                    if let Some(member) = scene_tree.get_node_mut(member_id) {
3045                                        let _: &mut PaintStyle = member
3046                                            .get_mut_style()
3047                                            .get_mut_paint()
3048                                            .set_background(None);
3049                                        scene_tree.mark_dirty(member_id, DIRTY_PAINT);
3050                                    }
3051                                }
3052                            },
3053                            (),
3054                        );
3055                    }
3056                }));
3057                if let Some(node) = tree.get_node_mut(seg_id) {
3058                    node.get_mut_handlers()
3059                        .set_on_pointer_enter(Some(enter_handler))
3060                        .set_on_pointer_leave(Some(leave_handler));
3061                }
3062            }
3063        }
3064        out.extend(group_ids);
3065    }
3066
3067    /// Mounts a long Markdown inline highlight (`> MD_HIGHLIGHT_SINGLE_SPAN_MAX_CHARS`) as flush continuous wrap segments so wrapped lines never leave an empty trailing rectangle.
3068    ///
3069    /// # Arguments
3070    ///
3071    /// - `&mut SceneTree` - Mutable scene tree.
3072    /// - `&str` - Highlighted text slice.
3073    /// - `(ThemeTokens, (Color, Color))` - Active theme tokens and resolved `(bg, fg)` highlight colors.
3074    /// - `Option<TextSelectMode>` - Optional inherited text selection mode.
3075    /// - `&mut Vec<NodeId>` - Output vector receiving mounted highlight segment nodes.
3076    fn mount_long_highlight_segments_in_tree(
3077        tree: &mut SceneTree,
3078        text_val: &str,
3079        style_ctx: (ThemeTokens, (Color, Color)),
3080        text_select: Option<TextSelectMode>,
3081        out: &mut Vec<NodeId>,
3082    ) {
3083        let (tokens, (hl_bg, hl_fg)): (ThemeTokens, (Color, Color)) = style_ctx;
3084        let radius_px: f32 = tokens.get_geometry().get_radius_sm();
3085        let mut pieces: Vec<String> = split_inline_wrap_pieces(text_val);
3086        if pieces.is_empty() {
3087            pieces.push(text_val.to_string());
3088        }
3089        let base_sel_st: Style = match text_select {
3090            Some(mode) => style! {
3091                mode
3092            },
3093            None => Style::default(),
3094        };
3095        let piece_count: usize = pieces.len();
3096        for (idx, piece) in pieces.into_iter().enumerate() {
3097            let is_first: bool = idx == 0;
3098            let is_last: bool = idx + 1 == piece_count;
3099            let pad_left: f32 = if is_first { SPACE_XS } else { 0.0 };
3100            let pad_right: f32 = if is_last { SPACE_XS } else { 0.0 };
3101            let seg_radius: CornerRadius = match (is_first, is_last) {
3102                (true, true) => CornerRadius::all(radius_px),
3103                (true, false) => CornerRadius::new(radius_px, 0.0, 0.0, radius_px),
3104                (false, true) => CornerRadius::new(0.0, radius_px, radius_px, 0.0),
3105                (false, false) => CornerRadius::all(0.0),
3106            };
3107            let mut row_st: Style = Style::default();
3108            row_st
3109                .get_mut_layout()
3110                .set_flex_direction(FlexDirection::Row)
3111                .set_align_self(AlignSelf::Start)
3112                .set_align_items(AlignItems::Center)
3113                .set_max_width(Length::Percent(100.0))
3114                .set_padding(Edges::new(1.0, pad_right, 1.0, pad_left))
3115                .set_overflow(Overflow::Hidden);
3116            row_st
3117                .get_mut_paint()
3118                .set_radius(seg_radius)
3119                .set_background(Some(hl_bg));
3120            let mut txt_st: Style = base_sel_st;
3121            txt_st
3122                .get_mut_layout()
3123                .set_max_width(Length::Percent(100.0));
3124            txt_st
3125                .get_mut_text()
3126                .set_font_size(13.5)
3127                .set_weight(FontWeight::Medium)
3128                .set_overflow(inline_word_overflow(piece.as_str()))
3129                .set_color(hl_fg);
3130            let seg_id: NodeId = tree.create_view(row_st);
3131            let txt_id: NodeId = tree.create_text(piece, txt_st);
3132            tree.append_child(seg_id, txt_id);
3133            out.push(seg_id);
3134        }
3135    }
3136
3137    /// Mounts one inline Markdown segment (or unified multi-segment link/highlight group) directly into `out`.
3138    ///
3139    /// # Arguments
3140    ///
3141    /// - `&mut SceneTree` - Mutable scene tree.
3142    /// - `&EuvMarkdownInline` - Parsed inline segment.
3143    /// - `(ThemeTokens, CodeThemePalette, (Color, Color))` - Active theme, Eva palette, and highlight `(bg, fg)`.
3144    /// - `Option<TextSelectMode>` - Optional inherited text selection mode.
3145    /// - `&str` - Asset base path for inline images.
3146    /// - `Option<&MarkdownStrCallback>` - Optional link activation callback.
3147    /// - `&mut Vec<NodeId>` - Output vector receiving mounted scene node handles.
3148    fn push_inline_nodes_in_tree(
3149        tree: &mut SceneTree,
3150        seg: &EuvMarkdownInline,
3151        style_ctx: (ThemeTokens, CodeThemePalette, (Color, Color)),
3152        text_select: Option<TextSelectMode>,
3153        asset_base: &str,
3154        on_link: Option<&MarkdownStrCallback>,
3155        out: &mut Vec<NodeId>,
3156    ) {
3157        let (tokens, eva, hl_colors): (ThemeTokens, CodeThemePalette, (Color, Color)) = style_ctx;
3158        match seg {
3159            EuvMarkdownInline::Link { label, url }
3160                if !has_inline_markdown_trigger(label.as_str()) =>
3161            {
3162                Self::mount_plain_link_segments_in_tree(
3163                    tree,
3164                    label.as_str(),
3165                    url.as_str(),
3166                    (tokens, eva),
3167                    text_select,
3168                    on_link,
3169                    out,
3170                );
3171            }
3172            EuvMarkdownInline::Highlight(text_val)
3173                if text_val.chars().count() > MD_HIGHLIGHT_SINGLE_SPAN_MAX_CHARS =>
3174            {
3175                Self::mount_long_highlight_segments_in_tree(
3176                    tree,
3177                    text_val.as_str(),
3178                    (tokens, hl_colors),
3179                    text_select,
3180                    out,
3181                );
3182            }
3183            other => {
3184                out.push(Self::render_inline_in_tree(
3185                    tree,
3186                    other,
3187                    style_ctx,
3188                    text_select,
3189                    asset_base,
3190                    on_link,
3191                ));
3192            }
3193        }
3194    }
3195
3196    /// Mounts this paragraph directly into an already-borrowed `SceneTree`.
3197    ///
3198    /// # Arguments
3199    ///
3200    /// - `&Self` - Paragraph component reference.
3201    /// - `&mut SceneTree` - Mutable scene tree.
3202    ///
3203    /// # Returns
3204    ///
3205    /// - `NodeId` - Mounted paragraph handle.
3206    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree) -> NodeId {
3207        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
3208        let palette: ThemePalette = tokens.get_palette();
3209        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
3210        let Self {
3211            inlines,
3212            text_select,
3213            asset_base,
3214            on_link,
3215            ..
3216        } = self;
3217        let para_select: Option<TextSelectMode> = *text_select;
3218        let para_asset_base: &str = asset_base.as_str();
3219        if inlines.len() == 1
3220            && let EuvMarkdownInline::Text(plain) = &inlines[0]
3221        {
3222            return Self::mount_plain_in_tree(tree, plain.as_str(), palette, para_select);
3223        }
3224        let has_rich: bool = inlines
3225            .iter()
3226            .any(|seg: &EuvMarkdownInline| !matches!(seg, EuvMarkdownInline::Text(_)));
3227        if !has_rich {
3228            let total_len: usize = inlines
3229                .iter()
3230                .map(|seg: &EuvMarkdownInline| match seg {
3231                    EuvMarkdownInline::Text(source_val) => source_val.len(),
3232                    _ => 0,
3233                })
3234                .sum();
3235            let mut plain: String = String::with_capacity(total_len);
3236            for seg in inlines {
3237                if let EuvMarkdownInline::Text(scale_val) = seg {
3238                    plain.push_str(scale_val);
3239                }
3240            }
3241            return Self::mount_plain_in_tree(tree, &plain, palette, para_select);
3242        }
3243        let hl_colors: (Color, Color) = match tokens.get_mode() {
3244            ThemeMode::Light => (
3245                Color::hex(MD_HIGHLIGHT_LIGHT_BG),
3246                Color::hex(MD_HIGHLIGHT_LIGHT_FG),
3247            ),
3248            ThemeMode::Dark => (
3249                Color::hex(MD_HIGHLIGHT_DARK_BG),
3250                Color::hex(MD_HIGHLIGHT_DARK_FG),
3251            ),
3252        };
3253        let on_link_ref: Option<&MarkdownStrCallback> = on_link.as_ref();
3254        let is_badge_row: bool = inlines.iter().any(|seg: &EuvMarkdownInline| {
3255            matches!(
3256                seg,
3257                EuvMarkdownInline::LinkedImage { .. } | EuvMarkdownInline::Image { .. }
3258            )
3259        }) && inlines.iter().all(|seg: &EuvMarkdownInline| match seg {
3260            EuvMarkdownInline::LinkedImage { .. }
3261            | EuvMarkdownInline::Image { .. }
3262            | EuvMarkdownInline::HardBreak => true,
3263            EuvMarkdownInline::Text(series_item) => series_item.trim().is_empty(),
3264            _ => false,
3265        });
3266        let mut wrap_row_st: Style = match para_select {
3267            Some(mode) => style! {
3268                mode
3269            },
3270            None => Style::default(),
3271        };
3272        wrap_row_st
3273            .get_mut_layout()
3274            .set_flex_direction(FlexDirection::Row)
3275            .set_width(Length::Percent(100.0))
3276            .set_min_width(Length::Px(0.0))
3277            .set_flex_wrap(FlexWrap::Wrap)
3278            .set_align_items(AlignItems::Center)
3279            .set_overflow(Overflow::Hidden)
3280            .set_row_gap(if is_badge_row { MD_BADGE_ROW_GAP } else { 4.0 })
3281            .set_column_gap(if is_badge_row { MD_BADGE_ROW_GAP } else { 0.0 });
3282        let has_hard_break: bool = inlines
3283            .iter()
3284            .any(|seg: &EuvMarkdownInline| matches!(seg, EuvMarkdownInline::HardBreak));
3285        if !has_hard_break {
3286            let expanded_buf: Vec<EuvMarkdownInline>;
3287            let iter_slice: &[EuvMarkdownInline] = if is_badge_row {
3288                inlines.as_slice()
3289            } else {
3290                expanded_buf = expand_inline_words_for_wrap(inlines);
3291                expanded_buf.as_slice()
3292            };
3293            let mut nodes: Vec<NodeId> = Vec::with_capacity(iter_slice.len());
3294            for seg in iter_slice {
3295                Self::push_inline_nodes_in_tree(
3296                    tree,
3297                    seg,
3298                    (tokens, eva, hl_colors),
3299                    para_select,
3300                    para_asset_base,
3301                    on_link_ref,
3302                    &mut nodes,
3303                );
3304            }
3305            let row_id: NodeId = tree.create_view(wrap_row_st);
3306            if !nodes.is_empty() {
3307                tree.append_children(row_id, &nodes);
3308            }
3309            return row_id;
3310        }
3311        let mut line_rows: Vec<NodeId> = Vec::new();
3312        let mut line_nodes: Vec<NodeId> = Vec::new();
3313        for line_segs in
3314            inlines.split(|seg: &EuvMarkdownInline| matches!(seg, EuvMarkdownInline::HardBreak))
3315        {
3316            let expanded_line: Vec<EuvMarkdownInline>;
3317            let seg_slice: &[EuvMarkdownInline] = if is_badge_row {
3318                line_segs
3319            } else {
3320                expanded_line = expand_inline_words_for_wrap(line_segs);
3321                expanded_line.as_slice()
3322            };
3323            line_nodes.clear();
3324            line_nodes.reserve(seg_slice.len());
3325            for seg in seg_slice {
3326                Self::push_inline_nodes_in_tree(
3327                    tree,
3328                    seg,
3329                    (tokens, eva, hl_colors),
3330                    para_select,
3331                    para_asset_base,
3332                    on_link_ref,
3333                    &mut line_nodes,
3334                );
3335            }
3336            let row_id: NodeId = tree.create_view(wrap_row_st);
3337            if !line_nodes.is_empty() {
3338                tree.append_children(row_id, &line_nodes);
3339            }
3340            line_rows.push(row_id);
3341        }
3342        if line_rows.len() == 1 {
3343            return line_rows.remove(0);
3344        }
3345        let mut col_st: Style = match para_select {
3346            Some(mode) => style! {
3347                mode
3348            },
3349            None => Style::default(),
3350        };
3351        col_st
3352            .get_mut_layout()
3353            .set_flex_direction(FlexDirection::Column)
3354            .set_width(Length::Percent(100.0))
3355            .set_row_gap(4.0)
3356            .set_column_gap(4.0);
3357        let col_id: NodeId = tree.create_view(col_st);
3358        if !line_rows.is_empty() {
3359            tree.append_children(col_id, &line_rows);
3360        }
3361        col_id
3362    }
3363}
3364
3365/// Declarative `#[component]` implementation for `EuvMarkdownParagraph`.
3366#[component]
3367/// Inherent implementation of [`EuvMarkdownParagraph`].
3368impl EuvMarkdownParagraph {
3369    /// Renders rich inline Markdown spans (bold, italic, bold-italic, strike, highlight, sup/sub, inline code, math, footnotes, images, links, hard breaks, `<kbd>`).
3370    ///
3371    /// # Arguments
3372    ///
3373    /// - `&Self` - Paragraph component reference.
3374    ///
3375    /// # Returns
3376    ///
3377    /// - `NodeId` - Mounted paragraph container handle.
3378    fn render(&self) -> NodeId {
3379        let ctx: Context = current_context();
3380        ctx.get_scene().with_write(
3381            |tree: &mut SceneTree| self.mount_in_tree(tree),
3382            NodeId::default(),
3383        )
3384    }
3385}
3386
3387/// Fluent builder helpers for `EuvMarkdownQuote`.
3388impl EuvMarkdownQuote {
3389    /// Sets the interactive text selection and copy mode for the quote (`TextSelectMode::None` by default).
3390    ///
3391    /// # Arguments
3392    ///
3393    /// - `Self` - Source quote.
3394    /// - `TextSelectMode` - Selection mode applied to the quote subtree.
3395    ///
3396    /// # Returns
3397    ///
3398    /// - `Self` - Updated quote.
3399    #[must_use]
3400    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
3401        self.set_text_select(Some(mode));
3402        self
3403    }
3404
3405    /// Controls whether quote text is selectable.
3406    ///
3407    /// # Arguments
3408    ///
3409    /// - `Self` - Source quote.
3410    /// - `bool` - Whether selection is enabled.
3411    ///
3412    /// # Returns
3413    ///
3414    /// - `Self` - Updated quote.
3415    #[must_use]
3416    pub fn selectable(self, enabled: bool) -> Self {
3417        let mode: TextSelectMode = if enabled {
3418            TextSelectMode::SelectAndCopy
3419        } else {
3420            TextSelectMode::None
3421        };
3422        self.text_select(mode)
3423    }
3424
3425    /// Registers a link-click handler for hyperlinks inside the quote.
3426    ///
3427    /// # Arguments
3428    ///
3429    /// - `Self` - Source quote.
3430    /// - `CallbackFn` - Callback invoked with clicked link URL.
3431    ///
3432    /// # Returns
3433    ///
3434    /// - `Self` - Updated quote.
3435    #[must_use]
3436    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
3437    where
3438        CallbackFn: Fn(&str) + 'static,
3439    {
3440        self.set_on_link(Some(Rc::new(handler)));
3441        self
3442    }
3443    /// Mounts this quote or GitHub Alert callout directly into an already-borrowed `SceneTree`.
3444    ///
3445    /// # Arguments
3446    ///
3447    /// - `&Self` - Quote component reference.
3448    /// - `&mut SceneTree` - Mutable scene tree.
3449    ///
3450    /// # Returns
3451    ///
3452    /// - `NodeId` - Mounted callout node handle.
3453    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree) -> NodeId {
3454        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
3455        let palette: ThemePalette = tokens.get_palette();
3456        let geometry: ThemeGeometry = tokens.get_geometry();
3457        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
3458        let kind: EuvMarkdownAlertKind = self.get_kind();
3459        let Self {
3460            lines,
3461            text_select,
3462            on_link,
3463            ..
3464        } = self;
3465        let quote_select: Option<TextSelectMode> = *text_select;
3466        let (accent, badge_opt): (Color, Option<&str>) = match kind {
3467            EuvMarkdownAlertKind::Quote => (eva.get_quote_border(), None),
3468            EuvMarkdownAlertKind::Note => (eva.get_link(), Some(MD_ALERT_LABEL_NOTE)),
3469            EuvMarkdownAlertKind::Tip => (eva.get_diff_add(), Some(MD_ALERT_LABEL_TIP)),
3470            EuvMarkdownAlertKind::Important => (eva.get_keyword(), Some(MD_ALERT_LABEL_IMPORTANT)),
3471            EuvMarkdownAlertKind::Warning => (palette.get_warning(), Some(MD_ALERT_LABEL_WARNING)),
3472            EuvMarkdownAlertKind::Caution => (eva.get_diff_del(), Some(MD_ALERT_LABEL_CAUTION)),
3473        };
3474        let bg: Color = if kind == EuvMarkdownAlertKind::Quote {
3475            eva.get_quote_bg()
3476        } else {
3477            accent.with_alpha(26)
3478        };
3479        let badge_fg: Color =
3480            palette.readable_foreground_with(accent, blend_over(bg, palette.get_background()));
3481        let mut body_nodes: Vec<NodeId> = Vec::with_capacity(lines.len() + 1);
3482        if let Some(tag) = badge_opt {
3483            let mut tag_row_st: Style = Style::default();
3484            tag_row_st
3485                .get_mut_layout()
3486                .set_flex_direction(FlexDirection::Row)
3487                .set_align_items(AlignItems::Center)
3488                .set_row_gap(SPACE_SM)
3489                .set_column_gap(SPACE_SM);
3490            let mut dot_st: Style = Style::default();
3491            dot_st
3492                .get_mut_layout()
3493                .set_width(Length::Px(7.0))
3494                .set_height(Length::Px(7.0))
3495                .set_flex_shrink(0.0);
3496            dot_st
3497                .get_mut_paint()
3498                .set_radius(CornerRadius::all(RADIUS_PILL))
3499                .set_background(Some(accent));
3500            let mut tag_txt_st: Style = Style::default();
3501            tag_txt_st
3502                .get_mut_text()
3503                .set_font_size(11.5)
3504                .set_weight(FontWeight::Bold)
3505                .set_color(badge_fg);
3506            let tag_row: NodeId = tree.create_view(tag_row_st);
3507            let dot_id: NodeId = tree.create_view(dot_st);
3508            let tag_txt: NodeId = tree.create_text(tag.to_string(), tag_txt_st);
3509            tree.append_children(tag_row, &[dot_id, tag_txt]);
3510            body_nodes.push(tag_row);
3511        }
3512        let mut nested_buf: Vec<String> = Vec::new();
3513        for line in lines {
3514            if let Some(after_gt) = line.trim_start().strip_prefix('>') {
3515                nested_buf.push(after_gt.trim_start().to_string());
3516            } else {
3517                if !nested_buf.is_empty() {
3518                    let inner_lines: Vec<String> = take(&mut nested_buf);
3519                    let (inner_kind, clean_inner): (EuvMarkdownAlertKind, Vec<String>) =
3520                        classify_quote_alert(inner_lines);
3521                    let mut nested: EuvMarkdownQuote =
3522                        EuvMarkdownQuote::new(inner_kind, clean_inner, tokens);
3523                    if let Some(mode) = quote_select {
3524                        nested = nested.text_select(mode);
3525                    }
3526                    if let Some(callback_fn) = on_link.clone() {
3527                        nested.set_on_link(Some(callback_fn));
3528                    }
3529                    body_nodes.push(nested.mount_in_tree(tree));
3530                }
3531                if !line.trim().is_empty() {
3532                    if !has_inline_markdown_trigger(line) {
3533                        body_nodes.push(EuvMarkdownParagraph::mount_plain_in_tree(
3534                            tree,
3535                            line,
3536                            palette,
3537                            quote_select,
3538                        ));
3539                    } else {
3540                        let mut para: EuvMarkdownParagraph =
3541                            EuvMarkdownParagraph::new(parse_markdown_inlines(line), tokens)
3542                                .asset_base(self.get_asset_base().as_str());
3543                        if let Some(mode) = quote_select {
3544                            para = para.text_select(mode);
3545                        }
3546                        if let Some(handler_cb) = on_link.clone() {
3547                            para.set_on_link(Some(handler_cb));
3548                        }
3549                        body_nodes.push(para.mount_in_tree(tree));
3550                    }
3551                }
3552            }
3553        }
3554        if !nested_buf.is_empty() {
3555            let inner_lines: Vec<String> = take(&mut nested_buf);
3556            let (inner_kind, clean_inner): (EuvMarkdownAlertKind, Vec<String>) =
3557                classify_quote_alert(inner_lines);
3558            let mut nested: EuvMarkdownQuote =
3559                EuvMarkdownQuote::new(inner_kind, clean_inner, tokens);
3560            if let Some(mode) = quote_select {
3561                nested = nested.text_select(mode);
3562            }
3563            if let Some(callback_fn_primary) = on_link.clone() {
3564                nested.set_on_link(Some(callback_fn_primary));
3565            }
3566            body_nodes.push(nested.mount_in_tree(tree));
3567        }
3568        let card_radius: f32 = geometry.get_radius_md().max(0.0);
3569        let bar_inset_v: f32 = (card_radius - 1.0).max(SPACE_XS);
3570        let mut root_st: Style = match quote_select {
3571            Some(mode) => style! {
3572                mode
3573            },
3574            None => Style::default(),
3575        };
3576        root_st
3577            .get_mut_layout()
3578            .set_flex_direction(FlexDirection::Row)
3579            .set_width(Length::Percent(100.0))
3580            .set_overflow(Overflow::Hidden);
3581        root_st
3582            .get_mut_paint()
3583            .set_background(Some(bg))
3584            .set_border(Border::new(1.0, accent.with_alpha(96)))
3585            .set_radius(CornerRadius::all(card_radius));
3586        let mut bar_st: Style = Style::default();
3587        bar_st
3588            .get_mut_layout()
3589            .set_width(Length::Px(4.0))
3590            .set_flex_shrink(0.0)
3591            .set_margin(Edges::new(bar_inset_v, 0.0, bar_inset_v, SPACE_XS));
3592        bar_st
3593            .get_mut_paint()
3594            .set_background(Some(accent))
3595            .set_radius(CornerRadius::all(RADIUS_PILL));
3596        let mut col_st: Style = Style::default();
3597        col_st
3598            .get_mut_layout()
3599            .set_flex_direction(FlexDirection::Column)
3600            .set_flex_grow(1.0)
3601            .set_flex_shrink(1.0)
3602            .set_min_width(Length::Px(0.0))
3603            .set_padding(Edges::new(SPACE_SM, SPACE_MD, SPACE_SM, SPACE_SM))
3604            .set_row_gap(SPACE_SM)
3605            .set_column_gap(SPACE_SM)
3606            .set_overflow(Overflow::Hidden);
3607        let root: NodeId = tree.create_view(root_st);
3608        let bar_id: NodeId = tree.create_view(bar_st);
3609        let col_id: NodeId = tree.create_view(col_st);
3610        if !body_nodes.is_empty() {
3611            tree.append_children(col_id, &body_nodes);
3612        }
3613        tree.append_children(root, &[bar_id, col_id]);
3614        root
3615    }
3616}
3617
3618/// Declarative `#[component]` implementation for `EuvMarkdownQuote`.
3619#[component]
3620/// Inherent implementation of [`EuvMarkdownQuote`].
3621impl EuvMarkdownQuote {
3622    /// Renders a Markdown blockquote (including nested `> >` quotes) or GitHub/container Alert callout card with full recursive child block support (`EuvCodeBlock`, lists, tables, images, and nested callouts).
3623    ///
3624    /// # Arguments
3625    ///
3626    /// - `&Self` - Quote component reference.
3627    ///
3628    /// # Returns
3629    ///
3630    /// - `NodeId` - Mounted callout node handle.
3631    fn render(&self) -> NodeId {
3632        let ctx: Context = current_context();
3633        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
3634        let palette: ThemePalette = tokens.get_palette();
3635        let geometry: ThemeGeometry = tokens.get_geometry();
3636        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
3637        let kind: EuvMarkdownAlertKind = self.get_kind();
3638        let Self {
3639            title,
3640            lines,
3641            children,
3642            code_block_size_mode,
3643            text_select,
3644            asset_base,
3645            on_link,
3646            on_copy,
3647            on_toggle_task,
3648            ..
3649        } = self;
3650        let resolved_children: Vec<EuvMarkdownBlock> = if !children.is_empty() {
3651            children.clone()
3652        } else if lines.iter().any(|text_value: &String| {
3653            let lt: &str = text_value.trim_start();
3654            lt.starts_with("```")
3655                || lt.starts_with("~~~")
3656                || lt.starts_with(MD_CALLOUT_FENCE)
3657                || lt.starts_with(MD_DETAILS_OPEN_TAG)
3658                || lt.starts_with("![")
3659        }) {
3660            parse_markdown_blocks(&lines.join("\n"))
3661        } else {
3662            Vec::new()
3663        };
3664        if resolved_children.is_empty() && title.is_none() {
3665            return ctx.get_scene().with_write(
3666                |tree: &mut SceneTree| self.mount_in_tree(tree),
3667                NodeId::default(),
3668            );
3669        }
3670        let quote_select: Option<TextSelectMode> = *text_select;
3671        let mounted_children: Vec<NodeId> = EuvMarkdown::mount_block_list(
3672            resolved_children,
3673            tokens,
3674            (quote_select, *code_block_size_mode, asset_base.as_str()),
3675            (on_link.as_ref(), on_copy.as_ref(), on_toggle_task.as_ref()),
3676        );
3677        let (accent, default_tag): (Color, Option<&str>) = match kind {
3678            EuvMarkdownAlertKind::Quote => (eva.get_quote_border(), None),
3679            EuvMarkdownAlertKind::Note => (eva.get_link(), Some(MD_ALERT_LABEL_NOTE)),
3680            EuvMarkdownAlertKind::Tip => (eva.get_diff_add(), Some(MD_ALERT_LABEL_TIP)),
3681            EuvMarkdownAlertKind::Important => (eva.get_keyword(), Some(MD_ALERT_LABEL_IMPORTANT)),
3682            EuvMarkdownAlertKind::Warning => (palette.get_warning(), Some(MD_ALERT_LABEL_WARNING)),
3683            EuvMarkdownAlertKind::Caution => (eva.get_diff_del(), Some(MD_ALERT_LABEL_CAUTION)),
3684        };
3685        let bg: Color = if kind == EuvMarkdownAlertKind::Quote {
3686            eva.get_quote_bg()
3687        } else {
3688            accent.with_alpha(26)
3689        };
3690        let badge_fg: Color =
3691            palette.readable_foreground_with(accent, blend_over(bg, palette.get_background()));
3692        let custom_title_opt: Option<&str> = title.as_deref();
3693        let asset_base_str: &str = asset_base.as_str();
3694        ctx.get_scene().with_write(
3695            |tree: &mut SceneTree| {
3696                let mut body_nodes: Vec<NodeId> = Vec::with_capacity(mounted_children.len() + 1);
3697                if let Some(hdr_title) = custom_title_opt.or(default_tag) {
3698                    let mut tag_row_st: Style = Style::default();
3699                    tag_row_st
3700                        .get_mut_layout()
3701                        .set_flex_direction(FlexDirection::Row)
3702                        .set_align_items(AlignItems::Center)
3703                        .set_width(Length::Percent(100.0))
3704                        .set_row_gap(SPACE_SM)
3705                        .set_column_gap(SPACE_SM);
3706                    let mut dot_st: Style = Style::default();
3707                    dot_st
3708                        .get_mut_layout()
3709                        .set_width(Length::Px(7.0))
3710                        .set_height(Length::Px(7.0))
3711                        .set_flex_shrink(0.0);
3712                    dot_st
3713                        .get_mut_paint()
3714                        .set_radius(CornerRadius::all(RADIUS_PILL))
3715                        .set_background(Some(accent));
3716                    let tag_row: NodeId = tree.create_view(tag_row_st);
3717                    let dot_id: NodeId = tree.create_view(dot_st);
3718                    let hdr_node: NodeId = if has_inline_markdown_trigger(hdr_title) {
3719                        let mut title_para: EuvMarkdownParagraph =
3720                            EuvMarkdownParagraph::new(parse_markdown_inlines(hdr_title), tokens)
3721                                .asset_base(asset_base_str);
3722                        if let Some(mode) = quote_select {
3723                            title_para = title_para.text_select(mode);
3724                        }
3725                        if let Some(callback_fn) = on_link.clone() {
3726                            title_para.set_on_link(Some(callback_fn));
3727                        }
3728                        title_para.mount_in_tree(tree)
3729                    } else {
3730                        let mut tag_txt_st: Style = Style::default();
3731                        tag_txt_st
3732                            .get_mut_text()
3733                            .set_font_size(if custom_title_opt.is_some() {
3734                                13.0
3735                            } else {
3736                                11.5
3737                            })
3738                            .set_weight(FontWeight::Bold)
3739                            .set_color(badge_fg);
3740                        tree.create_text(hdr_title.to_string(), tag_txt_st)
3741                    };
3742                    tree.append_children(tag_row, &[dot_id, hdr_node]);
3743                    body_nodes.push(tag_row);
3744                }
3745                body_nodes.extend(mounted_children.iter().copied());
3746                let card_radius: f32 = geometry.get_radius_md().max(0.0);
3747                let bar_inset_v: f32 = (card_radius - 1.0).max(SPACE_XS);
3748                let mut root_st: Style = match quote_select {
3749                    Some(mode) => style! {
3750                        mode
3751                    },
3752                    None => Style::default(),
3753                };
3754                root_st
3755                    .get_mut_layout()
3756                    .set_flex_direction(FlexDirection::Row)
3757                    .set_width(Length::Percent(100.0))
3758                    .set_overflow(Overflow::Hidden);
3759                root_st
3760                    .get_mut_paint()
3761                    .set_background(Some(bg))
3762                    .set_border(Border::new(1.0, accent.with_alpha(96)))
3763                    .set_radius(CornerRadius::all(card_radius));
3764                let mut bar_st: Style = Style::default();
3765                bar_st
3766                    .get_mut_layout()
3767                    .set_width(Length::Px(4.0))
3768                    .set_flex_shrink(0.0)
3769                    .set_margin(Edges::new(bar_inset_v, 0.0, bar_inset_v, SPACE_XS));
3770                bar_st
3771                    .get_mut_paint()
3772                    .set_background(Some(accent))
3773                    .set_radius(CornerRadius::all(RADIUS_PILL));
3774                let mut col_st: Style = Style::default();
3775                col_st
3776                    .get_mut_layout()
3777                    .set_flex_direction(FlexDirection::Column)
3778                    .set_flex_grow(1.0)
3779                    .set_flex_shrink(1.0)
3780                    .set_min_width(Length::Px(0.0))
3781                    .set_padding(Edges::new(SPACE_SM, SPACE_MD, SPACE_SM, SPACE_SM))
3782                    .set_row_gap(SPACE_SM)
3783                    .set_column_gap(SPACE_SM)
3784                    .set_overflow(Overflow::Hidden);
3785                let root: NodeId = tree.create_view(root_st);
3786                let bar_id: NodeId = tree.create_view(bar_st);
3787                let col_id: NodeId = tree.create_view(col_st);
3788                if !body_nodes.is_empty() {
3789                    tree.append_children(col_id, &body_nodes);
3790                }
3791                tree.append_children(root, &[bar_id, col_id]);
3792                root
3793            },
3794            NodeId::default(),
3795        )
3796    }
3797}
3798
3799/// Fluent builder helpers for `EuvMarkdownList`.
3800impl EuvMarkdownList {
3801    /// Sets the starting ordinal index for ordered lists.
3802    ///
3803    /// # Arguments
3804    ///
3805    /// - `Self` - Source list.
3806    /// - `usize` - Starting number (defaults to `1` when `0`).
3807    ///
3808    /// # Returns
3809    ///
3810    /// - `Self` - Updated list.
3811    #[must_use]
3812    pub fn start(mut self, start: usize) -> Self {
3813        self.set_start(start);
3814        self
3815    }
3816
3817    /// Sets the interactive text selection and copy mode for list items (`TextSelectMode::None` by default).
3818    ///
3819    /// # Arguments
3820    ///
3821    /// - `Self` - Source list.
3822    /// - `TextSelectMode` - Selection mode applied to list item text.
3823    ///
3824    /// # Returns
3825    ///
3826    /// - `Self` - Updated list.
3827    #[must_use]
3828    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
3829        self.set_text_select(Some(mode));
3830        self
3831    }
3832
3833    /// Controls whether list item text is selectable.
3834    ///
3835    /// # Arguments
3836    ///
3837    /// - `Self` - Source list.
3838    /// - `bool` - Whether selection is enabled.
3839    ///
3840    /// # Returns
3841    ///
3842    /// - `Self` - Updated list.
3843    #[must_use]
3844    pub fn selectable(self, enabled: bool) -> Self {
3845        let mode: TextSelectMode = if enabled {
3846            TextSelectMode::SelectAndCopy
3847        } else {
3848            TextSelectMode::None
3849        };
3850        self.text_select(mode)
3851    }
3852
3853    /// Registers a link-click handler for hyperlinks inside list items.
3854    ///
3855    /// # Arguments
3856    ///
3857    /// - `Self` - Source list.
3858    /// - `CallbackFn` - Callback invoked with clicked URL.
3859    ///
3860    /// # Returns
3861    ///
3862    /// - `Self` - Updated list.
3863    #[must_use]
3864    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
3865    where
3866        CallbackFn: Fn(&str) + 'static,
3867    {
3868        self.set_on_link(Some(Rc::new(handler)));
3869        self
3870    }
3871
3872    /// Registers an interactive task-checkbox toggle handler.
3873    ///
3874    /// # Arguments
3875    ///
3876    /// - `Self` - Source list.
3877    /// - `CallbackFn` - Callback receiving `(item_index, next_checked)`.
3878    ///
3879    /// # Returns
3880    ///
3881    /// - `Self` - Updated list.
3882    #[must_use]
3883    pub fn on_toggle_task<CallbackFn>(mut self, handler: CallbackFn) -> Self
3884    where
3885        CallbackFn: Fn(usize, bool) + 'static,
3886    {
3887        self.set_on_toggle_task(Some(Rc::new(handler)));
3888        self
3889    }
3890    /// Mounts this list directly into an already-borrowed `SceneTree` with zero per-checkbox signals or effects.
3891    ///
3892    /// # Arguments
3893    ///
3894    /// - `&Self` - List component reference.
3895    /// - `&mut SceneTree` - Mutable scene tree.
3896    /// - `&SceneHandle` - Shared scene handle captured by task-checkbox toggle handlers.
3897    ///
3898    /// # Returns
3899    ///
3900    /// - `NodeId` - Mounted list column handle.
3901    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree, scene: &SceneHandle) -> NodeId {
3902        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
3903        let palette: ThemePalette = tokens.get_palette();
3904        let geometry: ThemeGeometry = tokens.get_geometry();
3905        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
3906        let ordered: bool = self.get_ordered();
3907        let start_num: usize = self.get_start().max(1);
3908        let Self {
3909            items,
3910            text_select,
3911            asset_base,
3912            on_link,
3913            on_toggle_task,
3914            ..
3915        } = self;
3916        let list_select: Option<TextSelectMode> = *text_select;
3917        let list_asset_base: &str = asset_base.as_str();
3918        let mut para_col_st: Style = Style::default();
3919        para_col_st
3920            .get_mut_layout()
3921            .set_flex_direction(FlexDirection::Column)
3922            .set_flex_grow(1.0)
3923            .set_flex_shrink(1.0)
3924            .set_min_width(Length::Px(0.0))
3925            .set_overflow(Overflow::Hidden);
3926        let mut chk_box_st: Style = style! {
3927            TextSelectMode::None
3928        };
3929        chk_box_st
3930            .get_mut_layout()
3931            .set_flex_direction(FlexDirection::Row)
3932            .set_width(Length::Px(28.0))
3933            .set_height(Length::Px(22.0))
3934            .set_justify_content(JustifyContent::Center)
3935            .set_align_items(AlignItems::Center)
3936            .set_overflow(Overflow::Hidden);
3937        chk_box_st
3938            .get_mut_paint()
3939            .set_radius(CornerRadius::all(geometry.get_radius_sm()))
3940            .set_background(Some(eva.get_inline_code_bg()))
3941            .set_border(Border::new(1.0, eva.get_border()));
3942        let mut chk_txt_st: Style = Style::default();
3943        chk_txt_st
3944            .get_mut_text()
3945            .set_font_size(11.0)
3946            .set_family(FontFamily::Monospace)
3947            .set_weight(FontWeight::Bold)
3948            .set_color(eva.get_keyword())
3949            .set_align(TextAlign::Center)
3950            .set_overflow(TextOverflow::Clip);
3951        let mut marker_st: Style = style! {
3952            TextSelectMode::None
3953        };
3954        marker_st
3955            .get_mut_text()
3956            .set_font_size(14.0)
3957            .set_weight(FontWeight::Bold)
3958            .set_color(eva.get_keyword());
3959        let mut row_nodes: Vec<NodeId> = Vec::with_capacity(items.len());
3960        for (idx, item) in items.iter().enumerate() {
3961            let indent: f32 = (item.get_depth() as f32) * 18.0;
3962            let text_ref: &str = item.get_text().as_str();
3963            let para_node: NodeId = if !has_inline_markdown_trigger(text_ref) {
3964                EuvMarkdownParagraph::mount_plain_in_tree(tree, text_ref, palette, list_select)
3965            } else {
3966                let mut para: EuvMarkdownParagraph =
3967                    EuvMarkdownParagraph::new(parse_markdown_inlines(text_ref), tokens)
3968                        .asset_base(list_asset_base);
3969                if let Some(mode) = list_select {
3970                    para = para.text_select(mode);
3971                }
3972                if let Some(callback_fn) = on_link.clone() {
3973                    para.set_on_link(Some(callback_fn));
3974                }
3975                para.mount_in_tree(tree)
3976            };
3977            let para_col: NodeId = tree.create_view(para_col_st);
3978            tree.append_child(para_col, para_node);
3979            if let Some(initial_checked) = item.checked_state() {
3980                let chk_text: NodeId = tree.create_text(
3981                    if initial_checked {
3982                        MD_CHECKBOX_ON.to_string()
3983                    } else {
3984                        MD_CHECKBOX_OFF.to_string()
3985                    },
3986                    chk_txt_st,
3987                );
3988                let chk_box: NodeId = tree.create_view(chk_box_st);
3989                tree.append_child(chk_box, chk_text);
3990                let mut item_row_st: Style = Style::default();
3991                item_row_st
3992                    .get_mut_layout()
3993                    .set_flex_direction(FlexDirection::Row)
3994                    .set_width(Length::Percent(100.0))
3995                    .set_padding(Edges::new(SPACE_XS, SPACE_SM, SPACE_XS, SPACE_SM + indent))
3996                    .set_align_items(AlignItems::Center)
3997                    .set_row_gap(SPACE_SM)
3998                    .set_column_gap(SPACE_SM);
3999                item_row_st
4000                    .get_mut_paint()
4001                    .set_radius(CornerRadius::all(geometry.get_radius_sm()))
4002                    .set_cursor(CursorIcon::Pointer);
4003                let item_row: NodeId = tree.create_view(item_row_st);
4004                let chk_cell: Rc<Cell<bool>> = Rc::new(Cell::new(initial_checked));
4005                let cb_opt: Option<Rc<dyn Fn(usize, bool)>> = on_toggle_task.clone();
4006                let scene_toggle: SceneHandle = scene.clone();
4007                let toggle_handler: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
4008                    let next: bool = !chk_cell.get();
4009                    chk_cell.set(next);
4010                    let next_label: &'static str = if next {
4011                        MD_CHECKBOX_ON
4012                    } else {
4013                        MD_CHECKBOX_OFF
4014                    };
4015                    scene_toggle.with_write(
4016                        |scene_tree: &mut SceneTree| {
4017                            scene_tree.set_text(chk_text, next_label.to_string());
4018                        },
4019                        (),
4020                    );
4021                    if let Some(handler_cb) = cb_opt.as_ref() {
4022                        handler_cb(idx, next);
4023                    }
4024                }));
4025                if let Some(node) = tree.get_node_mut(item_row) {
4026                    node.get_mut_handlers().set_on_click(Some(toggle_handler));
4027                    node.get_mut_interaction().set_focusable(true);
4028                }
4029                tree.append_children(item_row, &[chk_box, para_col]);
4030                row_nodes.push(item_row);
4031            } else {
4032                let marker_txt: String = if ordered {
4033                    format!("{}.", start_num + idx)
4034                } else if item.get_depth() % 2 == 1 {
4035                    "â—¦".to_string()
4036                } else {
4037                    "•".to_string()
4038                };
4039                let marker_node: NodeId = tree.create_text(marker_txt, marker_st);
4040                let mut item_row_st: Style = Style::default();
4041                item_row_st
4042                    .get_mut_layout()
4043                    .set_flex_direction(FlexDirection::Row)
4044                    .set_width(Length::Percent(100.0))
4045                    .set_padding(Edges::new(SPACE_XS, 0.0, SPACE_XS, indent))
4046                    .set_align_items(AlignItems::Start)
4047                    .set_row_gap(SPACE_SM)
4048                    .set_column_gap(SPACE_SM);
4049                let item_row: NodeId = tree.create_view(item_row_st);
4050                tree.append_children(item_row, &[marker_node, para_col]);
4051                row_nodes.push(item_row);
4052            }
4053        }
4054        let mut col_st: Style = Style::default();
4055        col_st
4056            .get_mut_layout()
4057            .set_flex_direction(FlexDirection::Column)
4058            .set_width(Length::Percent(100.0))
4059            .set_row_gap(SPACE_XS)
4060            .set_column_gap(SPACE_XS);
4061        let root: NodeId = tree.create_view(col_st);
4062        if !row_nodes.is_empty() {
4063            tree.append_children(root, &row_nodes);
4064        }
4065        root
4066    }
4067}
4068
4069/// Declarative `#[component]` implementation for `EuvMarkdownList`.
4070#[component]
4071/// Inherent implementation of [`EuvMarkdownList`].
4072impl EuvMarkdownList {
4073    /// Renders unordered, ordered, nested, or interactive task-checklist Markdown items, including recursively nested child blocks (`EuvCodeBlock`, nested callouts, etc.).
4074    ///
4075    /// # Arguments
4076    ///
4077    /// - `&Self` - List component reference.
4078    ///
4079    /// # Returns
4080    ///
4081    /// - `NodeId` - Mounted list column handle.
4082    fn render(&self) -> NodeId {
4083        let ctx: Context = current_context();
4084        let scene: SceneHandle = ctx.get_scene().clone();
4085        let has_children: bool = self
4086            .get_items()
4087            .iter()
4088            .any(|it: &EuvMarkdownListItem| !it.get_children().is_empty());
4089        if !has_children {
4090            return scene.with_write(
4091                |tree: &mut SceneTree| self.mount_in_tree(tree, &scene),
4092                NodeId::default(),
4093            );
4094        }
4095        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
4096        let Self {
4097            items,
4098            code_block_size_mode,
4099            text_select,
4100            asset_base,
4101            on_link,
4102            on_copy,
4103            on_toggle_task,
4104            ..
4105        } = self;
4106        let mut mounted_per_item: Vec<Vec<NodeId>> = Vec::with_capacity(items.len());
4107        for item in items.iter() {
4108            if item.get_children().is_empty() {
4109                mounted_per_item.push(Vec::new());
4110            } else {
4111                mounted_per_item.push(EuvMarkdown::mount_block_list(
4112                    item.get_children().clone(),
4113                    tokens,
4114                    (*text_select, *code_block_size_mode, asset_base.as_str()),
4115                    (on_link.as_ref(), on_copy.as_ref(), on_toggle_task.as_ref()),
4116                ));
4117            }
4118        }
4119        scene.with_write(
4120            |tree: &mut SceneTree| {
4121                let root: NodeId = self.mount_in_tree(tree, &scene);
4122                let row_ids: Vec<NodeId> = tree.children_iter(root).collect();
4123                for (row_id, extra_nodes) in row_ids.into_iter().zip(mounted_per_item) {
4124                    if extra_nodes.is_empty() {
4125                        continue;
4126                    }
4127                    let row_kids: Vec<NodeId> = tree.children_iter(row_id).collect();
4128                    if let Some(&para_col) = row_kids.get(1) {
4129                        tree.append_children(para_col, &extra_nodes);
4130                    }
4131                }
4132                root
4133            },
4134            NodeId::default(),
4135        )
4136    }
4137}
4138
4139/// Fluent builder helpers for `EuvMarkdownTable`.
4140impl EuvMarkdownTable {
4141    /// Sets the interactive text selection and copy mode for table cells (`TextSelectMode::None` by default).
4142    ///
4143    /// # Arguments
4144    ///
4145    /// - `Self` - Source table.
4146    /// - `TextSelectMode` - Selection mode applied to table cells.
4147    ///
4148    /// # Returns
4149    ///
4150    /// - `Self` - Updated table.
4151    #[must_use]
4152    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
4153        self.set_text_select(Some(mode));
4154        self
4155    }
4156
4157    /// Controls whether table cell text is selectable.
4158    ///
4159    /// # Arguments
4160    ///
4161    /// - `Self` - Source table.
4162    /// - `bool` - Whether selection is enabled.
4163    ///
4164    /// # Returns
4165    ///
4166    /// - `Self` - Updated table.
4167    #[must_use]
4168    pub fn selectable(self, enabled: bool) -> Self {
4169        let mode: TextSelectMode = if enabled {
4170            TextSelectMode::SelectAndCopy
4171        } else {
4172            TextSelectMode::None
4173        };
4174        self.text_select(mode)
4175    }
4176
4177    /// Registers a link-click handler for hyperlinks inside table cells.
4178    ///
4179    /// # Arguments
4180    ///
4181    /// - `Self` - Source table.
4182    /// - `CallbackFn` - Callback invoked with clicked URL.
4183    ///
4184    /// # Returns
4185    ///
4186    /// - `Self` - Updated table.
4187    #[must_use]
4188    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
4189    where
4190        CallbackFn: Fn(&str) + 'static,
4191    {
4192        self.set_on_link(Some(Rc::new(handler)));
4193        self
4194    }
4195
4196    /// Maps a column index to its resolved `(TextAlign, JustifyContent)` pair without heap allocation.
4197    ///
4198    /// # Arguments
4199    ///
4200    /// - `&[EuvMarkdownAlign]` - Parsed column alignments.
4201    /// - `usize` - Zero-based column index.
4202    ///
4203    /// # Returns
4204    ///
4205    /// - `(TextAlign, JustifyContent)` - Text alignment and flex justification pair.
4206    #[inline(always)]
4207    fn align_pair(alignments: &[EuvMarkdownAlign], col_idx: usize) -> (TextAlign, JustifyContent) {
4208        match alignments.get(col_idx).copied().unwrap_or_default() {
4209            EuvMarkdownAlign::Left => (TextAlign::Left, JustifyContent::Start),
4210            EuvMarkdownAlign::Center => (TextAlign::Center, JustifyContent::Center),
4211            EuvMarkdownAlign::Right => (TextAlign::Right, JustifyContent::End),
4212        }
4213    }
4214    /// Builds the dynamically sized unclipped Markdown table grid directly inside `tree`.
4215    ///
4216    /// # Arguments
4217    ///
4218    /// - `&mut SceneTree` - Mutable retained scene tree.
4219    /// - `(&[String], &[EuvMarkdownAlign], &[Vec<String>])` - Tuple of `(headers, alignments, rows)`.
4220    /// - `(&[f32], f32)` - Tuple of `(col_widths, total_w)` in logical pixels.
4221    /// - `ThemeTokens` - Active design tokens.
4222    /// - `Option<TextSelectMode>` - Optional explicit text selection mode for table cells.
4223    /// - `Option<&MarkdownStrCallback>` - Optional link click callback for cell links.
4224    ///
4225    /// # Returns
4226    ///
4227    /// - `NodeId` - Mounted inner table column node handle.
4228    fn mount_table_grid_in_tree(
4229        tree: &mut SceneTree,
4230        table_data: (&[String], &[EuvMarkdownAlign], &[Vec<String>]),
4231        layout_spec: (&[f32], f32),
4232        tokens: ThemeTokens,
4233        text_select: Option<TextSelectMode>,
4234        on_link: Option<&MarkdownStrCallback>,
4235    ) -> NodeId {
4236        let (headers, alignments, rows): (&[String], &[EuvMarkdownAlign], &[Vec<String>]) =
4237            table_data;
4238        let (col_widths, total_w): (&[f32], f32) = layout_spec;
4239        let palette: ThemePalette = tokens.get_palette();
4240        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
4241        let col_count: usize = col_widths.len();
4242        let safe_total_w: f32 = total_w.max(1.0);
4243        let mut cell_styles: Vec<Style> = Vec::with_capacity(col_count);
4244        for &cw in col_widths.iter() {
4245            let pct: f32 = (cw / safe_total_w) * 100.0;
4246            let mut computed_style: Style = Style::default();
4247            computed_style
4248                .get_mut_layout()
4249                .set_flex_direction(FlexDirection::Row)
4250                .set_width(Length::Percent(pct))
4251                .set_min_width(Length::Px(cw))
4252                .set_flex_shrink(0.0)
4253                .set_align_items(AlignItems::Center)
4254                .set_padding(Edges::symmetric(SPACE_SM, SPACE_MD))
4255                .set_overflow(Overflow::Hidden);
4256            cell_styles.push(computed_style);
4257        }
4258        let base_sel_st: Style = match text_select {
4259            Some(mode) => style! {
4260                mode
4261            },
4262            None => Style::default(),
4263        };
4264        let mut base_cell_txt_st: Style = base_sel_st;
4265        base_cell_txt_st
4266            .get_mut_layout()
4267            .set_width(Length::Percent(100.0));
4268        base_cell_txt_st
4269            .get_mut_text()
4270            .set_font_size(MD_TABLE_BODY_FONT_SIZE)
4271            .set_color(palette.get_foreground())
4272            .set_overflow(TextOverflow::Wrap);
4273        let mut row_wrap_col_st: Style = Style::default();
4274        row_wrap_col_st
4275            .get_mut_layout()
4276            .set_flex_direction(FlexDirection::Column)
4277            .set_width(Length::Percent(100.0));
4278        let mut row_div_st: Style = Style::default();
4279        row_div_st
4280            .get_mut_layout()
4281            .set_width(Length::Percent(100.0))
4282            .set_height(Length::Px(1.0));
4283        row_div_st
4284            .get_mut_paint()
4285            .set_background(Some(palette.get_border()));
4286        let mut base_data_row_st: Style = Style::default();
4287        base_data_row_st
4288            .get_mut_layout()
4289            .set_flex_direction(FlexDirection::Row)
4290            .set_width(Length::Percent(100.0))
4291            .set_align_items(AlignItems::Stretch);
4292        let even_bg: Color = palette.get_card();
4293        let odd_bg: Color = palette.get_muted().with_alpha(96);
4294        let mut inner_col_st: Style = base_sel_st;
4295        inner_col_st
4296            .get_mut_layout()
4297            .set_flex_direction(FlexDirection::Column)
4298            .set_min_width(Length::Px(safe_total_w))
4299            .set_width(Length::Percent(100.0))
4300            .set_flex_shrink(0.0);
4301        let inner_col: NodeId = tree.create_view(inner_col_st);
4302        let mut head_row_st: Style = Style::default();
4303        head_row_st
4304            .get_mut_layout()
4305            .set_flex_direction(FlexDirection::Row)
4306            .set_width(Length::Percent(100.0))
4307            .set_align_items(AlignItems::Stretch);
4308        head_row_st
4309            .get_mut_paint()
4310            .set_background(Some(eva.get_header_bg()));
4311        let head_row: NodeId = tree.create_view(head_row_st);
4312        let mut base_hdr_txt_st: Style = base_sel_st;
4313        base_hdr_txt_st
4314            .get_mut_layout()
4315            .set_width(Length::Percent(100.0));
4316        base_hdr_txt_st
4317            .get_mut_text()
4318            .set_font_size(MD_TABLE_HEADER_FONT_SIZE)
4319            .set_weight(FontWeight::Bold)
4320            .set_color(palette.get_foreground())
4321            .set_overflow(TextOverflow::Wrap);
4322        let mut cell_buf: Vec<NodeId> = Vec::with_capacity(col_count);
4323        for (ci, &cell_style) in cell_styles.iter().enumerate() {
4324            let header: &str = headers.get(ci).map(String::as_str).unwrap_or("");
4325            let (hdr_align, hdr_justify): (TextAlign, JustifyContent) =
4326                Self::align_pair(alignments, ci);
4327            let mut h_cell_st: Style = cell_style;
4328            h_cell_st.get_mut_layout().set_justify_content(hdr_justify);
4329            let h_cell: NodeId = tree.create_view(h_cell_st);
4330            if !has_inline_markdown_trigger(header) {
4331                let mut hdr_txt_st: Style = base_hdr_txt_st;
4332                hdr_txt_st.get_mut_text().set_align(hdr_align);
4333                let h_txt: NodeId = tree.create_text(header.to_string(), hdr_txt_st);
4334                tree.append_child(h_cell, h_txt);
4335            } else {
4336                let h_inlines: Vec<EuvMarkdownInline> = parse_markdown_inlines(header);
4337                let mut para: EuvMarkdownParagraph = EuvMarkdownParagraph::new(h_inlines, tokens);
4338                if let Some(mode) = text_select {
4339                    para = para.text_select(mode);
4340                }
4341                if let Some(callback_fn) = on_link {
4342                    para.set_on_link(Some(Rc::clone(callback_fn)));
4343                }
4344                let h_node: NodeId = para.mount_in_tree(tree);
4345                tree.append_child(h_cell, h_node);
4346            }
4347            cell_buf.push(h_cell);
4348        }
4349        if !cell_buf.is_empty() {
4350            tree.append_children(head_row, &cell_buf);
4351        }
4352        let mut table_children: Vec<NodeId> = Vec::with_capacity(rows.len() + 1);
4353        table_children.push(head_row);
4354        for (ri, red_val) in rows.iter().enumerate() {
4355            cell_buf.clear();
4356            for (ci, &cell_style) in cell_styles.iter().enumerate() {
4357                let cell_val: &str = red_val.get(ci).map(String::as_str).unwrap_or("");
4358                let (cell_align, cell_justify): (TextAlign, JustifyContent) =
4359                    Self::align_pair(alignments, ci);
4360                let mut c_st: Style = cell_style;
4361                c_st.get_mut_layout().set_justify_content(cell_justify);
4362                let cell_id: NodeId = tree.create_view(c_st);
4363                if !has_inline_markdown_trigger(cell_val) {
4364                    let mut t_st: Style = base_cell_txt_st;
4365                    t_st.get_mut_text().set_align(cell_align);
4366                    let t_id: NodeId = tree.create_text(cell_val.to_string(), t_st);
4367                    tree.append_child(cell_id, t_id);
4368                } else {
4369                    let inlines: Vec<EuvMarkdownInline> = parse_markdown_inlines(cell_val);
4370                    let is_plain: bool = inlines
4371                        .iter()
4372                        .all(|seg: &EuvMarkdownInline| matches!(seg, EuvMarkdownInline::Text(_)));
4373                    if is_plain {
4374                        let plain_val: String = if inlines.len() == 1
4375                            && let EuvMarkdownInline::Text(source_val) = &inlines[0]
4376                        {
4377                            source_val.clone()
4378                        } else {
4379                            inlines
4380                                .into_iter()
4381                                .map(|seg: EuvMarkdownInline| match seg {
4382                                    EuvMarkdownInline::Text(scale_val) => scale_val,
4383                                    _ => String::new(),
4384                                })
4385                                .collect()
4386                        };
4387                        let mut t_st: Style = base_cell_txt_st;
4388                        t_st.get_mut_text().set_align(cell_align);
4389                        let t_id: NodeId = tree.create_text(plain_val, t_st);
4390                        tree.append_child(cell_id, t_id);
4391                    } else {
4392                        let mut para: EuvMarkdownParagraph =
4393                            EuvMarkdownParagraph::new(inlines, tokens);
4394                        if let Some(mode) = text_select {
4395                            para = para.text_select(mode);
4396                        }
4397                        if let Some(handler_cb) = on_link {
4398                            para.set_on_link(Some(Rc::clone(handler_cb)));
4399                        }
4400                        let cell_node: NodeId = para.mount_in_tree(tree);
4401                        tree.append_child(cell_id, cell_node);
4402                    }
4403                }
4404                cell_buf.push(cell_id);
4405            }
4406            let wrap_col: NodeId = tree.create_view(row_wrap_col_st);
4407            let div_id: NodeId = tree.create_view(row_div_st);
4408            let mut d_row_st: Style = base_data_row_st;
4409            d_row_st
4410                .get_mut_paint()
4411                .set_background(Some(if ri % 2 == 1 { odd_bg } else { even_bg }));
4412            let d_row: NodeId = tree.create_view(d_row_st);
4413            if !cell_buf.is_empty() {
4414                tree.append_children(d_row, &cell_buf);
4415            }
4416            tree.append_children(wrap_col, &[div_id, d_row]);
4417            table_children.push(wrap_col);
4418        }
4419        tree.append_children(inner_col, &table_children);
4420        inner_col
4421    }
4422
4423    /// Mounts the full-viewport 2D scrollable fullscreen modal card for `EuvMarkdownTable` on demand.
4424    ///
4425    /// # Arguments
4426    ///
4427    /// - `&Context` - Active build context.
4428    /// - `ThemeTokens` - Fallback design tokens resolved against live ambient theme.
4429    /// - `(&[String], &[EuvMarkdownAlign], &[Vec<String>])` - Tuple of `(headers, alignments, rows)`.
4430    /// - `(&[f32], f32)` - Tuple of `(col_widths, total_w)` in logical pixels.
4431    /// - `(Option<TextSelectMode>, Signal<bool>)` - Tuple of `(text_select, fs_open)`.
4432    /// - `Option<&MarkdownStrCallback>` - Optional link click callback.
4433    ///
4434    /// # Returns
4435    ///
4436    /// - `NodeId` - Mounted fullscreen modal card root handle.
4437    fn mount_fullscreen_modal_card(
4438        ctx: &Context,
4439        tokens: ThemeTokens,
4440        table_data: (&[String], &[EuvMarkdownAlign], &[Vec<String>]),
4441        layout_spec: (&[f32], f32),
4442        opts: (Option<TextSelectMode>, Signal<bool>),
4443        on_link: Option<&MarkdownStrCallback>,
4444    ) -> NodeId {
4445        let (_, _, rows): (&[String], &[EuvMarkdownAlign], &[Vec<String>]) = table_data;
4446        let (col_widths, _): (&[f32], f32) = layout_spec;
4447        let (text_select, fs_open): (Option<TextSelectMode>, Signal<bool>) = opts;
4448        let live_tok: ThemeTokens = live_tokens_untracked(tokens);
4449        let live_p: ThemePalette = live_tok.get_palette();
4450        let live_g: ThemeGeometry = live_tok.get_geometry();
4451        let live_eva: CodeThemePalette = CodeThemePalette::resolve(live_tok.get_mode());
4452        let safe_sig: Signal<SafeAreaInsets> = ctx.get_safe_area();
4453        let vp_sig: Signal<Size> = ctx.get_viewport_size();
4454        let init_fs: FullscreenSafeLayout =
4455            resolve_fullscreen_safe_layout(vp_sig.get_untracked(), safe_sig.get_untracked());
4456        let init_body: Edges = init_fs.get_body_padding();
4457        let summary_text: String = format!(
4458            "{MD_TABLE_HEADER_TITLE} · {} cols × {} rows",
4459            col_widths.len(),
4460            rows.len()
4461        );
4462        let grid_node: NodeId = ctx.get_scene().with_write(
4463            |tree: &mut SceneTree| {
4464                Self::mount_table_grid_in_tree(
4465                    tree,
4466                    table_data,
4467                    layout_spec,
4468                    live_tok,
4469                    text_select,
4470                    on_link,
4471                )
4472            },
4473            NodeId::default(),
4474        );
4475        let on_close_click = move |_: &UiEvent| {
4476            let _: bool = fs_open.set_if_changed(false);
4477        };
4478        let paint_close_icon = move |bounds: Rect, display_list: &mut DisplayList| {
4479            let cur_p: ThemePalette = live_tokens_untracked(tokens).get_palette();
4480            let close_fg: Color = cur_p.surface(SurfaceRole::Card).get_fg();
4481            draw_euv_icon(EuvIconName::Close, bounds, display_list, close_fg);
4482        };
4483        let close_btn_sz: f32 = live_g.get_control_sm();
4484        let mut top_bar_node: NodeId = NodeId::default();
4485        let mut body_scroll_node: NodeId = NodeId::default();
4486        let column_quaternary_style: Style = style! {
4487            Width(Length::Percent(100.0))
4488            Height(Length::Percent(100.0))
4489            Margin(Edges::all(0.0))
4490            Padding(Edges::all(0.0))
4491            Background(live_p.get_card())
4492            Radius(0.0)
4493            Overflow::Hidden
4494            StopScrollPropagation(true)
4495            StopEventPropagation(true)
4496        };
4497        let row_quaternary_style: Style = style! {
4498            Width(Length::Percent(100.0))
4499            Padding(init_fs.get_header_padding())
4500            JustifyContent::SpaceBetween
4501            AlignItems::Center
4502            Gap(SPACE_SM)
4503            Background(live_eva.get_header_bg())
4504            Overflow::Hidden
4505            TextSelectMode::None
4506        };
4507        let text_tertiary_style: Style = style! {
4508            FlexGrow(1.0)
4509            FlexShrink(1.0)
4510            MinWidth(Length::Px(0.0))
4511            FontSize(13.0)
4512            FontWeight::SemiBold
4513            TextColor(live_p.get_foreground())
4514            TextOverflow::Ellipsis
4515        };
4516        let row_fifth_style: Style = style! {
4517            Width(Length::Px(close_btn_sz))
4518            Height(Length::Px(close_btn_sz))
4519            FlexShrink(0.0)
4520            JustifyContent::Center
4521            AlignItems::Center
4522            Background(live_p.get_card())
4523            Border::new(live_g.get_border_width(), live_p.get_border())
4524            Radius(live_g.get_radius_sm())
4525            Overflow::Hidden
4526            CursorIcon::Pointer
4527        };
4528        let canvas_style: Style = style! {
4529            Width(Length::Px(14.0))
4530            Height(Length::Px(14.0))
4531        };
4532        let view_tertiary_style: Style = style! {
4533            Width(Length::Percent(100.0))
4534            Height(Length::Px(1.0))
4535            Background(live_p.get_border())
4536        };
4537        let scroll_style: Style = style! {
4538            FlexDirection::Column
4539            FlexGrow(1.0)
4540            FlexShrink(1.0)
4541            MinHeight(Length::Px(0.0))
4542            Width(Length::Percent(100.0))
4543            AlignItems::Start
4544            Padding(Edges::new(
4545                SPACE_MD,
4546                SPACE_MD + init_body.get_right(),
4547                SPACE_MD + init_body.get_bottom(),
4548                SPACE_MD + init_body.get_left()
4549            ))
4550            StopScrollPropagation(true)
4551        };
4552        let card: NodeId = view! {
4553            column {
4554                style: column_quaternary_style
4555                row {
4556                    node_ref: top_bar_node
4557                    style: row_quaternary_style
4558                    text {
4559                        style: text_tertiary_style
4560                        { summary_text }
4561                    }
4562                    row {
4563                        style: row_fifth_style
4564                        role: A11yRole::Button
4565                        a11y_label: CODE_BUTTON_CLOSE.to_string()
4566                        on_click: on_close_click
4567                        canvas {
4568                            style: canvas_style
4569                            painter: paint_close_icon
4570                        }
4571                    }
4572                }
4573                view {
4574                    style: view_tertiary_style
4575                }
4576                scroll {
4577                    node_ref: body_scroll_node
4578                    style: scroll_style
4579                    { grid_node }
4580                }
4581            }
4582        };
4583        let handle_safe: SceneHandle = ctx.get_scene().clone();
4584        let (safe_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4585            Effect::new(move || {
4586                let fs_lay: FullscreenSafeLayout =
4587                    resolve_fullscreen_safe_layout(vp_sig.get(), safe_sig.get());
4588                let fs_body: Edges = fs_lay.get_body_padding();
4589                handle_safe.with_write(
4590                    |tree: &mut SceneTree| {
4591                        let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4592                        if let Some(item_count) = tree.get_node_mut(top_bar_node) {
4593                            item_count
4594                                .get_mut_style()
4595                                .get_mut_layout()
4596                                .set_padding(fs_lay.get_header_padding());
4597                            tree.mark_dirty(top_bar_node, dirty_l | DIRTY_PAINT);
4598                        }
4599                        if let Some(node_entry) = tree.get_node_mut(body_scroll_node) {
4600                            node_entry
4601                                .get_mut_style()
4602                                .get_mut_layout()
4603                                .set_padding(Edges::new(
4604                                    SPACE_MD,
4605                                    SPACE_MD + fs_body.get_right(),
4606                                    SPACE_MD + fs_body.get_bottom(),
4607                                    SPACE_MD + fs_body.get_left(),
4608                                ));
4609                            tree.mark_dirty(body_scroll_node, dirty_l | DIRTY_PAINT);
4610                        }
4611                    },
4612                    (),
4613                );
4614            })
4615        });
4616        ctx.get_scene().with_write(
4617            |tree: &mut SceneTree| {
4618                tree.attach_scope(card, safe_scope);
4619            },
4620            (),
4621        );
4622        card
4623    }
4624
4625    /// Mounts the complete GFM aligned table with dynamic unclipped columns, 2D scrolling, and a lazy fullscreen modal directly into an already-borrowed `SceneTree`.
4626    ///
4627    /// # Arguments
4628    ///
4629    /// - `&Self` - Table component reference.
4630    /// - `&mut SceneTree` - Mutable scene tree.
4631    /// - `&Context` - Active build context for fullscreen modal mounting.
4632    ///
4633    /// # Returns
4634    ///
4635    /// - `NodeId` - Mounted table container handle.
4636    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree, ctx: &Context) -> NodeId {
4637        let base_tokens: ThemeTokens = self.get_tokens();
4638        let tokens: ThemeTokens = live_tokens_untracked(base_tokens);
4639        let palette: ThemePalette = tokens.get_palette();
4640        let geometry: ThemeGeometry = tokens.get_geometry();
4641        let ctrl_sm: f32 = geometry.get_control_sm();
4642        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
4643        let Self {
4644            headers,
4645            alignments,
4646            rows,
4647            text_select,
4648            on_link,
4649            ..
4650        } = self;
4651        let table_select: Option<TextSelectMode> = *text_select;
4652        let (col_widths, total_w): (Vec<f32>, f32) =
4653            compute_markdown_table_column_widths(headers, rows);
4654        let summary_text: String = format!(
4655            "{MD_TABLE_HEADER_TITLE} · {} cols × {} rows",
4656            col_widths.len(),
4657            rows.len()
4658        );
4659        let radius_md: CornerRadius = CornerRadius::all(geometry.get_radius_md().max(0.0));
4660        let radius_sm: CornerRadius = CornerRadius::all(geometry.get_radius_sm().max(0.0));
4661        let mut root_st: Style = Style::default();
4662        root_st
4663            .get_mut_layout()
4664            .set_flex_direction(FlexDirection::Column)
4665            .set_width(Length::Percent(100.0))
4666            .set_overflow(Overflow::Hidden);
4667        root_st
4668            .get_mut_paint()
4669            .set_background(Some(palette.get_card()))
4670            .set_border(Border::new(1.0, palette.get_border()))
4671            .set_radius(radius_md);
4672        let root: NodeId = tree.create_view(root_st);
4673        let mut toolbar_st: Style = style! {
4674            TextSelectMode::None
4675        };
4676        toolbar_st
4677            .get_mut_layout()
4678            .set_flex_direction(FlexDirection::Row)
4679            .set_width(Length::Percent(100.0))
4680            .set_padding(Edges::symmetric(SPACE_XS, SPACE_MD))
4681            .set_justify_content(JustifyContent::SpaceBetween)
4682            .set_align_items(AlignItems::Center)
4683            .set_row_gap(SPACE_SM)
4684            .set_column_gap(SPACE_SM)
4685            .set_overflow(Overflow::Hidden);
4686        toolbar_st
4687            .get_mut_paint()
4688            .set_background(Some(eva.get_header_bg()));
4689        let toolbar_row: NodeId = tree.create_view(toolbar_st);
4690        let mut title_st: Style = Style::default();
4691        title_st
4692            .get_mut_layout()
4693            .set_flex_grow(1.0)
4694            .set_flex_shrink(1.0)
4695            .set_min_width(Length::Px(0.0));
4696        title_st
4697            .get_mut_text()
4698            .set_font_size(11.5)
4699            .set_weight(FontWeight::SemiBold)
4700            .set_color(palette.get_muted_foreground())
4701            .set_overflow(TextOverflow::Ellipsis);
4702        let title_node: NodeId = tree.create_text(summary_text, title_st);
4703        let mut fs_btn_st: Style = Style::default();
4704        fs_btn_st
4705            .get_mut_layout()
4706            .set_flex_direction(FlexDirection::Row)
4707            .set_width(Length::Px(ctrl_sm))
4708            .set_height(Length::Px(ctrl_sm))
4709            .set_flex_shrink(0.0)
4710            .set_justify_content(JustifyContent::Center)
4711            .set_align_items(AlignItems::Center)
4712            .set_overflow(Overflow::Hidden);
4713        fs_btn_st
4714            .get_mut_paint()
4715            .set_background(Some(palette.get_card()))
4716            .set_border(Border::new(1.0, palette.get_border()))
4717            .set_radius(radius_sm)
4718            .set_cursor(CursorIcon::Pointer);
4719        let fs_btn: NodeId = tree.create_view(fs_btn_st);
4720        let mut icon_st: Style = Style::default();
4721        icon_st
4722            .get_mut_layout()
4723            .set_width(Length::Px(13.0))
4724            .set_height(Length::Px(13.0));
4725        let paint_fs_icon: CanvasDrawCallback = Rc::new(RefCell::new(
4726            move |bounds: Rect, display_list: &mut DisplayList| {
4727                let cur_p: ThemePalette = live_tokens_untracked(base_tokens).get_palette();
4728                let fg: Color = cur_p.surface(SurfaceRole::Card).get_fg();
4729                draw_euv_icon(EuvIconName::Maximize, bounds, display_list, fg);
4730            },
4731        ));
4732        let fs_icon: NodeId = tree.create_canvas(icon_st, paint_fs_icon);
4733        tree.append_child(fs_btn, fs_icon);
4734        tree.append_children(toolbar_row, &[title_node, fs_btn]);
4735        let mut div_st: Style = Style::default();
4736        div_st
4737            .get_mut_layout()
4738            .set_width(Length::Percent(100.0))
4739            .set_height(Length::Px(1.0));
4740        div_st
4741            .get_mut_paint()
4742            .set_background(Some(palette.get_border()));
4743        let div_node: NodeId = tree.create_view(div_st);
4744        let mut table_scroll_st: Style = Style::default();
4745        table_scroll_st
4746            .get_mut_layout()
4747            .set_flex_direction(FlexDirection::Column)
4748            .set_align_items(AlignItems::Start)
4749            .set_width(Length::Percent(100.0))
4750            .set_max_height(Length::Px(MD_TABLE_INLINE_MAX_HEIGHT));
4751        let scroll_id: NodeId = tree.create_scroll_view(table_scroll_st);
4752        let inner_col: NodeId = Self::mount_table_grid_in_tree(
4753            tree,
4754            (headers, alignments, rows),
4755            (&col_widths, total_w),
4756            tokens,
4757            table_select,
4758            on_link.as_ref(),
4759        );
4760        tree.append_child(scroll_id, inner_col);
4761        let mut portal_st: Style = Style::default();
4762        portal_st
4763            .get_mut_layout()
4764            .set_display(Display::None)
4765            .set_flex_direction(FlexDirection::Column)
4766            .set_position(Position::Fixed)
4767            .set_top(Some(0.0))
4768            .set_right(Some(0.0))
4769            .set_bottom(Some(0.0))
4770            .set_left(Some(0.0))
4771            .set_width(Length::Percent(100.0))
4772            .set_height(Length::Percent(100.0))
4773            .set_padding(Edges::all(0.0))
4774            .set_margin(Edges::all(0.0))
4775            .set_justify_content(JustifyContent::Start)
4776            .set_align_items(AlignItems::Stretch)
4777            .set_overflow(Overflow::Hidden)
4778            .set_z_index(Z_INDEX_FULLSCREEN);
4779        portal_st
4780            .get_mut_paint()
4781            .set_background(Some(palette.get_card()))
4782            .set_border(Border::default())
4783            .set_radius(CornerRadius::all(0.0))
4784            .set_pointer_events(PointerEvents::None)
4785            .set_stop_scroll_propagation(true)
4786            .set_stop_event_propagation(true);
4787        let fs_portal: NodeId = tree.create_portal(portal_st);
4788        let fs_open_slot: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
4789        let headers_rc: Rc<[String]> = Rc::from(headers.as_slice());
4790        let aligns_rc: Rc<[EuvMarkdownAlign]> = Rc::from(alignments.as_slice());
4791        let rows_rc: Rc<[Vec<String>]> = Rc::from(rows.as_slice());
4792        let widths_rc: Rc<[f32]> = Rc::from(col_widths.as_slice());
4793        let on_link_rc: Option<MarkdownStrCallback> = on_link.clone();
4794        let ctx_fs: Context = ctx.clone();
4795        let on_open_fs: UiEventHandler = Rc::new(RefCell::new(move |_: &UiEvent| {
4796            bind_fullscreen_context(&ctx_fs);
4797            if let Some(sig) = fs_open_slot.get() {
4798                if sig.get_untracked() {
4799                    let _: bool = sig.set_if_changed(false);
4800                }
4801                let _: bool = sig.set_if_changed(true);
4802                return;
4803            }
4804            let fs_open: Signal<bool> = Signal::new(true);
4805            fs_open_slot.set(Some(fs_open));
4806            let handle_ov: SceneHandle = ctx_fs.get_scene().clone();
4807            let handle_vp: SceneHandle = ctx_fs.get_scene().clone();
4808            let prev_open: Rc<Cell<bool>> = Rc::new(Cell::new(false));
4809            let fs_acquired: Rc<Cell<bool>> = Rc::new(Cell::new(false));
4810            let in_enter_guard: Rc<Cell<bool>> = Rc::new(Cell::new(false));
4811            let fs_cleanup: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
4812            let ctx_build: Context = ctx_fs.clone();
4813            let headers_build: Rc<[String]> = Rc::clone(&headers_rc);
4814            let aligns_build: Rc<[EuvMarkdownAlign]> = Rc::clone(&aligns_rc);
4815            let rows_build: Rc<[Vec<String>]> = Rc::clone(&rows_rc);
4816            let widths_build: Rc<[f32]> = Rc::clone(&widths_rc);
4817            let link_build: Option<MarkdownStrCallback> = on_link_rc.clone();
4818            let on_fs_key: UiEventHandler = Rc::new(RefCell::new(move |ui_event: &UiEvent| {
4819                if matches!(
4820                    ui_event.get_kind(),
4821                    UiEventKind::KeyDown(KeyCode::Escape | KeyCode::Back, _)
4822                ) && fs_open.get_untracked()
4823                {
4824                    let _: bool = fs_open.set_if_changed(false);
4825                }
4826            }));
4827            ctx_fs.get_scene().with_write(
4828                |scene_tree: &mut SceneTree| {
4829                    if let Some(node) = scene_tree.get_node_mut(fs_portal) {
4830                        node.get_mut_handlers().set_on_key_down(Some(on_fs_key));
4831                    }
4832                },
4833                (),
4834            );
4835            let (ov_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
4836                on_cleanup(move || {
4837                    if fs_cleanup.replace(false) {
4838                        exit_fullscreen();
4839                    }
4840                });
4841                let _: Effect = EuvOverlayStack::bind_signal(
4842                    fs_open,
4843                    MD_TABLE_FULLSCREEN_OVERLAY_NAME,
4844                    Z_INDEX_FULLSCREEN,
4845                );
4846                let vp_sig: Signal<Size> = ctx_build.get_viewport_size();
4847                let _: Effect = Effect::new(move || {
4848                    let box_size: Size = vp_sig.get();
4849                    if !fs_open.get() {
4850                        return;
4851                    }
4852                    let vw: f32 = box_size.get_width().max(1.0);
4853                    let vh: f32 = box_size.get_height().max(1.0);
4854                    handle_vp.with_write(
4855                        |tree_ref: &mut SceneTree| {
4856                            if let Some(item_count) = tree_ref.get_node_mut(fs_portal) {
4857                                item_count
4858                                    .get_mut_style()
4859                                    .get_mut_layout()
4860                                    .set_width(Length::Px(vw))
4861                                    .set_height(Length::Px(vh));
4862                                let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4863                                tree_ref.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
4864                                notify_frame_needed();
4865                            }
4866                        },
4867                        (),
4868                    );
4869                });
4870                let global_fs_sig: Signal<bool> = use_fullscreen_active();
4871                let ctx_fs_sig: Signal<bool> = ctx_build.immersive_fullscreen_signal();
4872                let saw_global_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
4873                let saw_ctx_fs: Rc<Cell<bool>> = Rc::new(Cell::new(false));
4874                let saw_global_reset: Rc<Cell<bool>> = Rc::clone(&saw_global_fs);
4875                let saw_ctx_reset: Rc<Cell<bool>> = Rc::clone(&saw_ctx_fs);
4876                let fs_acquired_sync: Rc<Cell<bool>> = Rc::clone(&fs_acquired);
4877                let enter_guard_sync: Rc<Cell<bool>> = Rc::clone(&in_enter_guard);
4878                let _: Effect = Effect::new(move || {
4879                    let g_active: bool = global_fs_sig.get();
4880                    let c_active: bool = ctx_fs_sig.get();
4881                    if enter_guard_sync.get() {
4882                        if g_active {
4883                            saw_global_fs.set(true);
4884                        }
4885                        if c_active {
4886                            saw_ctx_fs.set(true);
4887                        }
4888                        return;
4889                    }
4890                    if !fs_acquired_sync.get() {
4891                        saw_global_fs.set(false);
4892                        saw_ctx_fs.set(false);
4893                        return;
4894                    }
4895                    if g_active {
4896                        saw_global_fs.set(true);
4897                    }
4898                    if c_active {
4899                        saw_ctx_fs.set(true);
4900                    }
4901                    let external_exit: bool =
4902                        (saw_global_fs.get() && !g_active) || (saw_ctx_fs.get() && !c_active);
4903                    if external_exit {
4904                        let _: bool = fs_open.set_if_changed(false);
4905                    }
4906                });
4907                Effect::new(move || {
4908                    let is_open: bool = fs_open.get();
4909                    if is_open == prev_open.replace(is_open) {
4910                        return;
4911                    }
4912                    if is_open {
4913                        in_enter_guard.set(true);
4914                        saw_global_reset.set(false);
4915                        saw_ctx_reset.set(false);
4916                        let live_bg: Color =
4917                            live_tokens_untracked(base_tokens).get_palette().get_card();
4918                        let vp_now: Size = vp_sig.get_untracked();
4919                        let vw: f32 = vp_now.get_width().max(1.0);
4920                        let vh: f32 = vp_now.get_height().max(1.0);
4921                        let modal_card: NodeId = with_context(ctx_build.clone(), || {
4922                            Self::mount_fullscreen_modal_card(
4923                                &ctx_build,
4924                                base_tokens,
4925                                (&headers_build, &aligns_build, &rows_build),
4926                                (&widths_build, total_w),
4927                                (table_select, fs_open),
4928                                link_build.as_ref(),
4929                            )
4930                        });
4931                        let portal_shown: bool = modal_card != NodeId::default()
4932                            && handle_ov.with_write(
4933                                |blend_factor: &mut SceneTree| {
4934                                    if blend_factor.get_node(fs_portal).is_none()
4935                                        || blend_factor.get_node(modal_card).is_none()
4936                                    {
4937                                        return false;
4938                                    }
4939                                    blend_factor.cancel_subtree_transitions(fs_portal);
4940                                    blend_factor.replace_children(fs_portal, vec![modal_card]);
4941                                    if let Some(node_entry) = blend_factor.get_node_mut(fs_portal) {
4942                                        let computed_style: &mut Style = node_entry.get_mut_style();
4943                                        computed_style
4944                                            .get_mut_layout()
4945                                            .set_display(Display::Flex)
4946                                            .set_width(Length::Px(vw))
4947                                            .set_height(Length::Px(vh));
4948                                        computed_style
4949                                            .get_mut_paint()
4950                                            .set_background(Some(live_bg))
4951                                            .set_pointer_events(PointerEvents::Auto)
4952                                            .set_opacity(1.0)
4953                                            .set_transform(Transform2D::default());
4954                                    }
4955                                    let _: Vec<(UiEventHandler, UiEvent)> =
4956                                        blend_factor.update_focus(Some(fs_portal));
4957                                    let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4958                                    blend_factor.mark_dirty(fs_portal, dirty_l | DIRTY_PAINT);
4959                                    notify_frame_needed();
4960                                    true
4961                                },
4962                                false,
4963                            );
4964                        let entered: bool = portal_shown
4965                            && (fs_acquired.get()
4966                                || enter_fullscreen_for_portal(&ctx_build, fs_portal));
4967                        if entered {
4968                            fs_acquired.set(true);
4969                        } else {
4970                            handle_ov.dismiss_portal_immediate(fs_portal);
4971                            if fs_acquired.replace(false) {
4972                                exit_fullscreen();
4973                            }
4974                            prev_open.set(false);
4975                            let _: bool = fs_open.set_if_changed(false);
4976                        }
4977                        in_enter_guard.set(false);
4978                        notify_frame_needed();
4979                    } else {
4980                        in_enter_guard.set(false);
4981                        if fs_acquired.replace(false) {
4982                            exit_fullscreen();
4983                        }
4984                        handle_ov.dismiss_portal_immediate(fs_portal);
4985                    }
4986                })
4987            });
4988            ctx_fs.get_scene().with_write(
4989                |time_step: &mut SceneTree| {
4990                    time_step.attach_scope(root, ov_scope);
4991                },
4992                (),
4993            );
4994        }));
4995        if let Some(node) = tree.get_node_mut(fs_btn) {
4996            node.get_mut_handlers().set_on_click(Some(on_open_fs));
4997            node.get_mut_interaction().set_focusable(true);
4998            *node.get_mut_a11y() = Some(A11yProps::new(
4999                A11yRole::Button,
5000                CODE_BUTTON_FULLSCREEN.to_string(),
5001            ));
5002        }
5003        tree.append_children(root, &[toolbar_row, div_node, scroll_id, fs_portal]);
5004        root
5005    }
5006}
5007
5008/// Declarative `#[component]` implementation for `EuvMarkdownTable`.
5009#[component]
5010/// Inherent implementation of [`EuvMarkdownTable`].
5011impl EuvMarkdownTable {
5012    /// Renders a GFM aligned Markdown table with crisp hairline borders, rich cell inlines, dynamic unclipped column widths, 2D scrolling, fullscreen modal, and zebra row tint.
5013    ///
5014    /// # Arguments
5015    ///
5016    /// - `&Self` - Table component reference.
5017    ///
5018    /// # Returns
5019    ///
5020    /// - `NodeId` - Mounted table container handle.
5021    fn render(&self) -> NodeId {
5022        let ctx: Context = current_context();
5023        ctx.get_scene().with_write(
5024            |tree: &mut SceneTree| self.mount_in_tree(tree, &ctx),
5025            NodeId::default(),
5026        )
5027    }
5028}
5029
5030/// Fluent builder helpers for `EuvMarkdownDefList`.
5031impl EuvMarkdownDefList {
5032    /// Sets the interactive text selection and copy mode for the definition list (`TextSelectMode::None` by default).
5033    ///
5034    /// # Arguments
5035    ///
5036    /// - `Self` - Source definition list.
5037    /// - `TextSelectMode` - Selection mode applied to term and definition text.
5038    ///
5039    /// # Returns
5040    ///
5041    /// - `Self` - Updated definition list.
5042    #[must_use]
5043    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
5044        self.set_text_select(Some(mode));
5045        self
5046    }
5047
5048    /// Controls whether definition list text is selectable.
5049    ///
5050    /// # Arguments
5051    ///
5052    /// - `Self` - Source definition list.
5053    /// - `bool` - Whether selection is enabled.
5054    ///
5055    /// # Returns
5056    ///
5057    /// - `Self` - Updated definition list.
5058    #[must_use]
5059    pub fn selectable(self, enabled: bool) -> Self {
5060        let mode: TextSelectMode = if enabled {
5061            TextSelectMode::SelectAndCopy
5062        } else {
5063            TextSelectMode::None
5064        };
5065        self.text_select(mode)
5066    }
5067
5068    /// Registers a link-click handler for hyperlinks inside definitions.
5069    ///
5070    /// # Arguments
5071    ///
5072    /// - `Self` - Source definition list.
5073    /// - `CallbackFn` - Callback invoked with clicked URL.
5074    ///
5075    /// # Returns
5076    ///
5077    /// - `Self` - Updated definition list.
5078    #[must_use]
5079    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
5080    where
5081        CallbackFn: Fn(&str) + 'static,
5082    {
5083        self.set_on_link(Some(Rc::new(handler)));
5084        self
5085    }
5086}
5087
5088/// Declarative `#[component]` implementation for `EuvMarkdownDefList`.
5089#[component]
5090/// Inherent implementation of [`EuvMarkdownDefList`].
5091impl EuvMarkdownDefList {
5092    /// Renders an extended Markdown definition list with bold term headers and indented descriptions.
5093    ///
5094    /// # Arguments
5095    ///
5096    /// - `&Self` - Definition list component reference.
5097    ///
5098    /// # Returns
5099    ///
5100    /// - `NodeId` - Mounted definition list column handle.
5101    fn render(&self) -> NodeId {
5102        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
5103        let palette: ThemePalette = tokens.get_palette();
5104        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
5105        let Self {
5106            items,
5107            text_select,
5108            on_link,
5109            ..
5110        } = self;
5111        let def_select: Option<TextSelectMode> = *text_select;
5112        let mut term_base_st: Style = style! {
5113            Width(Length::Percent(100.0))
5114            FontSize(14.0)
5115            FontWeight::Bold
5116            TextColor(palette.get_foreground())
5117        };
5118        if let Some(mode) = def_select {
5119            term_base_st = term_base_st.text_select(mode);
5120        }
5121        let entry_nodes: Vec<NodeId> = items
5122            .iter()
5123            .map(|entry: &EuvMarkdownDefItem| {
5124                let term: &str = entry.get_term().as_str();
5125                let term_node: NodeId = if !has_inline_markdown_trigger(term) {
5126                    view! {
5127                        text {
5128                            style: term_base_st
5129                            { term }
5130                        }
5131                    }
5132                } else {
5133                    let mut term_para: EuvMarkdownParagraph =
5134                        EuvMarkdownParagraph::new(parse_markdown_inlines(term), tokens);
5135                    if let Some(mode) = def_select {
5136                        term_para = term_para.text_select(mode);
5137                    }
5138                    if let Some(callback_fn) = on_link.clone() {
5139                        term_para.set_on_link(Some(callback_fn));
5140                    }
5141                    term_para.mount()
5142                };
5143                let def_nodes: Vec<NodeId> = entry
5144                    .get_definitions()
5145                    .iter()
5146                    .map(|desc: &String| {
5147                        let desc_str: &str = desc.as_str();
5148                        if !has_inline_markdown_trigger(desc_str) {
5149                            return EuvMarkdownParagraph::mount_plain_text(
5150                                desc_str, palette, def_select,
5151                            );
5152                        }
5153                        let mut para: EuvMarkdownParagraph =
5154                            EuvMarkdownParagraph::new(parse_markdown_inlines(desc_str), tokens);
5155                        if let Some(mode) = def_select {
5156                            para = para.text_select(mode);
5157                        }
5158                        if let Some(handler_cb) = on_link.clone() {
5159                            para.set_on_link(Some(handler_cb));
5160                        }
5161                        para.mount()
5162                    })
5163                    .collect();
5164                let column_secondary_style: Style = style! {
5165                    Width(Length::Percent(100.0))
5166                    Gap(SPACE_XS)
5167                };
5168                let row_tertiary_style: Style = style! {
5169                    Width(Length::Percent(100.0))
5170                    Padding(Edges::new(0.0, 0.0, 0.0, SPACE_SM))
5171                    Gap(SPACE_SM)
5172                };
5173                let view_secondary_style: Style = style! {
5174                    Width(Length::Px(2.0))
5175                    FlexShrink(0.0)
5176                    Background(eva.get_border())
5177                };
5178                let column_tertiary_style: Style = style! {
5179                    FlexGrow(1.0)
5180                    FlexShrink(1.0)
5181                    MinWidth(Length::Px(0.0))
5182                    Gap(SPACE_XS)
5183                };
5184                view! {
5185                    column {
5186                        style: column_secondary_style
5187                        { term_node }
5188                        row {
5189                            style: row_tertiary_style
5190                            view {
5191                                style: view_secondary_style
5192                            }
5193                            column {
5194                                style: column_tertiary_style
5195                                ..def_nodes
5196                            }
5197                        }
5198                    }
5199                }
5200            })
5201            .collect();
5202        let mut root_st: Style = style! {
5203            FlexDirection::Column
5204            Width(Length::Percent(100.0))
5205            Gap(SPACE_MD)
5206        };
5207        if let Some(mode) = def_select {
5208            root_st = root_st.text_select(mode);
5209        }
5210        view! {
5211            column {
5212                style: root_st
5213                ..entry_nodes
5214            }
5215        }
5216    }
5217}
5218
5219/// Fluent builder helpers for `EuvMarkdownFootnotes`.
5220impl EuvMarkdownFootnotes {
5221    /// Sets the interactive text selection and copy mode for footnotes (`TextSelectMode::None` by default).
5222    ///
5223    /// # Arguments
5224    ///
5225    /// - `Self` - Source footnotes section.
5226    /// - `TextSelectMode` - Selection mode applied to footnote text.
5227    ///
5228    /// # Returns
5229    ///
5230    /// - `Self` - Updated footnotes section.
5231    #[must_use]
5232    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
5233        self.set_text_select(Some(mode));
5234        self
5235    }
5236
5237    /// Controls whether footnote text is selectable.
5238    ///
5239    /// # Arguments
5240    ///
5241    /// - `Self` - Source footnotes section.
5242    /// - `bool` - Whether selection is enabled.
5243    ///
5244    /// # Returns
5245    ///
5246    /// - `Self` - Updated footnotes section.
5247    #[must_use]
5248    pub fn selectable(self, enabled: bool) -> Self {
5249        let mode: TextSelectMode = if enabled {
5250            TextSelectMode::SelectAndCopy
5251        } else {
5252            TextSelectMode::None
5253        };
5254        self.text_select(mode)
5255    }
5256
5257    /// Registers a link-click handler for hyperlinks inside footnotes.
5258    ///
5259    /// # Arguments
5260    ///
5261    /// - `Self` - Source footnotes section.
5262    /// - `CallbackFn` - Callback invoked with clicked URL.
5263    ///
5264    /// # Returns
5265    ///
5266    /// - `Self` - Updated footnotes section.
5267    #[must_use]
5268    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
5269    where
5270        CallbackFn: Fn(&str) + 'static,
5271    {
5272        self.set_on_link(Some(Rc::new(handler)));
5273        self
5274    }
5275}
5276
5277/// Declarative `#[component]` implementation for `EuvMarkdownFootnotes`.
5278#[component]
5279/// Inherent implementation of [`EuvMarkdownFootnotes`].
5280impl EuvMarkdownFootnotes {
5281    /// Renders the bottom Markdown footnotes list separated by a subtle hairline rule.
5282    ///
5283    /// # Arguments
5284    ///
5285    /// - `&Self` - Footnotes component reference.
5286    ///
5287    /// # Returns
5288    ///
5289    /// - `NodeId` - Mounted footnotes section handle.
5290    fn render(&self) -> NodeId {
5291        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
5292        let palette: ThemePalette = tokens.get_palette();
5293        let geometry: ThemeGeometry = tokens.get_geometry();
5294        let fn_badge_bg: Color = palette.get_primary().with_alpha(24);
5295        let fn_badge_fg: Color = palette.readable_foreground_with(
5296            palette.get_primary(),
5297            blend_over(fn_badge_bg, palette.get_background()),
5298        );
5299        let Self {
5300            footnotes,
5301            text_select,
5302            on_link,
5303            ..
5304        } = self;
5305        let fn_select: Option<TextSelectMode> = *text_select;
5306        let rows: Vec<NodeId> = footnotes
5307            .iter()
5308            .map(|entry: &EuvMarkdownFootnote| {
5309                let id_lbl: String = format!("[{}]", entry.get_id());
5310                let content_str: &str = entry.get_content().as_str();
5311                let para_node: NodeId = if !has_inline_markdown_trigger(content_str) {
5312                    EuvMarkdownParagraph::mount_plain_text(content_str, palette, fn_select)
5313                } else {
5314                    let mut para: EuvMarkdownParagraph =
5315                        EuvMarkdownParagraph::new(parse_markdown_inlines(content_str), tokens);
5316                    if let Some(mode) = fn_select {
5317                        para = para.text_select(mode);
5318                    }
5319                    if let Some(callback_fn) = on_link.clone() {
5320                        para.set_on_link(Some(callback_fn));
5321                    }
5322                    para.mount()
5323                };
5324                let row_style: Style = style! {
5325                    Width(Length::Percent(100.0))
5326                    AlignItems::Start
5327                    Gap(SPACE_SM)
5328                };
5329                let row_secondary_style: Style = style! {
5330                    JustifyContent::Center
5331                    AlignItems::Center
5332                    Padding(Edges::symmetric(2.0, SPACE_XS))
5333                    Radius(geometry.get_radius_sm())
5334                    Overflow::Hidden
5335                    Background(fn_badge_bg)
5336                    FlexShrink(0.0)
5337                };
5338                let text_secondary_style: Style = style! {
5339                    FontSize(11.0)
5340                    FontFamily::Monospace
5341                    FontWeight::Bold
5342                    TextAlign::Center
5343                    TextOverflow::Clip
5344                    TextColor(fn_badge_fg)
5345                };
5346                let column_style: Style = style! {
5347                    FlexGrow(1.0)
5348                    FlexShrink(1.0)
5349                    MinWidth(Length::Px(0.0))
5350                    Overflow::Hidden
5351                };
5352                view! {
5353                    row {
5354                        style: row_style
5355                        row {
5356                            style: row_secondary_style
5357                            text {
5358                                style: text_secondary_style
5359                                { id_lbl }
5360                            }
5361                        }
5362                        column {
5363                            style: column_style
5364                            { para_node }
5365                        }
5366                    }
5367                }
5368            })
5369            .collect();
5370        let mut root_st: Style = style! {
5371            FlexDirection::Column
5372            Width(Length::Percent(100.0))
5373            Gap(SPACE_SM)
5374            Padding(Edges::new(SPACE_XS, 0.0, 0.0, 0.0))
5375        };
5376        if let Some(mode) = fn_select {
5377            root_st = root_st.text_select(mode);
5378        }
5379        let view_style: Style = style! {
5380            Width(Length::Percent(100.0))
5381            Height(Length::Px(1.0))
5382            Background(palette.get_border())
5383        };
5384        let text_style: Style = style! {
5385            FontSize(12.0)
5386            FontWeight::Bold
5387            TextColor(palette.get_muted_foreground())
5388        };
5389        view! {
5390            column {
5391                style: root_st
5392                view {
5393                    style: view_style
5394                }
5395                text {
5396                    style: text_style
5397                    { MD_FOOTNOTES_TITLE }
5398                }
5399                ..rows
5400            }
5401        }
5402    }
5403}
5404
5405/// Direct tree mounting helper for `EuvMarkdownDivider`.
5406impl EuvMarkdownDivider {
5407    /// Mounts a full-width thematic break directly into an already-borrowed `SceneTree`.
5408    ///
5409    /// # Arguments
5410    ///
5411    /// - `&Self` - Divider component reference.
5412    /// - `&mut SceneTree` - Mutable scene tree.
5413    ///
5414    /// # Returns
5415    ///
5416    /// - `NodeId` - Mounted divider handle.
5417    pub(crate) fn mount_in_tree(&self, tree: &mut SceneTree) -> NodeId {
5418        let palette: ThemePalette = live_tokens_untracked(self.get_tokens()).get_palette();
5419        let mut computed_style: Style = Style::default();
5420        computed_style
5421            .get_mut_layout()
5422            .set_width(Length::Percent(100.0))
5423            .set_height(Length::Px(1.0))
5424            .set_margin(Edges::symmetric(SPACE_XS, 0.0));
5425        computed_style
5426            .get_mut_paint()
5427            .set_background(Some(palette.get_border()));
5428        tree.create_view(computed_style)
5429    }
5430}
5431
5432/// Declarative `#[component]` implementation for `EuvMarkdownDivider`.
5433#[component]
5434/// Inherent implementation of [`EuvMarkdownDivider`].
5435impl EuvMarkdownDivider {
5436    /// Renders a subtle thematic break across the full container width.
5437    ///
5438    /// # Arguments
5439    ///
5440    /// - `&Self` - Divider component reference.
5441    ///
5442    /// # Returns
5443    ///
5444    /// - `NodeId` - Mounted divider handle.
5445    fn render(&self) -> NodeId {
5446        let ctx: Context = current_context();
5447        ctx.get_scene().with_write(
5448            |tree: &mut SceneTree| self.mount_in_tree(tree),
5449            NodeId::default(),
5450        )
5451    }
5452}
5453
5454/// Fluent builder helpers for `EuvMarkdownImage`.
5455impl EuvMarkdownImage {
5456    /// Sets the relative asset base prefix used when resolving local Markdown image paths.
5457    ///
5458    /// # Arguments
5459    ///
5460    /// - `Self` - Source image figure component.
5461    /// - `TextValue` - Relative asset base prefix (for example `"./"` or `"../"`).
5462    ///
5463    /// # Returns
5464    ///
5465    /// - `Self` - Updated image figure component.
5466    #[must_use]
5467    pub fn asset_base<TextValue>(mut self, base: TextValue) -> Self
5468    where
5469        TextValue: Into<String>,
5470    {
5471        self.set_asset_base(base.into());
5472        self
5473    }
5474
5475    /// Mounts a decoded `NodeKind::Image` wired for click-to-preview lightbox plus optional accessible alt caption inside `tree`.
5476    ///
5477    /// # Arguments
5478    ///
5479    /// - `&mut SceneTree` - Mutable scene tree.
5480    /// - `Context` - Live application context captured during render.
5481    /// - `ImageBuffer` - Decoded RGBA8 image buffer.
5482    /// - `&str` - Accessible alt caption (omitted when empty).
5483    /// - `ThemeTokens` - Active theme tokens.
5484    /// - `NodeId` - Associated hidden lightbox portal handle.
5485    ///
5486    /// # Returns
5487    ///
5488    /// - `Vec<NodeId>` - Mounted image, optional caption, and lightbox portal child nodes.
5489    fn build_loaded_figure_children(
5490        tree: &mut SceneTree,
5491        ctx: Context,
5492        buf: ImageBuffer,
5493        alt: &str,
5494        tokens: ThemeTokens,
5495        lb_portal: NodeId,
5496    ) -> Vec<NodeId> {
5497        let palette: ThemePalette = tokens.get_palette();
5498        let geometry: ThemeGeometry = tokens.get_geometry();
5499        let (dw, dh): (f32, f32) = EuvMarkdownParagraph::fit_image_dims(
5500            buf.get_width(),
5501            buf.get_height(),
5502            MD_IMAGE_MAX_DISPLAY_WIDTH,
5503            MD_IMAGE_MAX_DISPLAY_HEIGHT,
5504        );
5505        let mut img_st: Style = Style::default();
5506        img_st
5507            .get_mut_layout()
5508            .set_width(Length::Px(dw))
5509            .set_height(Length::Px(dh))
5510            .set_max_width(Length::Percent(100.0));
5511        img_st
5512            .get_mut_paint()
5513            .set_radius(CornerRadius::all(geometry.get_radius_md()))
5514            .set_cursor(CursorIcon::Pointer);
5515        let buf_slot: Rc<RefCell<Option<ImageBuffer>>> = Rc::new(RefCell::new(Some(buf.clone())));
5516        let img_node: NodeId = tree.create_image(buf, img_st);
5517        if !alt.is_empty()
5518            && let Some(node) = tree.get_node_mut(img_node)
5519        {
5520            *node.get_mut_a11y() = Some(A11yProps::new(A11yRole::Image, alt.to_string()));
5521        }
5522        attach_image_lightbox_trigger(
5523            tree,
5524            ctx,
5525            img_node,
5526            lb_portal,
5527            buf_slot,
5528            (alt.to_string(), tokens),
5529        );
5530        let mut out: Vec<NodeId> = Vec::with_capacity(3);
5531        out.push(img_node);
5532        if !alt.trim().is_empty() {
5533            let mut cap_st: Style = Style::default();
5534            cap_st.get_mut_layout().set_width(Length::Percent(100.0));
5535            cap_st
5536                .get_mut_text()
5537                .set_font_size(12.0)
5538                .set_color(palette.get_muted_foreground());
5539            out.push(tree.create_text(alt.trim().to_string(), cap_st));
5540        }
5541        out.push(lb_portal);
5542        out
5543    }
5544}
5545
5546/// Declarative `#[component]` implementation for `EuvMarkdownImage`.
5547#[component]
5548/// Inherent implementation of [`EuvMarkdownImage`].
5549impl EuvMarkdownImage {
5550    /// Loads and renders a Markdown image figure natively as decoded RGBA8 pixels with aspect-ratio scaling, click-to-preview lightbox, and optional alt caption.
5551    ///
5552    /// # Arguments
5553    ///
5554    /// - `&Self` - Image figure component reference.
5555    ///
5556    /// # Returns
5557    ///
5558    /// - `NodeId` - Mounted image figure container handle.
5559    fn render(&self) -> NodeId {
5560        let ctx: Context = current_context();
5561        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
5562        let palette: ThemePalette = tokens.get_palette();
5563        let geometry: ThemeGeometry = tokens.get_geometry();
5564        let eva: CodeThemePalette = CodeThemePalette::resolve(tokens.get_mode());
5565        let alt: String = self.get_alt().clone();
5566        let resolved: String =
5567            resolve_markdown_asset_url(self.get_url().as_str(), self.get_asset_base().as_str());
5568        let mut fig_st: Style = Style::default();
5569        fig_st
5570            .get_mut_layout()
5571            .set_flex_direction(FlexDirection::Column)
5572            .set_width(Length::Percent(100.0))
5573            .set_align_items(AlignItems::Start)
5574            .set_row_gap(SPACE_XS)
5575            .set_column_gap(SPACE_XS)
5576            .set_overflow(Overflow::Hidden);
5577        let scene: SceneHandle = ctx.get_scene().clone();
5578        if let Some(buf) = cached_network_image(&resolved) {
5579            let ctx_cached: Context = ctx;
5580            return scene.with_write(
5581                |tree: &mut SceneTree| {
5582                    let root: NodeId = tree.create_view(fig_st);
5583                    let lb_portal: NodeId = create_image_lightbox_portal(tree);
5584                    let kids: Vec<NodeId> = Self::build_loaded_figure_children(
5585                        tree,
5586                        ctx_cached,
5587                        buf,
5588                        alt.as_str(),
5589                        tokens,
5590                        lb_portal,
5591                    );
5592                    tree.append_children(root, &kids);
5593                    root
5594                },
5595                NodeId::default(),
5596            );
5597        }
5598        let placeholder_label: String = if !alt.trim().is_empty() {
5599            alt.trim().to_string()
5600        } else {
5601            MD_IMAGE_LOADING_LABEL.to_string()
5602        };
5603        let (root, lb_portal): (NodeId, NodeId) = scene.with_write(
5604            |tree: &mut SceneTree| {
5605                let root_id: NodeId = tree.create_view(fig_st);
5606                let portal_id: NodeId = create_image_lightbox_portal(tree);
5607                let mut ph_st: Style = Style::default();
5608                ph_st
5609                    .get_mut_layout()
5610                    .set_flex_direction(FlexDirection::Row)
5611                    .set_padding(Edges::symmetric(SPACE_SM, SPACE_MD))
5612                    .set_align_items(AlignItems::Center)
5613                    .set_row_gap(SPACE_SM)
5614                    .set_column_gap(SPACE_SM)
5615                    .set_max_width(Length::Percent(100.0))
5616                    .set_overflow(Overflow::Hidden);
5617                ph_st
5618                    .get_mut_paint()
5619                    .set_background(Some(eva.get_header_bg()))
5620                    .set_border(Border::new(1.0, eva.get_border()))
5621                    .set_radius(CornerRadius::all(geometry.get_radius_md()));
5622                let mut txt_st: Style = Style::default();
5623                txt_st
5624                    .get_mut_text()
5625                    .set_font_size(12.5)
5626                    .set_color(palette.get_muted_foreground());
5627                let ph_id: NodeId = tree.create_view(ph_st);
5628                let txt_id: NodeId = tree.create_text(placeholder_label.clone(), txt_st);
5629                tree.append_child(ph_id, txt_id);
5630                tree.append_children(root_id, &[ph_id, portal_id]);
5631                (root_id, portal_id)
5632            },
5633            (NodeId::default(), NodeId::default()),
5634        );
5635        let alt_cb: String = alt;
5636        let scene_cb: SceneHandle = scene;
5637        let ctx_cb: Context = ctx;
5638        request_network_image(
5639            &resolved,
5640            Rc::new(move |loaded: Option<ImageBuffer>| {
5641                if let Some(buf) = loaded {
5642                    let alt_inner: String = alt_cb.clone();
5643                    let ctx_inner: Context = ctx_cb.clone();
5644                    scene_cb.with_write(
5645                        |tree: &mut SceneTree| {
5646                            if tree.get_node(root).is_none() || tree.get_node(lb_portal).is_none() {
5647                                return;
5648                            }
5649                            let kids: Vec<NodeId> = Self::build_loaded_figure_children(
5650                                tree,
5651                                ctx_inner,
5652                                buf,
5653                                alt_inner.as_str(),
5654                                tokens,
5655                                lb_portal,
5656                            );
5657                            tree.replace_children(root, kids);
5658                            notify_frame_needed();
5659                        },
5660                        (),
5661                    );
5662                }
5663            }),
5664        );
5665        root
5666    }
5667}
5668
5669/// Fluent builder helpers for `EuvMarkdownDetails`.
5670impl EuvMarkdownDetails {
5671    /// Sets the default inline sizing mode forwarded to fenced `EuvCodeBlock` blocks inside expanded details (`EuvCodeBlockSizeMode::AutoExpand` by default).
5672    ///
5673    /// # Arguments
5674    ///
5675    /// - `Self` - Source disclosure block.
5676    /// - `EuvCodeBlockSizeMode` - Code block sizing mode.
5677    ///
5678    /// # Returns
5679    ///
5680    /// - `Self` - Updated disclosure block.
5681    #[must_use]
5682    pub fn code_block_size_mode(mut self, mode: EuvCodeBlockSizeMode) -> Self {
5683        self.set_code_block_size_mode(mode);
5684        self
5685    }
5686
5687    /// Sets the interactive text selection and copy mode for `<details>` content (`TextSelectMode::None` by default).
5688    ///
5689    /// # Arguments
5690    ///
5691    /// - `Self` - Source disclosure block.
5692    /// - `TextSelectMode` - Selection mode applied to nested Markdown content.
5693    ///
5694    /// # Returns
5695    ///
5696    /// - `Self` - Updated disclosure block.
5697    #[must_use]
5698    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
5699        self.set_text_select(Some(mode));
5700        self
5701    }
5702
5703    /// Controls whether content inside `<details>` is selectable.
5704    ///
5705    /// # Arguments
5706    ///
5707    /// - `Self` - Source disclosure block.
5708    /// - `bool` - Whether selection is enabled.
5709    ///
5710    /// # Returns
5711    ///
5712    /// - `Self` - Updated disclosure block.
5713    #[must_use]
5714    pub fn selectable(self, enabled: bool) -> Self {
5715        let mode: TextSelectMode = if enabled {
5716            TextSelectMode::SelectAndCopy
5717        } else {
5718            TextSelectMode::None
5719        };
5720        self.text_select(mode)
5721    }
5722
5723    /// Registers a link-click handler for hyperlinks inside expanded details.
5724    ///
5725    /// # Arguments
5726    ///
5727    /// - `Self` - Source disclosure block.
5728    /// - `CallbackFn` - Callback invoked with clicked URL.
5729    ///
5730    /// # Returns
5731    ///
5732    /// - `Self` - Updated disclosure block.
5733    #[must_use]
5734    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
5735    where
5736        CallbackFn: Fn(&str) + 'static,
5737    {
5738        self.set_on_link(Some(Rc::new(handler)));
5739        self
5740    }
5741
5742    /// Registers a copy handler for code blocks inside expanded details.
5743    ///
5744    /// # Arguments
5745    ///
5746    /// - `Self` - Source disclosure block.
5747    /// - `CallbackFn` - Callback invoked with copied code text.
5748    ///
5749    /// # Returns
5750    ///
5751    /// - `Self` - Updated disclosure block.
5752    #[must_use]
5753    pub fn on_copy<CallbackFn>(mut self, handler: CallbackFn) -> Self
5754    where
5755        CallbackFn: Fn(&str) + 'static,
5756    {
5757        self.set_on_copy(Some(Rc::new(handler)));
5758        self
5759    }
5760
5761    /// Registers a task-toggle handler for checklists inside expanded details.
5762    ///
5763    /// # Arguments
5764    ///
5765    /// - `Self` - Source disclosure block.
5766    /// - `CallbackFn` - Callback invoked with `(index, checked)`.
5767    ///
5768    /// # Returns
5769    ///
5770    /// - `Self` - Updated disclosure block.
5771    #[must_use]
5772    pub fn on_toggle_task<CallbackFn>(mut self, handler: CallbackFn) -> Self
5773    where
5774        CallbackFn: Fn(usize, bool) + 'static,
5775    {
5776        self.set_on_toggle_task(Some(Rc::new(handler)));
5777        self
5778    }
5779}
5780
5781/// Declarative `#[component]` implementation for `EuvMarkdownDetails`.
5782#[component]
5783/// Inherent implementation of [`EuvMarkdownDetails`].
5784impl EuvMarkdownDetails {
5785    /// Renders an interactive collapsible `<details><summary>` disclosure block supporting rich nested Markdown.
5786    ///
5787    /// # Arguments
5788    ///
5789    /// - `&Self` - Disclosure component reference.
5790    ///
5791    /// # Returns
5792    ///
5793    /// - `NodeId` - Mounted disclosure container handle.
5794    fn render(&self) -> NodeId {
5795        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
5796        let open: Signal<bool> = self.get_open();
5797        let Self {
5798            summary,
5799            body,
5800            text_select,
5801            asset_base,
5802            code_block_size_mode,
5803            on_link,
5804            on_copy,
5805            on_toggle_task,
5806            ..
5807        } = self;
5808        let active_cb_mode: EuvCodeBlockSizeMode = *code_block_size_mode;
5809        let nested_src: String = body.join("\n");
5810        let mut inner_md: EuvMarkdown = EuvMarkdown::new(nested_src, tokens)
5811            .code_block_size_mode(active_cb_mode)
5812            .asset_base(asset_base.as_str());
5813        if let Some(mode) = *text_select {
5814            inner_md = inner_md.text_select(mode);
5815        }
5816        if let Some(callback_fn) = on_link.clone() {
5817            inner_md.set_on_link(Some(callback_fn));
5818        }
5819        if let Some(handler_cb) = on_copy.clone() {
5820            inner_md.set_on_copy(Some(handler_cb));
5821        }
5822        if let Some(callback_fn_primary) = on_toggle_task.clone() {
5823            inner_md.set_on_toggle_task(Some(callback_fn_primary));
5824        }
5825        let body_node: NodeId = inner_md.mount();
5826        let summary_title: String = summary.clone();
5827        view! {
5828            EuvCollapsible {
5829                open: open
5830                title: summary_title
5831                content: body_node
5832                tokens: tokens
5833            }
5834        }
5835    }
5836}
5837
5838/// Fluent callback and selection builders for `EuvMarkdown`.
5839impl EuvMarkdown {
5840    /// Applies a unified container/text `Style` override (including `text_select` via `style! { text_select: ... }`).
5841    ///
5842    /// # Arguments
5843    ///
5844    /// - `Self` - Source Markdown renderer.
5845    /// - `TextValue` - Style value convertible into `Option<Style>`.
5846    ///
5847    /// # Returns
5848    ///
5849    /// - `Self` - Updated Markdown renderer.
5850    #[must_use]
5851    pub fn style<TextValue>(mut self, style: TextValue) -> Self
5852    where
5853        TextValue: Into<Option<Style>>,
5854    {
5855        self.set_style(style.into());
5856        self
5857    }
5858
5859    /// Sets the relative asset base prefix used when resolving local Markdown image URLs (for example `"./"` or `"../"`).
5860    ///
5861    /// # Arguments
5862    ///
5863    /// - `Self` - Source Markdown renderer.
5864    /// - `TextValue` - Relative asset base prefix.
5865    ///
5866    /// # Returns
5867    ///
5868    /// - `Self` - Updated Markdown renderer.
5869    #[must_use]
5870    pub fn asset_base<TextValue>(mut self, base: TextValue) -> Self
5871    where
5872        TextValue: Into<String>,
5873    {
5874        self.set_asset_base(base.into());
5875        self
5876    }
5877
5878    /// Sets the default inline sizing mode forwarded to fenced `EuvCodeBlock` blocks (`EuvCodeBlockSizeMode::AutoExpand` by default).
5879    ///
5880    /// # Arguments
5881    ///
5882    /// - `Self` - Source Markdown renderer.
5883    /// - `EuvCodeBlockSizeMode` - Code block sizing mode applied to all fenced code blocks in the document.
5884    ///
5885    /// # Returns
5886    ///
5887    /// - `Self` - Updated Markdown renderer.
5888    #[must_use]
5889    pub fn code_block_size_mode(mut self, mode: EuvCodeBlockSizeMode) -> Self {
5890        self.set_code_block_size_mode(mode);
5891        self
5892    }
5893
5894    /// Sets the interactive text selection and copy mode for the Markdown document (`TextSelectMode::None` by default; fenced code blocks default to `TextSelectMode::SelectAndCopy` unless overridden here).
5895    ///
5896    /// # Arguments
5897    ///
5898    /// - `Self` - Source Markdown renderer.
5899    /// - `TextSelectMode` - Selection mode applied across document blocks.
5900    ///
5901    /// # Returns
5902    ///
5903    /// - `Self` - Updated Markdown renderer.
5904    #[must_use]
5905    pub fn text_select(mut self, mode: TextSelectMode) -> Self {
5906        self.set_text_select(Some(mode));
5907        self
5908    }
5909
5910    /// Controls whether text inside the rendered Markdown document is selectable.
5911    ///
5912    /// # Arguments
5913    ///
5914    /// - `Self` - Source Markdown renderer.
5915    /// - `bool` - `true` to enable native text selection across blocks, `false` to disable.
5916    ///
5917    /// # Returns
5918    ///
5919    /// - `Self` - Updated Markdown renderer.
5920    #[must_use]
5921    pub fn selectable(self, enabled: bool) -> Self {
5922        let mode: TextSelectMode = if enabled {
5923            TextSelectMode::SelectAndCopy
5924        } else {
5925            TextSelectMode::None
5926        };
5927        self.text_select(mode)
5928    }
5929
5930    /// Attaches a link-click handler for hyperlinks inside the Markdown document.
5931    ///
5932    /// # Arguments
5933    ///
5934    /// - `Self` - Source Markdown renderer.
5935    /// - `CallbackFn` - Callback invoked with clicked link URL.
5936    ///
5937    /// # Returns
5938    ///
5939    /// - `Self` - Updated Markdown renderer.
5940    #[must_use]
5941    pub fn on_link<CallbackFn>(mut self, handler: CallbackFn) -> Self
5942    where
5943        CallbackFn: Fn(&str) + 'static,
5944    {
5945        self.set_on_link(Some(Rc::new(handler)));
5946        self
5947    }
5948
5949    /// Attaches a copy handler invoked when any fenced `EuvCodeBlock` or `EuvMermaid` diagram is copied.
5950    ///
5951    /// # Arguments
5952    ///
5953    /// - `Self` - Source Markdown renderer.
5954    /// - `CallbackFn` - Callback invoked with copied code text.
5955    ///
5956    /// # Returns
5957    ///
5958    /// - `Self` - Updated Markdown renderer.
5959    #[must_use]
5960    pub fn on_copy<CallbackFn>(mut self, handler: CallbackFn) -> Self
5961    where
5962        CallbackFn: Fn(&str) + 'static,
5963    {
5964        self.set_on_copy(Some(Rc::new(handler)));
5965        self
5966    }
5967
5968    /// Attaches a checkbox toggle handler for GFM task checklists inside the document.
5969    ///
5970    /// # Arguments
5971    ///
5972    /// - `Self` - Source Markdown renderer.
5973    /// - `CallbackFn` - Callback invoked with `(item_index, checked)`.
5974    ///
5975    /// # Returns
5976    ///
5977    /// - `Self` - Updated Markdown renderer.
5978    #[must_use]
5979    pub fn on_toggle_task<CallbackFn>(mut self, handler: CallbackFn) -> Self
5980    where
5981        CallbackFn: Fn(usize, bool) + 'static,
5982    {
5983        self.set_on_toggle_task(Some(Rc::new(handler)));
5984        self
5985    }
5986}
5987
5988/// Declarative `#[component]` implementation for `EuvMarkdown`.
5989#[component]
5990/// Inherent implementation of [`EuvMarkdown`].
5991impl EuvMarkdown {
5992    /// Parses and mounts a full GitHub-Flavored & Extended Markdown document natively using `view!`, including native vector Mermaid diagrams and Unicode LaTeX math.
5993    ///
5994    /// # Arguments
5995    ///
5996    /// - `&Self` - Markdown document component reference.
5997    ///
5998    /// # Returns
5999    ///
6000    /// - `NodeId` - Mounted Markdown document column handle.
6001    fn render(&self) -> NodeId {
6002        let ctx: Context = current_context();
6003        bind_fullscreen_context(&ctx);
6004        let tokens: ThemeTokens = live_tokens_untracked(self.get_tokens());
6005        let Self {
6006            source,
6007            style: custom_style,
6008            text_select,
6009            asset_base,
6010            code_block_size_mode,
6011            on_link,
6012            on_copy,
6013            on_toggle_task,
6014            ..
6015        } = self;
6016        let md_select: Option<TextSelectMode> = text_select.or_else(|| {
6017            custom_style
6018                .as_ref()
6019                .map(|computed_style: &Style| computed_style.get_text().get_text_select())
6020                .filter(|matrix_elems: &TextSelectMode| *matrix_elems != TextSelectMode::None)
6021        });
6022        let md_asset_base: &str = asset_base.as_str();
6023        let active_cb_mode: EuvCodeBlockSizeMode = *code_block_size_mode;
6024        let blocks: Vec<EuvMarkdownBlock> = parse_markdown_blocks(source);
6025        let all_pure: bool = blocks.iter().all(|blk: &EuvMarkdownBlock| match blk {
6026            EuvMarkdownBlock::Heading { .. }
6027            | EuvMarkdownBlock::Paragraph(_)
6028            | EuvMarkdownBlock::CodeBlock { .. }
6029            | EuvMarkdownBlock::Table { .. }
6030            | EuvMarkdownBlock::Divider => true,
6031            EuvMarkdownBlock::Quote {
6032                title,
6033                children,
6034                lines,
6035                ..
6036            } => {
6037                title.is_none()
6038                    && children.is_empty()
6039                    && !lines.iter().any(|text_value: &String| {
6040                        let lt: &str = text_value.trim_start();
6041                        lt.starts_with("```")
6042                            || lt.starts_with("~~~")
6043                            || lt.starts_with(MD_CALLOUT_FENCE)
6044                    })
6045            }
6046            EuvMarkdownBlock::List { items, .. } => items
6047                .iter()
6048                .all(|it: &EuvMarkdownListItem| it.get_children().is_empty()),
6049            _ => false,
6050        });
6051        let mut col_st: Style = match md_select {
6052            Some(mode) => style! {
6053                mode
6054            },
6055            None => Style::default(),
6056        };
6057        col_st
6058            .get_mut_layout()
6059            .set_flex_direction(FlexDirection::Column)
6060            .set_width(Length::Percent(100.0))
6061            .set_row_gap(SPACE_MD)
6062            .set_column_gap(SPACE_MD);
6063        if all_pure {
6064            let scene: SceneHandle = ctx.get_scene().clone();
6065            return scene.with_write(
6066                |tree: &mut SceneTree| {
6067                    let mut children: Vec<NodeId> = Vec::with_capacity(blocks.len());
6068                    for blk in blocks.into_iter() {
6069                        let node_id: NodeId = match blk {
6070                            EuvMarkdownBlock::Heading { level, text } => {
6071                                let mut heading: EuvMarkdownHeading =
6072                                    EuvMarkdownHeading::new(level, text, tokens);
6073                                if let Some(mode) = md_select {
6074                                    heading = heading.text_select(mode);
6075                                }
6076                                heading.mount_in_tree(tree)
6077                            }
6078                            EuvMarkdownBlock::Paragraph(inlines) => {
6079                                let mut para: EuvMarkdownParagraph =
6080                                    EuvMarkdownParagraph::new(inlines, tokens)
6081                                        .asset_base(md_asset_base);
6082                                if let Some(mode) = md_select {
6083                                    para = para.text_select(mode);
6084                                }
6085                                if let Some(callback_fn) = on_link.clone() {
6086                                    para.set_on_link(Some(callback_fn));
6087                                }
6088                                para.mount_in_tree(tree)
6089                            }
6090                            EuvMarkdownBlock::CodeBlock {
6091                                language,
6092                                title,
6093                                highlight_lines,
6094                                code,
6095                            } => {
6096                                let mut cb_block: EuvCodeBlock = EuvCodeBlock::new(code, tokens)
6097                                    .language(language)
6098                                    .line_numbers(true)
6099                                    .size_mode(active_cb_mode);
6100                                if let Some(mode) = md_select {
6101                                    cb_block = cb_block.text_select(mode);
6102                                }
6103                                if let Some(fname) = title {
6104                                    cb_block = cb_block.filename(fname);
6105                                }
6106                                if !highlight_lines.is_empty() {
6107                                    cb_block = cb_block.highlight_lines(highlight_lines);
6108                                }
6109                                if let Some(handler_cb) = on_copy.clone() {
6110                                    cb_block.set_on_copy(Some(handler_cb));
6111                                }
6112                                cb_block.mount_in_tree(tree, &ctx)
6113                            }
6114                            EuvMarkdownBlock::Quote { kind, lines, .. } => {
6115                                let mut quote: EuvMarkdownQuote =
6116                                    EuvMarkdownQuote::new(kind, lines, tokens);
6117                                quote.set_asset_base(md_asset_base.to_string());
6118                                if let Some(mode) = md_select {
6119                                    quote = quote.text_select(mode);
6120                                }
6121                                if let Some(callback_fn_primary) = on_link.clone() {
6122                                    quote.set_on_link(Some(callback_fn_primary));
6123                                }
6124                                quote.mount_in_tree(tree)
6125                            }
6126                            EuvMarkdownBlock::List {
6127                                ordered,
6128                                start,
6129                                items,
6130                            } => {
6131                                let mut list: EuvMarkdownList =
6132                                    EuvMarkdownList::new(ordered, items, tokens).start(start);
6133                                list.set_asset_base(md_asset_base.to_string());
6134                                if let Some(mode) = md_select {
6135                                    list = list.text_select(mode);
6136                                }
6137                                if let Some(callback_fn_secondary) = on_link.clone() {
6138                                    list.set_on_link(Some(callback_fn_secondary));
6139                                }
6140                                if let Some(callback_fn_next) = on_toggle_task.clone() {
6141                                    list.set_on_toggle_task(Some(callback_fn_next));
6142                                }
6143                                list.mount_in_tree(tree, &scene)
6144                            }
6145                            EuvMarkdownBlock::Table {
6146                                headers,
6147                                alignments,
6148                                rows,
6149                            } => {
6150                                let mut tbl: EuvMarkdownTable =
6151                                    EuvMarkdownTable::new(headers, alignments, rows, tokens);
6152                                if let Some(mode) = md_select {
6153                                    tbl = tbl.text_select(mode);
6154                                }
6155                                if let Some(callback_fn_alt) = on_link.clone() {
6156                                    tbl.set_on_link(Some(callback_fn_alt));
6157                                }
6158                                tbl.mount_in_tree(tree, &ctx)
6159                            }
6160                            EuvMarkdownBlock::Divider => {
6161                                EuvMarkdownDivider::new(tokens).mount_in_tree(tree)
6162                            }
6163                            _ => continue,
6164                        };
6165                        children.push(node_id);
6166                    }
6167                    let root: NodeId = tree.create_view(col_st);
6168                    if !children.is_empty() {
6169                        tree.append_children(root, &children);
6170                    }
6171                    root
6172                },
6173                NodeId::default(),
6174            );
6175        }
6176        let children: Vec<NodeId> = Self::mount_block_list(
6177            blocks,
6178            tokens,
6179            (md_select, active_cb_mode, md_asset_base),
6180            (on_link.as_ref(), on_copy.as_ref(), on_toggle_task.as_ref()),
6181        );
6182        ctx.get_scene().with_write(
6183            |tree: &mut SceneTree| {
6184                let root: NodeId = tree.create_view(col_st);
6185                if !children.is_empty() {
6186                    tree.append_children(root, &children);
6187                }
6188                root
6189            },
6190            NodeId::default(),
6191        )
6192    }
6193}
6194
6195/// Recursive block-list mounting helper for `EuvMarkdown` and nested block containers (`Quote`, `List`, `Details`).
6196impl EuvMarkdown {
6197    /// Mounts a list of parsed `EuvMarkdownBlock` nodes into native `euv-ui` component handles.
6198    ///
6199    /// # Arguments
6200    ///
6201    /// - `Vec<EuvMarkdownBlock>` - Ordered block-level Markdown AST nodes.
6202    /// - `ThemeTokens` - Active design tokens.
6203    /// - `(Option<TextSelectMode>, EuvCodeBlockSizeMode, &str)` - Tuple of `(text_select, code_block_size_mode, asset_base)`.
6204    /// - `MarkdownBlockCallbacks<'_>` - Optional `(on_link, on_copy, on_toggle_task)` callbacks.
6205    ///
6206    /// # Returns
6207    ///
6208    /// - `Vec<NodeId>` - Mounted scene node handles in block order.
6209    pub(crate) fn mount_block_list(
6210        blocks: Vec<EuvMarkdownBlock>,
6211        tokens: ThemeTokens,
6212        opts: (Option<TextSelectMode>, EuvCodeBlockSizeMode, &str),
6213        callbacks: MarkdownBlockCallbacks<'_>,
6214    ) -> Vec<NodeId> {
6215        let (md_select, active_cb_mode, md_asset_base): (
6216            Option<TextSelectMode>,
6217            EuvCodeBlockSizeMode,
6218            &str,
6219        ) = opts;
6220        let (on_link, on_copy, on_toggle_task): MarkdownBlockCallbacks<'_> = callbacks;
6221        blocks
6222            .into_iter()
6223            .map(|blk: EuvMarkdownBlock| match blk {
6224                EuvMarkdownBlock::Heading { level, text } => {
6225                    let mut heading: EuvMarkdownHeading =
6226                        EuvMarkdownHeading::new(level, text, tokens);
6227                    if let Some(mode) = md_select {
6228                        heading = heading.text_select(mode);
6229                    }
6230                    heading.mount()
6231                }
6232                EuvMarkdownBlock::Paragraph(inlines) => {
6233                    let mut para: EuvMarkdownParagraph =
6234                        EuvMarkdownParagraph::new(inlines, tokens).asset_base(md_asset_base);
6235                    if let Some(mode) = md_select {
6236                        para = para.text_select(mode);
6237                    }
6238                    if let Some(callback_fn) = on_link {
6239                        para.set_on_link(Some(Rc::clone(callback_fn)));
6240                    }
6241                    para.mount()
6242                }
6243                EuvMarkdownBlock::CodeBlock {
6244                    language,
6245                    title,
6246                    highlight_lines,
6247                    code,
6248                } => {
6249                    let mut cb_block: EuvCodeBlock = EuvCodeBlock::new(code, tokens)
6250                        .language(language)
6251                        .line_numbers(true)
6252                        .size_mode(active_cb_mode);
6253                    if let Some(mode) = md_select {
6254                        cb_block = cb_block.text_select(mode);
6255                    }
6256                    if let Some(fname) = title {
6257                        cb_block = cb_block.filename(fname);
6258                    }
6259                    if !highlight_lines.is_empty() {
6260                        cb_block = cb_block.highlight_lines(highlight_lines);
6261                    }
6262                    if let Some(handler_cb) = on_copy {
6263                        cb_block.set_on_copy(Some(Rc::clone(handler_cb)));
6264                    }
6265                    cb_block.mount()
6266                }
6267                EuvMarkdownBlock::Mermaid { source: diag_src } => {
6268                    let mut diagram: EuvMermaid = EuvMermaid::new(diag_src, tokens);
6269                    if let Some(callback_fn_primary) = on_copy {
6270                        diagram.set_on_copy(Some(Rc::clone(callback_fn_primary)));
6271                    }
6272                    diagram.mount()
6273                }
6274                EuvMarkdownBlock::EChart { source: chart_src } => {
6275                    let opt: EuvChartOption = parse_markdown_echart_option(&chart_src);
6276                    EuvEChart::new(opt, tokens)
6277                        .style(style! {
6278                            Height(Length::Px(MD_ECHART_HEIGHT))
6279                        })
6280                        .mount()
6281                }
6282                EuvMarkdownBlock::MathBlock(expr) => {
6283                    let mut math: EuvMarkdownMath = EuvMarkdownMath::new(expr, tokens);
6284                    if let Some(mode) = md_select {
6285                        math = math.text_select(mode);
6286                    }
6287                    math.mount()
6288                }
6289                EuvMarkdownBlock::Quote {
6290                    kind,
6291                    title,
6292                    lines,
6293                    children,
6294                    ..
6295                } => {
6296                    let mut quote: EuvMarkdownQuote = EuvMarkdownQuote::new(kind, lines, tokens);
6297                    quote.set_title(title);
6298                    quote.set_children(children);
6299                    quote.set_code_block_size_mode(active_cb_mode);
6300                    quote.set_asset_base(md_asset_base.to_string());
6301                    if let Some(mode) = md_select {
6302                        quote = quote.text_select(mode);
6303                    }
6304                    if let Some(callback_fn_secondary) = on_link {
6305                        quote.set_on_link(Some(Rc::clone(callback_fn_secondary)));
6306                    }
6307                    if let Some(callback_fn_next) = on_copy {
6308                        quote.set_on_copy(Some(Rc::clone(callback_fn_next)));
6309                    }
6310                    if let Some(callback_fn_alt) = on_toggle_task {
6311                        quote.set_on_toggle_task(Some(Rc::clone(callback_fn_alt)));
6312                    }
6313                    quote.mount()
6314                }
6315                EuvMarkdownBlock::List {
6316                    ordered,
6317                    start,
6318                    items,
6319                } => {
6320                    let mut list: EuvMarkdownList =
6321                        EuvMarkdownList::new(ordered, items, tokens).start(start);
6322                    list.set_code_block_size_mode(active_cb_mode);
6323                    list.set_asset_base(md_asset_base.to_string());
6324                    if let Some(mode) = md_select {
6325                        list = list.text_select(mode);
6326                    }
6327                    if let Some(callback_fn_inner) = on_link {
6328                        list.set_on_link(Some(Rc::clone(callback_fn_inner)));
6329                    }
6330                    if let Some(callback_fn_local) = on_copy {
6331                        list.set_on_copy(Some(Rc::clone(callback_fn_local)));
6332                    }
6333                    if let Some(callback_fn_cur) = on_toggle_task {
6334                        list.set_on_toggle_task(Some(Rc::clone(callback_fn_cur)));
6335                    }
6336                    list.mount()
6337                }
6338                EuvMarkdownBlock::Table {
6339                    headers,
6340                    alignments,
6341                    rows,
6342                } => {
6343                    let mut tbl: EuvMarkdownTable =
6344                        EuvMarkdownTable::new(headers, alignments, rows, tokens);
6345                    if let Some(mode) = md_select {
6346                        tbl = tbl.text_select(mode);
6347                    }
6348                    if let Some(callback_fn_slot) = on_link {
6349                        tbl.set_on_link(Some(Rc::clone(callback_fn_slot)));
6350                    }
6351                    tbl.mount()
6352                }
6353                EuvMarkdownBlock::DefinitionList(items) => {
6354                    let mut def_list: EuvMarkdownDefList = EuvMarkdownDefList::new(items, tokens);
6355                    if let Some(mode) = md_select {
6356                        def_list = def_list.text_select(mode);
6357                    }
6358                    if let Some(callback_fn_2) = on_link {
6359                        def_list.set_on_link(Some(Rc::clone(callback_fn_2)));
6360                    }
6361                    def_list.mount()
6362                }
6363                EuvMarkdownBlock::Footnotes(entries) => {
6364                    let mut fn_sec: EuvMarkdownFootnotes =
6365                        EuvMarkdownFootnotes::new(entries, tokens);
6366                    if let Some(mode) = md_select {
6367                        fn_sec = fn_sec.text_select(mode);
6368                    }
6369                    if let Some(callback_fn_3) = on_link {
6370                        fn_sec.set_on_link(Some(Rc::clone(callback_fn_3)));
6371                    }
6372                    fn_sec.mount()
6373                }
6374                EuvMarkdownBlock::Divider => view! {
6375                    EuvMarkdownDivider {
6376                        tokens: tokens
6377                    }
6378                },
6379                EuvMarkdownBlock::Image { alt, url } => EuvMarkdownImage::new(alt, url, tokens)
6380                    .asset_base(md_asset_base)
6381                    .mount(),
6382                EuvMarkdownBlock::Details {
6383                    summary,
6384                    open,
6385                    body,
6386                    ..
6387                } => {
6388                    let open_sig: Signal<bool> = Signal::new(open);
6389                    let mut details: EuvMarkdownDetails =
6390                        EuvMarkdownDetails::new(summary, body, open_sig, tokens)
6391                            .code_block_size_mode(active_cb_mode);
6392                    details.set_asset_base(md_asset_base.to_string());
6393                    if let Some(mode) = md_select {
6394                        details = details.text_select(mode);
6395                    }
6396                    if let Some(callback_fn_4) = on_link {
6397                        details.set_on_link(Some(Rc::clone(callback_fn_4)));
6398                    }
6399                    if let Some(callback_fn_5) = on_copy {
6400                        details.set_on_copy(Some(Rc::clone(callback_fn_5)));
6401                    }
6402                    if let Some(callback_fn_6) = on_toggle_task {
6403                        details.set_on_toggle_task(Some(Rc::clone(callback_fn_6)));
6404                    }
6405                    details.mount()
6406                }
6407            })
6408            .collect()
6409    }
6410}