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