Skip to main content

egui_cha_ds/atoms/core/
code.rs

1//! Code/CodeBlock atom
2//!
3//! Theme-aware code display components with proper scaling support.
4
5use crate::theme::Theme;
6use egui::{FontId, RichText, Ui};
7
8/// Inline code styling
9///
10/// Uses theme for colors, spacing, and font sizing.
11pub struct Code<'a> {
12    text: &'a str,
13}
14
15impl<'a> Code<'a> {
16    pub fn new(text: &'a str) -> Self {
17        Self { text }
18    }
19
20    pub fn show(self, ui: &mut Ui) {
21        let theme = Theme::current(ui.ctx());
22
23        // Use tertiary background for inline code
24        let bg = theme.bg_tertiary;
25        // Use state_danger for code highlight (reddish)
26        let fg = theme.state_danger;
27
28        egui::Frame::new()
29            .fill(bg)
30            .corner_radius(theme.radius_sm)
31            .inner_margin(egui::Margin::symmetric((theme.spacing_xs * 0.75) as i8, 1))
32            .show(ui, |ui| {
33                ui.label(
34                    RichText::new(self.text)
35                        .color(fg)
36                        .font(FontId::monospace(theme.font_size_sm)),
37                );
38            });
39    }
40}
41
42/// Code block for multi-line code
43///
44/// Uses theme for colors, spacing, borders, and font sizing.
45pub struct CodeBlock<'a> {
46    code: &'a str,
47    language: Option<&'a str>,
48}
49
50impl<'a> CodeBlock<'a> {
51    pub fn new(code: &'a str) -> Self {
52        Self {
53            code,
54            language: None,
55        }
56    }
57
58    pub fn language(mut self, lang: &'a str) -> Self {
59        self.language = Some(lang);
60        self
61    }
62
63    pub fn show(self, ui: &mut Ui) {
64        let theme = Theme::current(ui.ctx());
65
66        // Use secondary background for code blocks
67        let bg = theme.bg_secondary;
68        // Use primary text for code content
69        let fg = theme.text_primary;
70        // Use border color from theme
71        let border = theme.border;
72
73        egui::Frame::new()
74            .fill(bg)
75            .stroke(egui::Stroke::new(theme.border_width, border))
76            .corner_radius(theme.radius_md)
77            .inner_margin(egui::Margin::same(theme.spacing_sm as i8))
78            .show(ui, |ui| {
79                // Language label
80                if let Some(lang) = self.language {
81                    ui.label(
82                        RichText::new(lang)
83                            .size(theme.font_size_xs)
84                            .color(theme.text_muted),
85                    );
86                    ui.add_space(theme.spacing_xs);
87                }
88
89                // Code content
90                ui.label(
91                    RichText::new(self.code)
92                        .color(fg)
93                        .font(FontId::monospace(theme.font_size_sm)),
94                );
95            });
96    }
97}