Skip to main content

logicaffeine_web/ui/components/
logic_output.rs

1//! First-Order Logic output display component.
2//!
3//! Renders compiled logic expressions with syntax highlighting. Supports multiple
4//! output formats (Unicode, SimpleFOL, LaTeX, Kripke) and multiple readings for
5//! ambiguous sentences.
6//!
7//! # Props
8//!
9//! - `logic` - Primary Unicode output
10//! - `simple_logic` - SimpleFOL format output
11//! - `kripke_logic` - Kripke semantics output
12//! - `readings` - Multiple readings for ambiguous sentences
13//! - `error` - Optional error message
14//! - `format` - Output format selection
15//!
16//! # Syntax Highlighting
17//!
18//! Different logical elements are color-coded:
19//! - Quantifiers (∀, ∃): purple
20//! - Connectives (∧, ∨, →, ↔, ¬): purple
21//! - Variables (lowercase): blue
22//! - Predicates (uppercase words): green
23//! - Constants (capitalized names): yellow
24
25use dioxus::prelude::*;
26
27const OUTPUT_STYLE: &str = r#"
28.logic-output-container {
29    display: flex;
30    flex-direction: column;
31    padding: var(--studio-inset, 16px);
32}
33
34.reading-selector {
35    display: flex;
36    align-items: center;
37    gap: 8px;
38    margin-bottom: 12px;
39    flex-wrap: wrap;
40}
41
42.reading-selector span {
43    color: #888;
44    font-size: 14px;
45}
46
47.reading-btn {
48    width: 28px;
49    height: 28px;
50    border-radius: 6px;
51    border: 1px solid rgba(255, 255, 255, 0.2);
52    background: rgba(255, 255, 255, 0.08);
53    color: #888;
54    font-size: 12px;
55    cursor: pointer;
56    transition: all 0.2s ease;
57}
58
59.reading-btn:hover {
60    background: rgba(255, 255, 255, 0.15);
61    color: #e8e8e8;
62}
63
64.reading-btn.active {
65    background: #667eea;
66    border-color: transparent;
67    color: white;
68}
69
70/* The formula sits on the panel's own surface, set like the code editor's text. */
71.logic-display {
72    font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
73    font-size: 14px;
74    line-height: 1.6;
75    color: #e8eaed;
76    overflow: auto;
77    -webkit-overflow-scrolling: touch;
78    word-break: break-word;
79}
80
81.logic-display.empty {
82    color: #666;
83    font-style: italic;
84}
85
86.logic-display.error {
87    color: #e06c75;
88}
89
90.logic-quantifier { color: #c678dd; font-weight: 500; }
91.logic-variable { color: #61afef; }
92.logic-predicate { color: #98c379; }
93.logic-connective { color: #c678dd; }
94.logic-constant { color: #e5c07b; }
95.logic-paren { color: #abb2bf; }
96
97/* Mobile optimizations */
98@media (max-width: 768px) {
99    .logic-output-container {
100        padding: var(--studio-inset, 12px);
101    }
102
103    .reading-selector {
104        gap: 6px;
105        margin-bottom: 10px;
106    }
107
108    .reading-selector span {
109        font-size: 13px;
110    }
111
112    /* Touch-friendly reading buttons */
113    .reading-btn {
114        width: 44px;
115        height: 44px;
116        font-size: 14px;
117        border-radius: 8px;
118        -webkit-tap-highlight-color: transparent;
119    }
120
121    .reading-btn:active {
122        transform: scale(0.95);
123    }
124
125}
126
127/* Extra small screens */
128@media (max-width: 480px) {
129    .reading-btn {
130        width: 40px;
131        height: 40px;
132        font-size: 13px;
133    }
134
135    .logic-display {
136        font-size: 15px;
137        padding: 14px;
138    }
139}
140"#;
141
142#[derive(Clone, Copy, PartialEq, Default)]
143pub enum OutputFormat {
144    #[default]
145    Unicode,
146    SimpleFOL,
147    LaTeX,
148    Kripke, // Deep/Kripke semantics
149}
150
151#[component]
152pub fn LogicOutput(
153    logic: Option<String>,
154    simple_logic: Option<String>,
155    kripke_logic: Option<String>, // Deep/Kripke semantics output (single)
156    readings: Vec<String>,
157    simple_readings: Vec<String>, // SimpleFOL readings (deduplicated)
158    kripke_readings: Vec<String>, // Deep/Kripke readings for ambiguous sentences
159    error: Option<String>,
160    format: OutputFormat,
161) -> Element {
162    let mut current_reading = use_signal(|| 0usize);
163
164    // Use format-appropriate readings
165    let active_readings = match format {
166        OutputFormat::Kripke => &kripke_readings,
167        OutputFormat::SimpleFOL => &simple_readings,
168        _ => &readings,
169    };
170
171    let total_readings = active_readings.len().max(1);
172    let display_logic = if !active_readings.is_empty() {
173        let idx = (*current_reading.read()).min(active_readings.len().saturating_sub(1));
174        Some(active_readings.get(idx).cloned().unwrap_or_default())
175    } else if format == OutputFormat::Kripke {
176        kripke_logic.clone()
177    } else {
178        logic.clone()
179    };
180
181    let formatted_output = match format {
182        OutputFormat::LaTeX => display_logic
183            .as_ref()
184            .map(|l| convert_to_latex(l))
185            .unwrap_or_default(),
186        _ => display_logic.clone().unwrap_or_default(),
187    };
188
189    rsx! {
190        style { "{OUTPUT_STYLE}" }
191
192        div { class: "logic-output-container",
193            if total_readings > 1 {
194                div { class: "reading-selector",
195                    span { "Reading" }
196                    for i in 0..total_readings {
197                        button {
198                            class: if *current_reading.read() == i { "reading-btn active" } else { "reading-btn" },
199                            onclick: move |_| current_reading.set(i),
200                            "{i + 1}"
201                        }
202                    }
203                    span { "of {total_readings}" }
204                }
205            }
206
207            if let Some(err) = &error {
208                div { class: "logic-display error",
209                    "{err}"
210                }
211            } else if formatted_output.is_empty() {
212                div { class: "logic-display empty",
213                    "Type a sentence to see its logical form..."
214                }
215            } else {
216                div { class: "logic-display",
217                    dangerous_inner_html: highlight_logic(&formatted_output)
218                }
219            }
220        }
221    }
222}
223
224fn convert_to_latex(unicode: &str) -> String {
225    unicode
226        .replace('\u{2200}', "\\forall ")
227        .replace('\u{2203}', "\\exists ")
228        .replace('\u{00AC}', "\\neg ")
229        .replace('\u{2227}', "\\land ")
230        .replace('\u{2228}', "\\lor ")
231        .replace('\u{2192}', "\\rightarrow ")
232        .replace('\u{2194}', "\\leftrightarrow ")
233        .replace('\u{22A5}', "\\bot ")
234        .replace('\u{22A4}', "\\top ")
235}
236
237pub fn highlight_logic(logic: &str) -> String {
238    let mut result = String::new();
239    let mut chars = logic.chars().peekable();
240
241    while let Some(c) = chars.next() {
242        match c {
243            '\u{2200}' | '\u{2203}' => {
244                result.push_str(&format!(r#"<span class="logic-quantifier">{}</span>"#, c));
245            }
246            '\u{00AC}' | '\u{2227}' | '\u{2228}' | '\u{2192}' | '\u{2194}' => {
247                result.push_str(&format!(r#"<span class="logic-connective">{}</span>"#, c));
248            }
249            '(' | ')' | '[' | ']' => {
250                result.push_str(&format!(r#"<span class="logic-paren">{}</span>"#, c));
251            }
252            'a'..='z' if chars.peek().map(|n| !n.is_alphabetic()).unwrap_or(true) => {
253                result.push_str(&format!(r#"<span class="logic-variable">{}</span>"#, c));
254            }
255            'A'..='Z' => {
256                let mut word = String::from(c);
257                while let Some(&next) = chars.peek() {
258                    if next.is_alphanumeric() {
259                        word.push(chars.next().unwrap());
260                    } else {
261                        break;
262                    }
263                }
264                if word
265                    .chars()
266                    .next()
267                    .map(|c| c.is_uppercase())
268                    .unwrap_or(false)
269                    && word.len() > 1
270                    && word
271                        .chars()
272                        .skip(1)
273                        .all(|c| c.is_lowercase() || c.is_numeric())
274                {
275                    result.push_str(&format!(r#"<span class="logic-constant">{}</span>"#, word));
276                } else {
277                    result.push_str(&format!(r#"<span class="logic-predicate">{}</span>"#, word));
278                }
279            }
280            '\n' => result.push_str("<br>"),
281            _ => result.push(c),
282        }
283    }
284
285    result
286}