Skip to main content

logicaffeine_web/ui/components/
guide_code_block.rs

1//! Interactive code block component for the Programmer's Guide.
2//!
3//! Features:
4//! - The Studio's editor with the language server: highlighting, hovers, squiggles
5//! - Run button (Logic mode: FOL output, Imperative mode: interpreter, Web mode: the page
6//!   compiled to WebAssembly and shown live in a sandboxed frame)
7//! - Copy button
8//! - Reset button
9//! - Output panel
10
11use super::inline_editor::{InlineEditor, InlineEditorStyle};
12use crate::ui::pages::guide::content::{ExampleMode, Runnability};
13use crate::ui::pages::guide::theorem_verdict;
14use dioxus::prelude::*;
15use logicaffeine_compile::{compile_for_ui, compile_theorem_for_ui, interpret_for_ui};
16
17const CODE_BLOCK_STYLE: &str = r#"
18.guide-code-block {
19    border-radius: 16px;
20    border: 1px solid rgba(255,255,255,0.10);
21    background: rgba(0,0,0,0.35);
22    overflow: hidden;
23    margin: 20px 0;
24    box-shadow: 0 8px 32px rgba(0,0,0,0.3);
25}
26
27.guide-code-header {
28    display: flex;
29    flex-wrap: wrap;
30    justify-content: space-between;
31    align-items: center;
32    gap: 10px;
33    padding: 12px 16px;
34    background: rgba(255,255,255,0.04);
35    border-bottom: 1px solid rgba(255,255,255,0.08);
36}
37
38.guide-code-label {
39    display: flex;
40    flex-wrap: wrap;
41    align-items: center;
42    gap: 6px 10px;
43}
44
45.guide-code-title {
46    font-size: 13px;
47    font-weight: 600;
48    color: rgba(229,231,235,0.9);
49}
50
51.guide-code-mode {
52    font-size: 11px;
53    padding: 4px 10px;
54    border-radius: 999px;
55    font-weight: 600;
56    text-transform: uppercase;
57    letter-spacing: 0.5px;
58}
59
60.guide-code-mode.logic {
61    background: rgba(167,139,250,0.2);
62    color: #a78bfa;
63    border: 1px solid rgba(167,139,250,0.3);
64}
65
66.guide-code-mode.imperative {
67    background: rgba(34,197,94,0.2);
68    color: #22c55e;
69    border: 1px solid rgba(34,197,94,0.3);
70}
71
72.guide-code-actions {
73    display: flex;
74    flex-wrap: wrap;
75    gap: 8px;
76}
77
78.guide-code-btn {
79    padding: 8px 14px;
80    border-radius: 8px;
81    border: 1px solid rgba(255,255,255,0.12);
82    background: rgba(255,255,255,0.06);
83    color: rgba(229,231,235,0.8);
84    font-size: 12px;
85    font-weight: 600;
86    cursor: pointer;
87    transition: all 0.2s ease;
88    display: flex;
89    align-items: center;
90    gap: 6px;
91}
92
93.guide-code-btn:hover {
94    background: rgba(255,255,255,0.10);
95    border-color: rgba(255,255,255,0.20);
96    color: #fff;
97}
98
99.guide-code-btn:active {
100    transform: scale(0.97);
101}
102
103.guide-code-btn.primary {
104    background: linear-gradient(135deg, rgba(96,165,250,0.9), rgba(167,139,250,0.9));
105    border-color: rgba(255,255,255,0.2);
106    color: #060814;
107}
108
109.guide-code-btn.primary:hover {
110    background: linear-gradient(135deg, #60a5fa, #a78bfa);
111}
112
113.guide-code-btn.running {
114    opacity: 0.7;
115    cursor: wait;
116}
117
118.guide-code-editor {
119    position: relative;
120}
121
122.guide-code-output {
123    border-top: 1px solid rgba(255,255,255,0.08);
124    background: rgba(0,0,0,0.25);
125}
126
127.guide-code-output-header {
128    display: flex;
129    align-items: center;
130    justify-content: space-between;
131    padding: 10px 16px;
132    font-size: 11px;
133    font-weight: 600;
134    text-transform: uppercase;
135    letter-spacing: 0.5px;
136    color: rgba(229,231,235,0.5);
137    border-bottom: 1px solid rgba(255,255,255,0.06);
138}
139
140.guide-code-output-content {
141    padding: 16px;
142    font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Monaco, monospace;
143    font-size: 14px;
144    line-height: 1.6;
145    white-space: pre-wrap;
146    word-break: break-word;
147}
148
149.guide-code-output-content.success {
150    color: #a78bfa;
151}
152
153.guide-code-output-content.error {
154    color: #f87171;
155}
156
157.guide-code-output-content.info {
158    color: rgba(229,231,235,0.7);
159}
160
161.guide-code-mode.web {
162    background: rgba(52,211,153,0.15);
163    color: #34d399;
164    border: 1px solid rgba(52,211,153,0.3);
165}
166
167.guide-code-preview {
168    display: block;
169    width: 100%;
170    height: 320px;
171    border: 0;
172    background: #faf9f5;
173}
174
175.guide-code-copied {
176    position: absolute;
177    top: 50%;
178    left: 50%;
179    transform: translate(-50%, -50%);
180    padding: 8px 16px;
181    background: rgba(34,197,94,0.9);
182    color: #fff;
183    border-radius: 8px;
184    font-size: 13px;
185    font-weight: 600;
186    animation: fadeInOut 1.5s ease forwards;
187    pointer-events: none;
188}
189
190@keyframes fadeInOut {
191    0% { opacity: 0; transform: translate(-50%, -50%) scale(0.9); }
192    15% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
193    85% { opacity: 1; }
194    100% { opacity: 0; }
195}
196
197.guide-code-placeholder {
198    padding: 24px 16px;
199    text-align: center;
200    color: rgba(229,231,235,0.4);
201    font-size: 13px;
202}
203
204.guide-code-compiled-pill {
205    font-size: 11px;
206    padding: 4px 10px;
207    border-radius: 999px;
208    font-weight: 600;
209    text-transform: uppercase;
210    letter-spacing: 0.5px;
211    background: rgba(251,191,36,0.15);
212    color: #fbbf24;
213    border: 1px solid rgba(251,191,36,0.3);
214    cursor: help;
215    white-space: nowrap;
216}
217"#;
218
219#[derive(Props, Clone, PartialEq)]
220pub struct GuideCodeBlockProps {
221    pub id: String,
222    pub label: String,
223    pub mode: ExampleMode,
224    pub runnability: Runnability,
225    pub expected_output: Option<String>,
226    /// Predict-first (Muller/POE): start with the locked expectation HIDDEN
227    /// and ask the reader to commit to a prediction before revealing.
228    pub predict: bool,
229    pub initial_code: String,
230}
231
232#[component]
233pub fn GuideCodeBlock(props: GuideCodeBlockProps) -> Element {
234    let mut code = use_signal(|| props.initial_code.clone());
235    let mut output = use_signal(String::new);
236    let mut output_type = use_signal(|| "info".to_string());
237    let mut is_running = use_signal(|| false);
238    let mut show_copied = use_signal(|| false);
239    let mut has_run = use_signal(|| false);
240    let mut predict_hidden = use_signal(|| props.predict);
241    let mut preview = use_signal(String::new);
242
243    let initial_code = props.initial_code.clone();
244    let mode = props.mode;
245    let id = props.id.clone();
246
247    // Run handler
248    let handle_run = move |_| {
249        is_running.set(true);
250        has_run.set(true);
251
252        let current_code = code.read().clone();
253
254        match mode {
255            ExampleMode::Logic => {
256                // Use compile_for_ui for Logic mode
257                let result = compile_for_ui(&current_code);
258                if let Some(logic) = result.logic {
259                    output.set(logic);
260                    output_type.set("success".to_string());
261                } else if let Some(err) = result.error {
262                    output.set(err);
263                    output_type.set("error".to_string());
264                } else {
265                    output.set("No output".to_string());
266                    output_type.set("info".to_string());
267                }
268            }
269            ExampleMode::Theorem => {
270                // The proof engine + CoC kernel run in-process — the verdict
271                // is the output.
272                let result = compile_theorem_for_ui(&current_code);
273                match theorem_verdict(&result) {
274                    Ok(verdict) => {
275                        output.set(verdict);
276                        output_type.set("success".to_string());
277                    }
278                    Err(err) => {
279                        output.set(err);
280                        output_type.set("error".to_string());
281                    }
282                }
283            }
284            ExampleMode::Web => {
285                // The Studio's Web preview: the page compiled to WebAssembly here, in the browser,
286                // and handed to a sandboxed frame as its whole document. A build error becomes the
287                // themed overlay with the offending line, in the same frame.
288                let doc = match logicaffeine_compile::web_host::assemble_preview(&current_code) {
289                    Ok(srcdoc) => {
290                        output_type.set("success".to_string());
291                        srcdoc
292                    }
293                    Err(pe) => {
294                        output_type.set("error".to_string());
295                        logicaffeine_compile::web_host::error_overlay_html(&pe, &current_code, "")
296                    }
297                };
298                preview.set(doc);
299            }
300            ExampleMode::Imperative => {
301                // Phase 55: interpret_for_ui is now async for VFS support
302                spawn(async move {
303                    let result = interpret_for_ui(&current_code).await;
304                    if let Some(err) = result.error {
305                        output.set(err);
306                        output_type.set("error".to_string());
307                    } else if result.lines.is_empty() {
308                        output.set("(no output)".to_string());
309                        output_type.set("info".to_string());
310                    } else {
311                        output.set(result.lines.join("\n"));
312                        output_type.set("success".to_string());
313                    }
314                    is_running.set(false);
315                });
316                return;
317            }
318        }
319
320        is_running.set(false);
321    };
322
323    // Copy handler
324    let handle_copy = move |_| {
325        let code_to_copy = code.read().clone();
326
327        #[cfg(target_arch = "wasm32")]
328        {
329            if let Some(window) = web_sys::window() {
330                let clipboard = window.navigator().clipboard();
331                let _ = clipboard.write_text(&code_to_copy);
332                show_copied.set(true);
333
334                // Reset after animation
335                spawn(async move {
336                    gloo_timers::future::TimeoutFuture::new(1500).await;
337                    show_copied.set(false);
338                });
339            }
340        }
341
342        #[cfg(not(target_arch = "wasm32"))]
343        {
344            let _ = code_to_copy;
345            show_copied.set(true);
346        }
347    };
348
349    // Reset handler
350    let handle_reset = {
351        let initial = initial_code.clone();
352        move |_| {
353            code.set(initial.clone());
354            output.set(String::new());
355            preview.set(String::new());
356            has_run.set(false);
357        }
358    };
359
360    let mode_class = match mode {
361        ExampleMode::Logic | ExampleMode::Theorem => "logic",
362        ExampleMode::Imperative => "imperative",
363        ExampleMode::Web => "web",
364    };
365
366    let mode_label = match mode {
367        ExampleMode::Logic => "Logic",
368        ExampleMode::Theorem => "Prove",
369        ExampleMode::Imperative => "Run",
370        ExampleMode::Web => "Open page",
371    };
372
373    // The runnability declaration drives the affordance: a CompiledOnly example
374    // gets a pill carrying its reason instead of a Run button that would fail.
375    let compiled_reason: Option<&'static str> = match props.runnability {
376        Runnability::CompiledOnly { reason } => Some(reason),
377        _ => None,
378    };
379
380    // Before the first run, an example with locked content shows it up front:
381    // the expected output (Playground) or the expected diagnostic (ExpectedError).
382    let prepopulated: Option<(&'static str, String, &'static str)> = if *has_run.read() {
383        None
384    } else {
385        match props.runnability {
386            Runnability::Playground => props
387                .expected_output
388                .clone()
389                .map(|text| ("Expected output", text, "info")),
390            Runnability::ExpectedError { message } => {
391                Some(("Expected error", message.to_string(), "error"))
392            }
393            Runnability::CompiledOnly { .. } => None,
394        }
395    };
396
397    rsx! {
398        style { "{CODE_BLOCK_STYLE}" }
399        InlineEditorStyle {}
400
401        div {
402            class: "guide-code-block",
403            id: "{id}",
404
405            // Header
406            div { class: "guide-code-header",
407                div { class: "guide-code-label",
408                    span { class: "guide-code-title", "{props.label}" }
409                    span { class: "guide-code-mode {mode_class}",
410                        match mode {
411                            ExampleMode::Logic => "Logic Mode",
412                            ExampleMode::Theorem => "Theorem",
413                            ExampleMode::Imperative => "Imperative",
414                            ExampleMode::Web => "Web page",
415                        }
416                    }
417                }
418
419                div { class: "guide-code-actions",
420                    if let Some(reason) = compiled_reason {
421                        a {
422                            class: "guide-code-compiled-pill",
423                            title: "{reason}",
424                            href: "/guide#appendix-runnability",
425                            "Compiled — run with largo"
426                        }
427                    } else {
428                        button {
429                            class: if *is_running.read() { "guide-code-btn primary running" } else { "guide-code-btn primary" },
430                            onclick: handle_run,
431                            disabled: *is_running.read(),
432                            if *is_running.read() {
433                                "Running..."
434                            } else {
435                                "{mode_label}"
436                            }
437                        }
438                    }
439                    button {
440                        class: "guide-code-btn",
441                        onclick: handle_copy,
442                        "Copy"
443                    }
444                    button {
445                        class: "guide-code-btn",
446                        onclick: handle_reset,
447                        "Reset"
448                    }
449                }
450            }
451
452            // Editor
453            div { class: "guide-code-editor",
454                InlineEditor {
455                    value: code.read().clone(),
456                    on_change: move |v| code.set(v),
457                    language: mode.language(),
458                }
459
460                if *show_copied.read() {
461                    div { class: "guide-code-copied", "Copied!" }
462                }
463            }
464
465            // Output: the live page for a web example; the actual output after a run; the locked
466            // expectation before it.
467            if *has_run.read() && mode == ExampleMode::Web {
468                div { class: "guide-code-output",
469                    div { class: "guide-code-output-header",
470                        span { "Page" }
471                    }
472                    iframe {
473                        class: "guide-code-preview",
474                        srcdoc: "{preview}",
475                        "sandbox": "allow-scripts",
476                    }
477                }
478            } else if *has_run.read() {
479                div { class: "guide-code-output",
480                    div { class: "guide-code-output-header",
481                        span { "Output" }
482                    }
483                    div {
484                        class: "guide-code-output-content {output_type}",
485                        "{output}"
486                    }
487                }
488            } else if let Some((header, text, kind)) = prepopulated {
489                div { class: "guide-code-output",
490                    div { class: "guide-code-output-header",
491                        // While hidden, the header asks for a committed
492                        // prediction instead of naming the answer's category.
493                        if *predict_hidden.read() {
494                            span {
495                                match (props.runnability, mode) {
496                                    (Runnability::ExpectedError { .. }, _) => "What error do you expect?",
497                                    (_, ExampleMode::Logic) => "What FOL does this produce?",
498                                    (_, ExampleMode::Theorem) => "What verdict do you expect?",
499                                    (_, ExampleMode::Imperative) => "What will this print?",
500                                    (_, ExampleMode::Web) => "What will this page show?",
501                                }
502                            }
503                        } else {
504                            span { "{header}" }
505                        }
506                        // Predict-the-output: hide the answer, guess, reveal.
507                        button {
508                            class: "guide-predict-toggle",
509                            style: "background: none; border: 1px solid rgba(255,255,255,0.15); border-radius: 6px; color: rgba(229,231,235,0.6); font-size: 10px; padding: 2px 8px; cursor: pointer; text-transform: none; letter-spacing: 0;",
510                            onclick: move |_| { let v = *predict_hidden.read(); predict_hidden.set(!v); },
511                            if *predict_hidden.read() { "Reveal" } else { "Hide & predict" }
512                        }
513                    }
514                    if !*predict_hidden.read() {
515                        div {
516                            class: "guide-code-output-content {kind}",
517                            "{text}"
518                        }
519                    }
520                }
521            }
522        }
523    }
524}