Skip to main content

slt/context/widgets_display/
status.rs

1use super::*;
2
3impl Context {
4    /// Render an alert banner with icon and level-based coloring.
5    ///
6    /// Argument order is `(message, level)` — message first, then the
7    /// [`AlertLevel`](crate::widgets::AlertLevel). This is the executable
8    /// proof that [API_DESIGN.md](https://github.com/subinium/superlighttui/blob/main/docs/API_DESIGN.md)
9    /// Rule 3 matches the shipped signature.
10    ///
11    /// # Example
12    ///
13    /// ```no_run
14    /// # use slt::AlertLevel;
15    /// # slt::run(|ui: &mut slt::Context| {
16    /// ui.alert("Disk full", AlertLevel::Error);
17    /// ui.alert("Saved", AlertLevel::Success);
18    /// # });
19    /// ```
20    pub fn alert(&mut self, message: &str, level: crate::widgets::AlertLevel) -> Response {
21        use crate::widgets::AlertLevel;
22
23        let theme = self.theme;
24        let (icon, color) = match level {
25            AlertLevel::Info => ("ℹ", theme.accent),
26            AlertLevel::Success => ("✓", theme.success),
27            AlertLevel::Warning => ("⚠", theme.warning),
28            AlertLevel::Error => ("✕", theme.error),
29        };
30
31        let focused = self.register_focusable();
32        let key_dismiss = if focused {
33            let consumed: Vec<usize> = self
34                .available_key_presses()
35                .filter_map(|(i, key)| {
36                    if matches!(key.code, KeyCode::Enter | KeyCode::Char('x')) {
37                        Some(i)
38                    } else {
39                        None
40                    }
41                })
42                .collect();
43            let dismissed = !consumed.is_empty();
44            self.consume_indices(consumed);
45            dismissed
46        } else {
47            false
48        };
49
50        let mut response = self.container().col(|ui| {
51            ui.line(|ui| {
52                let mut icon_text = String::with_capacity(icon.len() + 2);
53                icon_text.push(' ');
54                icon_text.push_str(icon);
55                icon_text.push(' ');
56                ui.text(icon_text).fg(color).bold();
57                ui.text(message).grow(1);
58                ui.text(" [×] ").dim();
59            });
60        });
61        response.focused = focused;
62        if key_dismiss {
63            response.clicked = true;
64        }
65
66        response
67    }
68
69    /// Yes/No confirmation dialog. Returns Response with .clicked=true when answered.
70    ///
71    /// `result` is set to true for Yes, false for No.
72    ///
73    /// # Examples
74    /// ```
75    /// # use slt::*;
76    /// # TestBackend::new(80, 24).render(|ui| {
77    /// let mut answer = false;
78    /// let r = ui.confirm("Delete this file?", &mut answer);
79    /// if r.clicked && answer { /* user confirmed */ }
80    /// # });
81    /// ```
82    pub fn confirm(&mut self, question: &str, result: &mut bool) -> Response {
83        let focused = self.register_focusable();
84        let mut is_yes = *result;
85        let mut clicked = false;
86
87        // 1) Keyboard hit-test runs first so it can mutate `is_yes`.
88        if focused {
89            let mut consumed_indices = Vec::new();
90            for (i, key) in self.available_key_presses() {
91                match key.code {
92                    KeyCode::Char('y') => {
93                        is_yes = true;
94                        *result = true;
95                        clicked = true;
96                        consumed_indices.push(i);
97                    }
98                    KeyCode::Char('n') => {
99                        is_yes = false;
100                        *result = false;
101                        clicked = true;
102                        consumed_indices.push(i);
103                    }
104                    KeyCode::Tab | KeyCode::BackTab | KeyCode::Left | KeyCode::Right => {
105                        is_yes = !is_yes;
106                        *result = is_yes;
107                        consumed_indices.push(i);
108                    }
109                    KeyCode::Enter => {
110                        *result = is_yes;
111                        clicked = true;
112                        consumed_indices.push(i);
113                    }
114                    _ => {}
115                }
116            }
117            self.consume_indices(consumed_indices);
118        }
119
120        // 2) Mouse hit-test runs *before* style computation and rendering so
121        // the visual feedback for `[Yes]` / `[No]` reflects the click in the
122        // same frame the click happened. Predict the row's interaction id
123        // (the next slot the row will allocate) and look up the previous
124        // frame's rect from `prev_hit_map`. On the first frame the row has
125        // no entry yet, so we fall back to assuming the row starts at (0,0)
126        // — same behaviour as the prior implementation.
127        let q_width = UnicodeWidthStr::width(question) as u32;
128        if !clicked {
129            if let Some((mx, my)) = self.click_pos {
130                let next_id = self.rollback.interaction_count;
131                let prev_rect = self.prev_hit_map.get(next_id).copied();
132                let row_x = prev_rect.map(|r| r.x).unwrap_or(0);
133                let in_row_y = match prev_rect {
134                    Some(r) if r.height > 0 => my >= r.y && my < r.bottom(),
135                    _ => true,
136                };
137                if in_row_y {
138                    let yes_start = row_x + q_width + 1;
139                    let yes_end = yes_start + 5;
140                    let no_start = yes_end + 1;
141                    let no_end = no_start + 4; // "[No]" = 4 display columns
142                    if mx >= yes_start && mx < yes_end {
143                        is_yes = true;
144                        *result = true;
145                        clicked = true;
146                    } else if mx >= no_start && mx < no_end {
147                        is_yes = false;
148                        *result = false;
149                        clicked = true;
150                    }
151                }
152            }
153        }
154
155        // 3) Style computation reads the now-mutated `is_yes`.
156        let yes_style = if is_yes {
157            if focused {
158                Style::new().fg(self.theme.bg).bg(self.theme.success).bold()
159            } else {
160                Style::new().fg(self.theme.success).bold()
161            }
162        } else {
163            Style::new().fg(self.theme.text_dim)
164        };
165        let no_style = if !is_yes {
166            if focused {
167                Style::new().fg(self.theme.bg).bg(self.theme.error).bold()
168            } else {
169                Style::new().fg(self.theme.error).bold()
170            }
171        } else {
172            Style::new().fg(self.theme.text_dim)
173        };
174
175        // 4) Render with the post-hit-test styles.
176        let mut response = self.row(|ui| {
177            ui.text(question);
178            ui.text(" ");
179            ui.styled("[Yes]", yes_style);
180            ui.text(" ");
181            ui.styled("[No]", no_style);
182        });
183
184        response.focused = focused;
185        response.clicked = clicked;
186        response.changed = clicked;
187        response
188    }
189
190    /// Begin building a breadcrumb navigation bar with the default separator
191    /// (` › `).
192    ///
193    /// Returns a [`Breadcrumb`] builder that auto-renders on `Drop`. Chain
194    /// `.separator(s)` for a custom separator and `.color(c)` for a custom
195    /// link color. Call `.show()` to render and obtain a
196    /// [`BreadcrumbResponse`] carrying `clicked_segment` and `Deref<Response>`.
197    ///
198    /// # Example
199    ///
200    /// ```no_run
201    /// # slt::run(|ui: &mut slt::Context| {
202    /// // simple
203    /// ui.breadcrumb(&["Home", "Settings", "Profile"]);
204    ///
205    /// // with custom separator + color, capturing the response
206    /// let r = ui
207    ///     .breadcrumb(&["Home", "src", "lib.rs"])
208    ///     .separator(" > ")
209    ///     .show();
210    /// if let Some(i) = r.clicked_segment {
211    ///     // navigate to segment `i`
212    /// }
213    /// # });
214    /// ```
215    pub fn breadcrumb<'a>(&'a mut self, segments: &'a [&'a str]) -> Breadcrumb<'a> {
216        Breadcrumb::new(self, segments)
217    }
218
219    /// Collapsible section that toggles on click, Enter, or Space.
220    pub fn accordion(
221        &mut self,
222        title: &str,
223        open: &mut bool,
224        f: impl FnOnce(&mut Context),
225    ) -> Response {
226        let theme = self.theme;
227        let focused = self.register_focusable();
228        let old_open = *open;
229        let toggled_from_key = self.consume_activation_keys(focused);
230        if toggled_from_key {
231            *open = !*open;
232        }
233
234        let icon = if *open { "▾" } else { "▸" };
235        let title_color = if focused { theme.primary } else { theme.text };
236
237        let mut response = self.container().col(|ui| {
238            ui.line(|ui| {
239                ui.text(icon).fg(title_color);
240                let mut title_text = String::with_capacity(1 + title.len());
241                title_text.push(' ');
242                title_text.push_str(title);
243                ui.text(title_text).bold().fg(title_color);
244            });
245        });
246
247        if response.clicked {
248            *open = !*open;
249        }
250
251        if *open {
252            let indent = self.theme.spacing.sm();
253            let _ = self.container().pl(indent).col(f);
254        }
255
256        response.focused = focused;
257        response.changed = *open != old_open;
258        response
259    }
260
261    /// Render a key-value definition list with aligned columns.
262    pub fn definition_list(&mut self, items: &[(&str, &str)]) -> Response {
263        let max_key_width = items
264            .iter()
265            .map(|(k, _)| UnicodeWidthStr::width(*k))
266            .max()
267            .unwrap_or(0);
268
269        let _ = self.col(|ui| {
270            for (key, value) in items {
271                ui.line(|ui| {
272                    let key_display_w = UnicodeWidthStr::width(*key);
273                    let pad = max_key_width.saturating_sub(key_display_w);
274                    let mut padded = String::with_capacity(key.len() + pad);
275                    padded.extend(std::iter::repeat(' ').take(pad));
276                    padded.push_str(key);
277                    ui.text(padded).dim();
278                    ui.text("  ");
279                    ui.text(*value);
280                });
281            }
282        });
283
284        Response::none()
285    }
286
287    /// Render a horizontal divider with a centered text label.
288    pub fn divider_text(&mut self, label: &str) -> Response {
289        let w = self.width();
290        let label_len = UnicodeWidthStr::width(label) as u32;
291        // Reserve `label_len + 2` for the label and its single-space padding on
292        // each side, then split the remaining width evenly. On odd widths the
293        // right separator is one cell longer (no asymmetry that's visible).
294        let total_separator = w.saturating_sub(label_len + 2);
295        let left_len = total_separator / 2;
296        let right_len = total_separator - left_len;
297        let left: String = "─".repeat(left_len as usize);
298        let right: String = "─".repeat(right_len as usize);
299        let theme = self.theme;
300        self.line(|ui| {
301            ui.text(&left).fg(theme.border);
302            let mut label_text = String::with_capacity(label.len() + 2);
303            label_text.push(' ');
304            label_text.push_str(label);
305            label_text.push(' ');
306            ui.text(label_text).fg(theme.text);
307            ui.text(&right).fg(theme.border);
308        });
309
310        Response::none()
311    }
312
313    /// Render a badge with the theme's primary color.
314    ///
315    /// Returns a [`Response`] carrying real `hovered` / `right_clicked` state
316    /// for the badge's rect, so callers can attach `.on_hover(...)` tooltips.
317    /// Prior to v0.21.0 this always returned [`Response::none()`]; statement-form
318    /// callers (`ui.badge("NEW");`) compile unchanged.
319    ///
320    /// # Example
321    ///
322    /// ```no_run
323    /// # slt::run(|ui: &mut slt::Context| {
324    /// let r = ui.badge("NEW");
325    /// if r.hovered { /* attach a tooltip */ }
326    /// # });
327    /// ```
328    pub fn badge(&mut self, label: &str) -> Response {
329        let theme = self.theme;
330        self.badge_colored(label, theme.primary)
331    }
332
333    /// Render a badge with a custom background color.
334    ///
335    /// Foreground is auto-selected for contrast via [`Color::contrast_fg`].
336    ///
337    /// Returns a [`Response`] carrying real `hovered` / `right_clicked` state
338    /// for the badge's rect, so callers can attach `.on_hover(...)` tooltips.
339    /// Prior to v0.21.0 this always returned [`Response::none()`]; statement-form
340    /// callers compile unchanged.
341    ///
342    /// # Example
343    ///
344    /// ```no_run
345    /// # use slt::Color;
346    /// # slt::run(|ui: &mut slt::Context| {
347    /// let r = ui.badge_colored("ALPHA", Color::Magenta);
348    /// if r.hovered { /* attach a tooltip */ }
349    /// # });
350    /// ```
351    pub fn badge_colored(&mut self, label: &str, color: Color) -> Response {
352        let fg = Color::contrast_fg(color);
353        let mut label_text = String::with_capacity(label.len() + 2);
354        label_text.push(' ');
355        label_text.push_str(label);
356        label_text.push(' ');
357        // Reserve the interaction slot *before* the text so the marker
358        // attaches to the badge's rect (same pattern as `spinner` / `gauge`).
359        let response = self.interaction();
360        self.text(label_text).fg(fg).bg(color);
361
362        response
363    }
364
365    /// Render a keyboard shortcut hint with reversed styling.
366    ///
367    /// Returns a [`Response`] carrying real `hovered` / `right_clicked` state
368    /// for the hint's rect, so callers can attach `.on_hover(...)` tooltips.
369    /// Prior to v0.21.0 this always returned [`Response::none()`]; statement-form
370    /// callers compile unchanged.
371    ///
372    /// # Example
373    ///
374    /// ```no_run
375    /// # slt::run(|ui: &mut slt::Context| {
376    /// ui.line(|ui| {
377    ///     ui.text("Quit: ");
378    ///     let r = ui.key_hint("Ctrl+Q");
379    ///     if r.hovered { /* attach a tooltip */ }
380    /// });
381    /// # });
382    /// ```
383    pub fn key_hint(&mut self, key: &str) -> Response {
384        let theme = self.theme;
385        let mut key_text = String::with_capacity(key.len() + 2);
386        key_text.push(' ');
387        key_text.push_str(key);
388        key_text.push(' ');
389        // Reserve the interaction slot *before* the text so the marker
390        // attaches to the hint's rect.
391        let response = self.interaction();
392        self.text(key_text).reversed().fg(theme.text_dim);
393
394        response
395    }
396
397    /// Render a label-value stat pair.
398    ///
399    /// Renders as a column: a dim label above a bold value. Pair multiple
400    /// stats in a [`row`](Self::row) for a compact dashboard strip.
401    ///
402    /// Returns a [`Response`] carrying real `hovered` / `clicked` /
403    /// `right_clicked` state for the stat's column rect, so callers can attach
404    /// `.on_hover(...)` tooltips. Prior to v0.21.0 this always returned
405    /// [`Response::none()`]; statement-form callers compile unchanged.
406    ///
407    /// # Example
408    ///
409    /// ```no_run
410    /// # slt::run(|ui: &mut slt::Context| {
411    /// ui.row(|ui| {
412    ///     let r = ui.stat("Users", "1.2k");
413    ///     if r.hovered { /* attach a tooltip */ }
414    ///     ui.stat("Revenue", "$8,420");
415    /// });
416    /// # });
417    /// ```
418    pub fn stat(&mut self, label: &str, value: &str) -> Response {
419        self.col(|ui| {
420            ui.text(label).dim();
421            ui.text(value).bold();
422        })
423    }
424
425    /// Render a stat pair with a custom value color.
426    ///
427    /// Returns a [`Response`] carrying real `hovered` / `clicked` /
428    /// `right_clicked` state for the stat's column rect, so callers can attach
429    /// `.on_hover(...)` tooltips. Prior to v0.21.0 this always returned
430    /// [`Response::none()`]; statement-form callers compile unchanged.
431    ///
432    /// # Example
433    ///
434    /// ```no_run
435    /// # use slt::Color;
436    /// # slt::run(|ui: &mut slt::Context| {
437    /// let r = ui.stat_colored("Errors", "0", Color::Green);
438    /// if r.hovered { /* attach a tooltip */ }
439    /// # });
440    /// ```
441    pub fn stat_colored(&mut self, label: &str, value: &str, color: Color) -> Response {
442        self.col(|ui| {
443            ui.text(label).dim();
444            ui.text(value).bold().fg(color);
445        })
446    }
447
448    /// Render a stat pair with an up/down trend arrow.
449    ///
450    /// The arrow color follows the theme: `success` for [`Trend::Up`],
451    /// `error` for [`Trend::Down`].
452    ///
453    /// Returns a [`Response`] carrying real `hovered` / `clicked` /
454    /// `right_clicked` state for the stat's column rect, so callers can attach
455    /// `.on_hover(...)` tooltips. Prior to v0.21.0 this always returned
456    /// [`Response::none()`]; statement-form callers compile unchanged.
457    ///
458    /// [`Trend::Up`]: crate::widgets::Trend::Up
459    /// [`Trend::Down`]: crate::widgets::Trend::Down
460    ///
461    /// # Example
462    ///
463    /// ```no_run
464    /// # use slt::widgets::Trend;
465    /// # slt::run(|ui: &mut slt::Context| {
466    /// let r = ui.stat_trend("MRR", "$24.5k", Trend::Up);
467    /// if r.hovered { /* attach a tooltip */ }
468    /// ui.stat_trend("Churn", "1.8%", Trend::Down);
469    /// # });
470    /// ```
471    pub fn stat_trend(
472        &mut self,
473        label: &str,
474        value: &str,
475        trend: crate::widgets::Trend,
476    ) -> Response {
477        let theme = self.theme;
478        let (arrow, color) = match trend {
479            crate::widgets::Trend::Up => ("↑", theme.success),
480            crate::widgets::Trend::Down => ("↓", theme.error),
481        };
482        self.col(|ui| {
483            ui.text(label).dim();
484            ui.line(|ui| {
485                ui.text(value).bold();
486                let mut arrow_text = String::with_capacity(1 + arrow.len());
487                arrow_text.push(' ');
488                arrow_text.push_str(arrow);
489                ui.text(arrow_text).fg(color);
490            });
491        })
492    }
493
494    /// Render a centered empty-state placeholder.
495    ///
496    /// Title is rendered prominently; description is dimmed below. Both are
497    /// centered horizontally and vertically inside the available space.
498    ///
499    /// Returns a [`Response`] carrying real `hovered` / `clicked` /
500    /// `right_clicked` state for the placeholder rect, so callers can attach
501    /// `.on_hover(...)` tooltips. Prior to v0.21.0 this always returned
502    /// [`Response::none()`]; statement-form callers compile unchanged.
503    ///
504    /// # Example
505    ///
506    /// ```no_run
507    /// # let items: Vec<&str> = vec![];
508    /// # slt::run(|ui: &mut slt::Context| {
509    /// if items.is_empty() {
510    ///     ui.empty_state("No items yet", "Press 'a' to add one");
511    /// }
512    /// # });
513    /// ```
514    pub fn empty_state(&mut self, title: &str, description: &str) -> Response {
515        self.container().center().col(|ui| {
516            ui.text(title).align(Align::Center);
517            ui.text(description).dim().align(Align::Center);
518        })
519    }
520
521    /// Render a centered empty-state placeholder with an action button.
522    ///
523    /// Returns a [`Response`] whose `clicked` field is `true` on the frame
524    /// the action button is activated. As of v0.21.0 the response also carries
525    /// real `hovered` / `right_clicked` state (and the laid-out `rect`) for the
526    /// placeholder area, so callers can attach `.on_hover(...)` tooltips. The
527    /// `clicked` / `changed` fields still track the action button specifically,
528    /// not the whole placeholder.
529    ///
530    /// # Example
531    ///
532    /// ```no_run
533    /// # let items: Vec<&str> = vec![];
534    /// # slt::run(|ui: &mut slt::Context| {
535    /// if items.is_empty() {
536    ///     let r = ui.empty_state_action("No items yet", "Get started", "Add first item");
537    ///     if r.clicked {
538    ///         // open create flow
539    ///     }
540    /// }
541    /// # });
542    /// ```
543    pub fn empty_state_action(
544        &mut self,
545        title: &str,
546        description: &str,
547        action_label: &str,
548    ) -> Response {
549        let mut clicked = false;
550        // The container response carries hover / right-click / rect for the
551        // whole placeholder area; `clicked` still tracks the action button.
552        let mut response = self.container().center().col(|ui| {
553            ui.text(title).align(Align::Center);
554            ui.text(description).dim().align(Align::Center);
555            if ui.button(action_label).clicked {
556                clicked = true;
557            }
558        });
559
560        response.clicked = clicked;
561        response.changed = clicked;
562        response
563    }
564
565    /// Begin building a syntax-highlighted code block.
566    ///
567    /// Chain `.lang(...)` for language-aware highlighting and `.numbered()`
568    /// for a line-number gutter. The returned [`CodeBlock`] auto-renders when
569    /// dropped, so a bare `ui.code_block(code);` produces a default block.
570    /// Call `.show()` (instead of dropping) to capture the [`Response`].
571    ///
572    /// This is the consuming-builder shape shared with [`Context::gauge`] /
573    /// [`Context::breadcrumb`] — see [API_DESIGN.md](https://github.com/subinium/superlighttui/blob/main/docs/API_DESIGN.md) Rule 1.
574    ///
575    /// # Example
576    ///
577    /// ```no_run
578    /// # slt::run(|ui: &mut slt::Context| {
579    /// ui.code_block("let x = 1;");
580    /// let r = ui.code_block("fn main() {}").lang("rust").numbered().show();
581    /// if r.hovered { /* attach tooltip */ }
582    /// # });
583    /// ```
584    pub fn code_block<'a>(&'a mut self, code: &'a str) -> CodeBlock<'a> {
585        CodeBlock::new(self, code)
586    }
587
588    /// Render a code block with language-aware syntax highlighting.
589    #[deprecated(since = "0.21.0", note = "use `code_block(code).lang(lang)`")]
590    pub fn code_block_lang(&mut self, code: &str, lang: &str) -> Response {
591        render_code_block(self, code, lang, false)
592    }
593
594    /// Render a code block with line numbers and keyword highlighting.
595    #[deprecated(since = "0.21.0", note = "use `code_block(code).numbered()`")]
596    pub fn code_block_numbered(&mut self, code: &str) -> Response {
597        render_code_block(self, code, "", true)
598    }
599
600    /// Render a code block with line numbers and language-aware highlighting.
601    #[deprecated(
602        since = "0.21.0",
603        note = "use `code_block(code).lang(lang).numbered()`"
604    )]
605    pub fn code_block_numbered_lang(&mut self, code: &str, lang: &str) -> Response {
606        render_code_block(self, code, lang, true)
607    }
608}
609
610/// Syntax-highlighted code block builder. Auto-renders on `Drop`.
611///
612/// Constructed via [`Context::code_block`]. Chain `.lang(...)` for
613/// language-aware highlighting and `.numbered()` for a line-number gutter.
614/// Drop the value to render without capturing a response, or call
615/// [`Self::show`] to render and obtain a [`Response`].
616///
617/// Consuming-builder shape, mirroring [`Gauge`](super::Gauge) /
618/// [`Breadcrumb`]: `Drop` is intentional so `ui.code_block(code);` is the
619/// idiomatic form when the response isn't needed (egui's `ui.add(...)` idiom).
620pub struct CodeBlock<'a> {
621    ctx: Option<&'a mut Context>,
622    code: &'a str,
623    lang: &'a str,
624    numbered: bool,
625}
626
627impl<'a> CodeBlock<'a> {
628    fn new(ctx: &'a mut Context, code: &'a str) -> Self {
629        Self {
630            ctx: Some(ctx),
631            code,
632            lang: "",
633            numbered: false,
634        }
635    }
636
637    /// Set the language for syntax highlighting (e.g. `"rust"`). Empty string
638    /// (the default) falls back to keyword-based highlighting.
639    pub fn lang(mut self, lang: &'a str) -> Self {
640        self.lang = lang;
641        self
642    }
643
644    /// Enable the line-number gutter.
645    pub fn numbered(mut self) -> Self {
646        self.numbered = true;
647        self
648    }
649
650    /// Render now and return the [`Response`].
651    pub fn show(mut self) -> Response {
652        // SAFETY: ctx is Some until Drop runs; show consumes self before Drop.
653        let ctx = self.ctx.take().expect("CodeBlock::show called twice");
654        render_code_block(ctx, self.code, self.lang, self.numbered)
655    }
656}
657
658impl Drop for CodeBlock<'_> {
659    fn drop(&mut self) {
660        if let Some(ctx) = self.ctx.take() {
661            let _ = render_code_block(ctx, self.code, self.lang, self.numbered);
662        }
663    }
664}
665
666/// Internal code-block rendering shared by the [`CodeBlock`] builder and the
667/// deprecated `code_block_*` aliases. Folds the language-aware and
668/// line-numbered paths on the `numbered` flag — no behavior change versus the
669/// previous separate `code_block_lang` / `code_block_numbered_lang` bodies.
670fn render_code_block(ctx: &mut Context, code: &str, lang: &str, numbered: bool) -> Response {
671    let theme = ctx.theme;
672    let pad = theme.spacing.xs();
673    let highlighted: Option<Vec<Vec<(String, Style)>>> =
674        crate::syntax::highlight_code(code, lang, &theme);
675
676    if numbered {
677        let lines: Vec<&str> = code.lines().collect();
678        let gutter_w = (lines.len().max(1).ilog10() + 1) as usize;
679        let _ = ctx
680            .bordered(Border::Rounded)
681            .bg(theme.surface)
682            .p(pad)
683            .col(|ui| {
684                if let Some(ref hl_lines) = highlighted {
685                    for (i, segs) in hl_lines.iter().enumerate() {
686                        ui.line(|ui| {
687                            ui.text(format!("{:>gutter_w$} │ ", i + 1))
688                                .fg(theme.text_dim);
689                            for (text, style) in segs {
690                                ui.styled(text, *style);
691                            }
692                        });
693                    }
694                } else {
695                    for (i, line) in lines.iter().enumerate() {
696                        ui.line(|ui| {
697                            ui.text(format!("{:>gutter_w$} │ ", i + 1))
698                                .fg(theme.text_dim);
699                            render_highlighted_line(ui, line);
700                        });
701                    }
702                }
703            });
704    } else {
705        let _ = ctx
706            .bordered(Border::Rounded)
707            .bg(theme.surface)
708            .p(pad)
709            .col(|ui| {
710                if let Some(ref lines) = highlighted {
711                    render_tree_sitter_lines(ui, lines);
712                } else {
713                    for line in code.lines() {
714                        ui.line(|ui| render_highlighted_line(ui, line));
715                    }
716                }
717            });
718    }
719
720    Response::none()
721}
722
723/// Breadcrumb navigation bar builder. Auto-renders on `Drop`.
724///
725/// Constructed via [`Context::breadcrumb`]. Chain `.separator(s)` to override
726/// the default ` › ` separator and `.color(c)` to override the link color.
727/// Drop the value to render without capturing a response, or call
728/// [`Self::show`] to render and obtain a [`BreadcrumbResponse`].
729///
730/// `Drop` is intentional: `ui.breadcrumb(&["Home", "src"]).separator(" > ");`
731/// is the idiomatic form when the response isn't needed.
732pub struct Breadcrumb<'a> {
733    ctx: Option<&'a mut Context>,
734    segments: &'a [&'a str],
735    separator: &'a str,
736    color: Option<Color>,
737}
738
739impl<'a> Breadcrumb<'a> {
740    pub(super) fn new(ctx: &'a mut Context, segments: &'a [&'a str]) -> Self {
741        Self {
742            ctx: Some(ctx),
743            segments,
744            separator: " › ",
745            color: None,
746        }
747    }
748
749    /// Set the separator string between segments (default: ` › `).
750    pub fn separator(mut self, sep: &'a str) -> Self {
751        self.separator = sep;
752        self
753    }
754
755    /// Override the link (clickable segment) color. Defaults to `theme.primary`.
756    pub fn color(mut self, color: Color) -> Self {
757        self.color = Some(color);
758        self
759    }
760
761    /// Render now and return the [`BreadcrumbResponse`].
762    pub fn show(mut self) -> BreadcrumbResponse {
763        let ctx = self.ctx.take().expect("Breadcrumb::show called twice");
764        render_breadcrumb(ctx, self.segments, self.separator, self.color)
765    }
766}
767
768impl Drop for Breadcrumb<'_> {
769    fn drop(&mut self) {
770        if let Some(ctx) = self.ctx.take() {
771            let _ = render_breadcrumb(ctx, self.segments, self.separator, self.color);
772        }
773    }
774}
775
776fn render_breadcrumb(
777    ctx: &mut Context,
778    segments: &[&str],
779    separator: &str,
780    color_override: Option<Color>,
781) -> BreadcrumbResponse {
782    let theme = ctx.theme;
783    let last_idx = segments.len().saturating_sub(1);
784    let mut clicked_segment: Option<usize> = None;
785    let link_color = color_override.unwrap_or(theme.primary);
786
787    let response = ctx.row(|ui| {
788        for (i, segment) in segments.iter().enumerate() {
789            let is_last = i == last_idx;
790            if is_last {
791                ui.text(*segment).bold();
792            } else {
793                let focused = ui.register_focusable();
794                let resp = ui.interaction();
795                let activated = resp.clicked || ui.consume_activation_keys(focused);
796                let color = if resp.hovered || focused {
797                    theme.accent
798                } else {
799                    link_color
800                };
801                ui.text(*segment).fg(color).underline();
802                if activated {
803                    clicked_segment = Some(i);
804                }
805                ui.text(separator).dim();
806            }
807        }
808    });
809
810    BreadcrumbResponse {
811        response,
812        clicked_segment,
813    }
814}
815
816#[cfg(test)]
817mod code_block_tests {
818    use crate::test_utils::TestBackend;
819    use crate::widgets::AlertLevel;
820
821    #[test]
822    fn code_block_builder_renders_lang_and_gutter() {
823        let mut tb = TestBackend::new(40, 8);
824        tb.render(|ui| {
825            let _ = ui.code_block("let x = 1;").lang("rust").numbered().show();
826        });
827        tb.assert_contains("let");
828        // Line-number gutter from the numbered path (`status.rs` render).
829        tb.assert_contains("1 │");
830    }
831
832    #[test]
833    fn code_block_default_drop_renders() {
834        // Bare drop-render (no chain) must produce the same content as `.show()`.
835        let mut tb_drop = TestBackend::new(40, 8);
836        tb_drop.render(|ui| {
837            ui.code_block("a\nb");
838        });
839        let mut tb_show = TestBackend::new(40, 8);
840        tb_show.render(|ui| {
841            let _ = ui.code_block("a\nb").show();
842        });
843        assert_eq!(tb_drop.to_string(), tb_show.to_string());
844    }
845
846    #[test]
847    fn code_block_deprecated_alias_byte_identical() {
848        let code = "fn main() {}\nlet y = 2;";
849        let mut tb_builder = TestBackend::new(40, 8);
850        tb_builder.render(|ui| {
851            let _ = ui.code_block(code).lang("rust").numbered().show();
852        });
853        let mut tb_alias = TestBackend::new(40, 8);
854        tb_alias.render(|ui| {
855            #[allow(deprecated)]
856            let _ = ui.code_block_numbered_lang(code, "rust");
857        });
858        assert_eq!(
859            tb_builder.to_string(),
860            tb_alias.to_string(),
861            "deprecated alias must be behavior-preserving"
862        );
863    }
864
865    #[test]
866    fn alert_message_first_then_level() {
867        // Regression guard for the API_DESIGN.md arg-order drift: `(message,
868        // level)` is the shipped order. Compiles == doc order matches code.
869        let mut tb = TestBackend::new(40, 5);
870        tb.render(|ui| {
871            let _ = ui.alert("Disk full", AlertLevel::Error);
872        });
873        tb.assert_contains("Disk full");
874    }
875}