Skip to main content

logicaffeine_web/ui/pages/
studio.rs

1//! Studio page - multi-mode playground for Logic, Code, and Math.
2//!
3//! The main development environment with three modes:
4//!
5//! - **Logic Mode**: Parse English sentences to First-Order Logic with AST
6//!   visualization and proof checking
7//! - **Code Mode**: Write imperative LOGOS code with REPL execution and
8//!   Rust code generation
9//! - **Math Mode**: Define theorems and types with interactive proofs and
10//!   tactic guidance
11//!
12//! # Layout
13//!
14//! - **Left sidebar**: File browser with example files
15//! - **Center**: Live editor with syntax highlighting
16//! - **Right panel**: Context-sensitive output (FOL, AST, REPL, proofs)
17//!
18//! # Route
19//!
20//! Accessed via [`Route::Studio`](crate::ui::router::Route::Studio).
21
22use crate::ui::components::context_view::{ContextEntry, EntryKind};
23use crate::ui::components::logic_output::OutputFormat;
24use crate::ui::components::main_nav::{ActivePage, MainNav};
25use crate::ui::components::proof_panel::{ProofNode, ProofStatus};
26use crate::ui::fault::{contain, ActionFault};
27use crate::ui::pages::studio_files::examples_tree;
28#[cfg(target_arch = "wasm32")]
29use crate::ui::pages::studio_files::{example_text, load_dir_recursive, open_store, StudioFiles};
30#[cfg(target_arch = "wasm32")]
31use crate::ui::pages::studio_opening::Arrival;
32use crate::ui::pages::studio_opening::StudioOpening;
33use crate::ui::pages::studio_layout::MobileTab;
34use crate::ui::pages::studio_run;
35#[cfg(target_arch = "wasm32")]
36use crate::ui::pages::studio_workbench::WorkbenchState;
37use crate::ui::pages::studio_workbench::{use_workbench, Host, StoreNote, Workbench};
38use crate::ui::responsive::{MOBILE_BASE_STYLES, MOBILE_TAB_BAR_STYLES};
39use crate::ui::seo::{
40    breadcrumb_schema, organization_schema, pages as seo_pages, software_application_schema,
41    BreadcrumbItem, JsonLdMultiple, PageHead,
42};
43#[cfg(target_arch = "wasm32")]
44use crate::ui::state::StudioMode;
45use crate::ui::state::{FileNode, ReplLine};
46use dioxus::prelude::*;
47#[cfg(all(feature = "split", target_arch = "wasm32"))]
48use dioxus::wasm_split;
49use logicaffeine_compile::{CompileResult, ProofCompileResult, SolvedGrid, TheoremCompileResult};
50use logicaffeine_kernel::interface::Repl;
51use logicaffeine_proof::{hints::suggest_hint, DerivationTree, InferenceRule, ProofExpr};
52#[cfg(target_arch = "wasm32")]
53use logicaffeine_system::fs::{get_platform_vfs_with_fallback, Vfs, WebVfs};
54
55/// Parse math code into complete statements.
56///
57/// Handles both Coq-style (period-terminated) and Literate syntax (block-based):
58/// - `## To ...` blocks: collect header + all indented lines until non-indented line
59/// - `A X is either:` blocks: collect header + indented variants
60/// - Traditional commands: accumulate until period-terminator
61pub fn parse_math_statements(code: &str) -> Vec<String> {
62    let mut statements = Vec::new();
63    let lines: Vec<&str> = code.lines().collect();
64    let mut i = 0;
65
66    while i < lines.len() {
67        let line = lines[i];
68        let trimmed = line.trim();
69
70        // Skip empty lines and comments
71        if trimmed.is_empty() || trimmed.starts_with("--") {
72            i += 1;
73            continue;
74        }
75
76        // Check for Literate function definition: "## To ..."
77        if trimmed.starts_with("## To ") {
78            let mut block = String::new();
79            block.push_str(trimmed);
80            i += 1;
81
82            // Collect all indented lines (body of the function)
83            while i < lines.len() {
84                let next_line = lines[i];
85                let next_trimmed = next_line.trim();
86
87                // Empty lines within block are OK
88                if next_trimmed.is_empty() {
89                    i += 1;
90                    continue;
91                }
92
93                // Comments within block are skipped
94                if next_trimmed.starts_with("--") {
95                    i += 1;
96                    continue;
97                }
98
99                // Check if line is indented (part of block body)
100                // A line is indented if it starts with whitespace
101                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
102
103                // Also check if it's a continuation keyword (Consider, When, Yield)
104                let is_continuation = next_trimmed.starts_with("Consider ")
105                    || next_trimmed.starts_with("When ")
106                    || next_trimmed.starts_with("Yield ");
107
108                if is_indented || is_continuation {
109                    block.push(' ');
110                    block.push_str(next_trimmed);
111                    i += 1;
112                } else {
113                    // Non-indented, non-continuation line: end of block
114                    break;
115                }
116            }
117
118            statements.push(block);
119            continue;
120        }
121
122        // Check for Literate theorem: "## Theorem: ..."
123        // Collects header + Statement: + Proof: lines as one block
124        if trimmed.starts_with("## Theorem:") {
125            let mut block = String::new();
126            block.push_str(trimmed);
127            i += 1;
128
129            // Collect indented lines (Statement: and Proof:)
130            while i < lines.len() {
131                let next_line = lines[i];
132                let next_trimmed = next_line.trim();
133
134                // Empty lines within block are OK
135                if next_trimmed.is_empty() {
136                    i += 1;
137                    continue;
138                }
139
140                // Comments within block are skipped
141                if next_trimmed.starts_with("--") {
142                    i += 1;
143                    continue;
144                }
145
146                // Check if line is indented (part of theorem block)
147                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
148
149                // Also check for Statement: or Proof: keywords (may not be indented)
150                let is_theorem_part =
151                    next_trimmed.starts_with("Statement:") || next_trimmed.starts_with("Proof:");
152
153                if is_indented || is_theorem_part {
154                    block.push('\n');
155                    block.push_str(next_line);
156                    i += 1;
157
158                    // If we just added a Proof: line that ends with period, block is complete
159                    if next_trimmed.starts_with("Proof:") && next_trimmed.ends_with('.') {
160                        break;
161                    }
162                } else {
163                    // Non-indented, non-theorem-part line: end of block
164                    break;
165                }
166            }
167
168            statements.push(block);
169            continue;
170        }
171
172        // Check for Literate inductive: "A X is either..." or "An X is either..."
173        if (trimmed.starts_with("A ") || trimmed.starts_with("An "))
174            && trimmed.contains(" is either")
175        {
176            // Check if this is a single-line definition (ends with period and no colon at end)
177            if trimmed.ends_with('.') && !trimmed.trim_end_matches('.').ends_with(':') {
178                statements.push(trimmed.to_string());
179                i += 1;
180                continue;
181            }
182
183            // Multi-line definition: collect header + indented variants
184            let mut block = String::new();
185            block.push_str(trimmed);
186            i += 1;
187
188            // Collect indented variant lines
189            while i < lines.len() {
190                let next_line = lines[i];
191                let next_trimmed = next_line.trim();
192
193                // Empty lines are OK
194                if next_trimmed.is_empty() {
195                    i += 1;
196                    continue;
197                }
198
199                // Comments are skipped
200                if next_trimmed.starts_with("--") {
201                    i += 1;
202                    continue;
203                }
204
205                // Check if indented
206                let is_indented = next_line.starts_with(' ') || next_line.starts_with('\t');
207
208                // Also accept "a Variant" or variant names starting with capital
209                let looks_like_variant = next_trimmed.starts_with("a ")
210                    || next_trimmed
211                        .chars()
212                        .next()
213                        .map(|c| c.is_uppercase())
214                        .unwrap_or(false);
215
216                if is_indented
217                    || (looks_like_variant
218                        && !next_trimmed.starts_with("A ")
219                        && !next_trimmed.starts_with("An "))
220                {
221                    // For indented lines, join with " or " for the parser
222                    if !block.ends_with(':') {
223                        block.push_str(" or ");
224                    } else {
225                        block.push(' ');
226                    }
227                    block.push_str(next_trimmed.trim_end_matches('.'));
228                    i += 1;
229                } else {
230                    break;
231                }
232            }
233
234            // Ensure ends with period
235            if !block.ends_with('.') {
236                block.push('.');
237            }
238            statements.push(block);
239            continue;
240        }
241
242        // Traditional Coq-style: accumulate until period
243        let mut current_stmt = String::new();
244        while i < lines.len() {
245            let line = lines[i];
246            let trimmed = line.trim();
247
248            if trimmed.is_empty() || trimmed.starts_with("--") {
249                i += 1;
250                continue;
251            }
252
253            if !current_stmt.is_empty() {
254                current_stmt.push(' ');
255            }
256            current_stmt.push_str(trimmed);
257
258            i += 1;
259
260            // Check if statement is complete
261            if trimmed.ends_with('.') {
262                break;
263            }
264        }
265
266        if !current_stmt.is_empty() {
267            statements.push(current_stmt);
268        }
269    }
270
271    statements
272}
273
274/// Count total files and directories in a tree (for debugging)
275fn count_files(node: &FileNode) -> usize {
276    let mut count = node.children.len();
277    for child in &node.children {
278        if child.is_directory {
279            count += count_files(child);
280        }
281    }
282    count
283}
284
285/// A rule's word for the drawer's pill, and what it was applied with when that says more than the
286/// word: the term a universal was instantiated at, the variable or witness a quantifier rule took.
287/// Every rule the chainer has gets a word; one it gains later reads as its name, spaced.
288fn rule_look(rule: &InferenceRule) -> (String, Option<String>) {
289    use InferenceRule::*;
290    let word = |w: &str| (w.to_string(), None);
291    match rule {
292        PremiseMatch => word("Given"),
293        Axiom => word("Axiom"),
294        ModusPonens => word("Modus Ponens"),
295        ModusTollens => word("Modus Tollens"),
296        ConjunctionIntro => word("\u{2227} intro"),
297        ConjunctionElim => word("\u{2227} elim"),
298        DisjunctionIntro => word("\u{2228} intro"),
299        DisjunctionElim | DisjunctionCases => word("\u{2228} elim"),
300        ImpliesIntro => word("\u{2192} intro"),
301        BicondIntro => word("\u{2194} intro"),
302        DoubleNegation => word("\u{AC}\u{AC} elim"),
303        ExFalso => word("Ex falso"),
304        ClassicalReductio | ReductioAdAbsurdum => word("Reductio"),
305        Contradiction => word("Contradiction"),
306        UniversalInst(term) => ("\u{2200} elim".to_string(), Some(term.clone())),
307        UniversalInstTerm(term) => ("\u{2200} elim".to_string(), Some(term.to_string())),
308        UniversalIntro { variable, .. } => ("\u{2200} intro".to_string(), Some(variable.clone())),
309        ExistentialIntro { .. } | ExistentialIntroTerm { .. } => word("\u{2203} intro"),
310        ExistentialElim { witness } => ("\u{2203} elim".to_string(), Some(witness.clone())),
311        CaseAnalysis { .. } => word("Cases"),
312        StructuralInduction { .. } | InductionScheme { .. } => word("Induction"),
313        Rewrite { .. } | RewriteAt { .. } => word("Rewrite"),
314        EqualitySymmetry => word("= symmetry"),
315        EqualityTransitivity => word("= transitivity"),
316        Reflexivity => word("Reflexivity"),
317        ArithDecision | LeTrans | LeRefl | LeAddMono | LinFalse | LeMulNonneg | LeSub | LtSuccLe | LtAdd1Le | LeSuccLt | LeTotal => word("Arithmetic"),
318        NativeDecide => word("Decide"),
319        GroundRefutation => word("Refutation"),
320        OracleVerification(name) => ("Oracle".to_string(), Some(name.clone())),
321        other => {
322            let name = format!("{other:?}");
323            let name = name.split(|c| c == '(' || c == ' ' || c == '{').next().unwrap_or("").to_string();
324            let mut spaced = String::new();
325            for (i, c) in name.chars().enumerate() {
326                if i > 0 && c.is_uppercase() {
327                    spaced.push(' ');
328                }
329                spaced.push(c);
330            }
331            (spaced, None)
332        }
333    }
334}
335
336/// A derivation as the drawer's tree: each step its rule, what it took, its conclusion and the
337/// steps it rests on.
338pub(super) fn proof_nodes(tree: &DerivationTree) -> ProofNode {
339    let (rule, detail) = rule_look(&tree.rule);
340    ProofNode { rule, detail, conclusion: tree.conclusion.to_string(), premises: tree.premises.iter().map(proof_nodes).collect() }
341}
342
343/// Minimal HTML escape for grid/answer cell text.
344fn esc(s: &str) -> String {
345    s.replace('&', "&amp;")
346        .replace('<', "&lt;")
347        .replace('>', "&gt;")
348}
349
350/// Render a [`SolvedGrid`] as an HTML table for the proof panel — the easter egg that
351/// fills the whole grid once the premises take the grid form. Every shown cell is a
352/// certified entailment (no Z3); an undetermined cell shows a dot.
353fn format_grid_html(grid: &SolvedGrid) -> String {
354    let cell = "border:1px solid var(--studio-border);padding:4px 10px;text-align:center;";
355    let head = "border:1px solid var(--studio-border);padding:4px 10px;text-align:center;color:var(--studio-accent);font-weight:600;";
356    let mut s = String::new();
357    s.push_str("<div style=\"margin-bottom:16px;\">");
358    s.push_str("<div style=\"font-family:monospace;font-size:12px;color:var(--studio-text-secondary);margin-bottom:6px;\">Solved grid (every filled cell certified, no Z3):</div>");
359    s.push_str("<table style=\"border-collapse:collapse;font-family:monospace;font-size:13px;color:var(--studio-text);\">");
360    s.push_str("<tr>");
361    s.push_str(&format!(
362        "<th style=\"{head}\">{}</th>",
363        esc(&grid.row_label)
364    ));
365    for col in &grid.columns {
366        s.push_str(&format!("<th style=\"{head}\">{}</th>", esc(&col.label)));
367    }
368    s.push_str("</tr>");
369    for (ri, row) in grid.rows.iter().enumerate() {
370        s.push_str("<tr>");
371        s.push_str(&format!(
372            "<td style=\"{cell}font-weight:600;\">{}</td>",
373            esc(row)
374        ));
375        for col in &grid.columns {
376            match col.cells.get(ri).and_then(|c| c.as_ref()) {
377                Some(v) => s.push_str(&format!("<td style=\"{cell}\">{}</td>", esc(v))),
378                None => s.push_str(&format!(
379                    "<td style=\"{cell}color:var(--studio-text-muted);\">·</td>"
380                )),
381            }
382        }
383        s.push_str("</tr>");
384    }
385    s.push_str("</table></div>");
386    s
387}
388
389/// Render a wh-question's answer ("Who is in Florida?" → "Beta") for the proof panel.
390fn format_answer_html(answers: &[String]) -> String {
391    let body = if answers.is_empty() {
392        "<span style=\"color:var(--studio-text-muted);\">no individual satisfies the question</span>".to_string()
393    } else {
394        format!(
395            "<span style=\"color:#34d399;font-weight:600;\">{}</span>",
396            esc(&answers.join(", "))
397        )
398    };
399    format!(
400        "<div style=\"font-family:monospace;font-size:14px;margin-bottom:12px;\"><span style=\"color:var(--studio-text-secondary);\">Answer: </span>{body}</div>"
401    )
402}
403
404/// Assemble the proof-panel HTML for a compiled theorem: the solved grid (when the form
405/// triggers it), then the wh-question answer or the certified derivation.
406fn theorem_proof_html(result: &TheoremCompileResult) -> String {
407    let mut html = String::new();
408    if let Some(grid) = &result.grid {
409        html.push_str(&format_grid_html(grid));
410    }
411    if let Some(answer) = &result.answer {
412        html.push_str(&format_answer_html(answer));
413    }
414    html
415}
416
417/// What the proof panel shows for a compiled theorem: its derivation as the drawer's tree (unless
418/// the theorem asks a question, whose answer the HTML carries), a grid's or an answer's HTML, its
419/// status, and the hint beneath.
420pub(super) struct TheoremView {
421    pub(super) html: String,
422    pub(super) tree: Option<ProofNode>,
423    pub(super) status: ProofStatus,
424    pub(super) hint: String,
425}
426
427/// One reading of a compiled theorem, for opening its file and for Execute alike. A derivation
428/// the kernel refused is shown for inspection and called uncertified — never "Ready to prove",
429/// never "solved".
430fn theorem_view(result: &TheoremCompileResult) -> TheoremView {
431    let html = theorem_proof_html(result);
432    let tree = result.derivation.as_ref().filter(|_| result.answer.is_none()).map(proof_nodes);
433    let name = &result.name;
434    if html.is_empty() && tree.is_none() {
435        return TheoremView {
436            html,
437            tree,
438            status: ProofStatus::Idle,
439            hint: format!(
440                "Theorem '{name}' ready. {} premise(s) loaded. Press Prove to prove it.",
441                result.premises.len()
442            ),
443        };
444    }
445    let (status, hint) = if let Some(answer) = &result.answer {
446        let hint = if answer.is_empty() {
447            "No answer found.".to_string()
448        } else {
449            format!("Answer: {}", answer.join(", "))
450        };
451        (
452            if result.verified {
453                ProofStatus::Success
454            } else {
455                ProofStatus::Idle
456            },
457            hint,
458        )
459    } else if result.verified {
460        (ProofStatus::Success, format!("Theorem '{name}' proved!"))
461    } else if result.derivation.is_some() {
462        let broke = result.verification_error.clone().unwrap_or_default();
463        let hint = if broke.is_empty() {
464            format!("Theorem '{name}': a derivation was found, but it is not certified.")
465        } else {
466            format!("Theorem '{name}': a derivation was found, but it is not certified. {broke}")
467        };
468        (ProofStatus::Uncertified(broke), hint)
469    } else {
470        (
471            ProofStatus::Idle,
472            format!("Theorem '{name}': grid solved."),
473        )
474    };
475    TheoremView { html, tree, status, hint }
476}
477
478/// The Auto tactic's reading, through the same door as opening a theorem
479/// (`prove_certify_check`): a certified derivation is a proof, a derivation the kernel refused
480/// is shown and called uncertified, and no derivation is a failure with a Socratic hint.
481pub(super) fn auto_view(kb: &[ProofExpr], goal: &ProofExpr, goal_text: &str) -> TheoremView {
482    let outcome = logicaffeine_proof::verify::prove_certify_check(kb, goal);
483    let broke = outcome.verification_error.unwrap_or_default();
484    match outcome.derivation {
485        Some(derivation) if outcome.verified => TheoremView {
486            html: String::new(),
487            tree: Some(proof_nodes(&derivation)),
488            status: ProofStatus::Success,
489            hint: "Proof found! The derivation tree shows the inference steps.".to_string(),
490        },
491        Some(derivation) => TheoremView {
492            html: String::new(),
493            tree: Some(proof_nodes(&derivation)),
494            hint: if broke.is_empty() {
495                "A derivation was found, but it is not certified.".to_string()
496            } else {
497                format!("A derivation was found, but it is not certified: {broke}")
498            },
499            status: ProofStatus::Uncertified(broke),
500        },
501        None => {
502            let error = if broke.is_empty() {
503                "no derivation found".to_string()
504            } else {
505                broke
506            };
507            TheoremView {
508                tree: None,
509                html: format!(
510                    "<span class=\"rule\">Auto-prove failed</span>\n\nGoal: {}\n\nError: {}",
511                    crate::ui::components::hover_hint::escape(goal_text),
512                    crate::ui::components::hover_hint::escape(&error)
513                ),
514                hint: suggest_hint(goal, kb, &[]).text,
515                status: ProofStatus::Failed(error),
516            }
517        }
518    }
519}
520
521/// Runs one of the Studio's actions behind the fault boundary. A fault nobody planned for becomes
522/// the toolbar's note and the action gives back nothing, so the panels stay as they were; a clean
523/// run takes down the note an earlier run left.
524pub(super) fn attempt<T>(
525    mut fault: Signal<Option<ActionFault>>,
526    action: &'static str,
527    work: impl FnOnce() -> T,
528) -> Option<T> {
529    let outcome = contain(work);
530    let note = outcome.as_ref().err().map(|f| ActionFault {
531        action,
532        fault: f.clone(),
533    });
534    if *fault.peek() != note {
535        fault.set(note);
536    }
537    outcome.ok()
538}
539
540/// What running a Logic document produced, computed away from the page's signals so the work can
541/// run behind the fault boundary.
542pub(super) enum LogicRun {
543    /// A `## Theorem:` block: its compiled result and how the proof panel reads it, or why it did
544    /// not compile.
545    Theorem(Result<(TheoremCompileResult, TheoremView), String>),
546    /// Plain sentences: their readings, and the first of them compiled for the prover.
547    Sentences(CompileResult, ProofCompileResult),
548    /// Nothing but headers and comments.
549    Empty,
550}
551
552/// A Logic document run by the one runner every surface shares (`studio_run`), with the proof panel's
553/// reading of a theorem added.
554pub(super) fn run_logic(text: &str) -> LogicRun {
555    match studio_run::run_logic(text) {
556        studio_run::LogicRun::Theorem(theorem) => LogicRun::Theorem(theorem.map(|result| {
557            let view = theorem_view(&result);
558            (result, view)
559        })),
560        studio_run::LogicRun::Sentences(compiled, proof) => LogicRun::Sentences(compiled, proof),
561        studio_run::LogicRun::Empty => LogicRun::Empty,
562    }
563}
564
565/// The kernel environment as the Math Context panel lists it: its inductive types and its
566/// definitions, each by name. The kernel keeps them in hash maps, whose order changes from one process
567/// to the next, so by name is the one order the server's render, the browser and every visit share.
568/// Built once per run, behind the fault boundary — printing a term walks it, and a deep enough term
569/// runs the stack out.
570#[derive(Clone, PartialEq)]
571pub(super) struct MathContext {
572    pub(super) inductives: Vec<ContextEntry>,
573    pub(super) definitions: Vec<ContextEntry>,
574}
575
576impl MathContext {
577    pub(super) fn of(ctx: &logicaffeine_kernel::Context) -> Self {
578        let by_name = |mut entries: Vec<ContextEntry>| {
579            entries.sort_by(|a, b| a.name.cmp(&b.name));
580            entries
581        };
582        MathContext {
583            inductives: by_name(
584                ctx.iter_inductives()
585                    .map(|(name, sort)| ContextEntry {
586                        name: name.to_string(),
587                        ty: sort.to_string(),
588                        body: None,
589                        kind: EntryKind::Inductive,
590                    })
591                    .collect(),
592            ),
593            definitions: by_name(
594                ctx.iter_definitions()
595                    .map(|(name, ty, body)| ContextEntry {
596                        name: name.to_string(),
597                        ty: ty.to_string(),
598                        body: Some(body.to_string()),
599                        kind: EntryKind::Definition,
600                    })
601                    .collect(),
602            ),
603        }
604    }
605
606    /// What a fresh kernel holds before any program runs: the standard library.
607    pub(super) fn prelude() -> Self {
608        MathContext::of(Repl::new().context())
609    }
610
611    pub(super) fn is_empty(&self) -> bool {
612        self.inductives.is_empty() && self.definitions.is_empty()
613    }
614}
615
616/// What running a Math document produced: a line per statement, and — when the statements ran
617/// through the REPL — the environment they built. A `## Theory` development certifies its theorems
618/// on its own and leaves the Context panel as it was.
619pub(super) struct MathRun {
620    pub(super) lines: Vec<ReplLine>,
621    pub(super) context: Option<MathContext>,
622}
623
624/// A Math document run from a fresh kernel by the one runner every surface shares (`studio_run`), so
625/// each run replaces the last rather than piling on, with the environment it built as the Context panel
626/// lists it.
627pub(super) fn run_math(code: &str) -> MathRun {
628    let run = studio_run::run_math(code);
629    MathRun {
630        lines: run.lines,
631        context: run.kernel.map(|kernel| MathContext::of(kernel.context())),
632    }
633}
634
635#[cfg(test)]
636#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/math_context_tests.rs"]
637mod math_context_tests;
638
639#[cfg(test)]
640#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/math_context_order_tests.rs"]
641mod math_context_order_tests;
642
643#[cfg(test)]
644#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/theorem_view_tests.rs"]
645mod theorem_view_tests;
646
647/// The file browser toggle while the tree is hidden: two stacked pages, the files it will show.
648pub(super) const FILES_SVG: &str = r#"<svg data-icon="files" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 1.5h4.5l3 3v7a.5.5 0 0 1-.5.5H6a.5.5 0 0 1-.5-.5V2a.5.5 0 0 1 .5-.5z"/><path d="M10.5 1.5v3h3"/><path d="M3 4v9.5a1 1 0 0 0 1 1h6.5"/></svg>"#;
649
650/// The file browser toggle while the tree shows: an arrow folding left into a line.
651pub(super) const COLLAPSE_FILES_SVG: &str = r#"<svg data-icon="collapse" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.5 2.5v11"/><path d="M13.5 8H5.5"/><path d="M9 4.5 5.5 8 9 11.5"/></svg>"#;
652
653/// The formula the Logic Output shows in `format`, with the view that printed it: the Symbol
654/// Dictionary reads it with the names that view prints. Deep falls back to the full formula when
655/// there is no Kripke reading, as the output does.
656pub(super) fn formula_on_screen(
657    result: &CompileResult,
658    format: OutputFormat,
659) -> Option<(String, OutputFormat)> {
660    match format {
661        OutputFormat::SimpleFOL => result
662            .simple_logic
663            .clone()
664            .map(|l| (l, OutputFormat::SimpleFOL)),
665        OutputFormat::Kripke => result
666            .kripke_logic
667            .clone()
668            .map(|l| (l, OutputFormat::Kripke))
669            .or_else(|| result.logic.clone().map(|l| (l, OutputFormat::Unicode))),
670        OutputFormat::Unicode | OutputFormat::LaTeX => {
671            result.logic.clone().map(|l| (l, OutputFormat::Unicode))
672        }
673    }
674}
675
676/// Code mode output toggle - interpret output vs generated Rust
677#[derive(Clone, Copy, PartialEq, Eq, Default)]
678pub(super) enum CodeOutputMode {
679    #[default]
680    Interpret,
681    Rust,
682}
683
684/// Logic mode output view — FOL interpretation or generated Rust. (SVA synthesis lives in
685/// Hardware mode, where signals/clocks/cycles have meaning; general FOL has none to assert.)
686#[derive(Clone, Copy, PartialEq, Eq, Default)]
687pub(super) enum LogicView {
688    #[default]
689    Logic,
690    Rust,
691}
692
693/// Studio-specific styles that extend the shared responsive styles
694pub const STUDIO_STYLE: &str = r#"
695/* ============================================ */
696/* STUDIO PAGE - Design Tokens                  */
697/* ============================================ */
698:root {
699    --studio-bg: #0f1419;
700    --studio-panel-bg: #12161c;
701    /* The one surface every column paints — the editor's — and how far every column holds its
702       content from its edges. A column's scroll ends at its last line: nothing to scroll into. */
703    --studio-surface: #0f1419;
704    --studio-inset: 20px;
705    --editor-overscroll: var(--studio-inset);
706    --studio-elevated: #1a1f27;
707    --studio-border: rgba(255, 255, 255, 0.08);
708    /* The column bars' grey: opaque (the border over --studio-bg), so every bar reads the
709       same whatever sits behind it. */
710    --studio-resizer: #22272b;
711    --studio-border-hover: rgba(255, 255, 255, 0.15);
712    --studio-text: #e8eaed;
713    --studio-text-secondary: #9ca3af;
714    --studio-text-muted: #6b7280;
715    --studio-accent: #667eea;
716    /* The one syntax palette: a colour for each kind of thing a formula is made of (One Dark), worn
717       by the Syntax Tree's pills and legend. Kinds that share a colour share a value. */
718    --syntax-quantifier: #c678dd;
719    --syntax-connective: #c678dd;
720    --syntax-predicate: #98c379;
721    --syntax-individual: #e5c07b;
722    --syntax-role: #e5c07b;
723    --syntax-variable: #61afef;
724    --syntax-modal: #56b6c2;
725    --syntax-tense: #56b6c2;
726    /* The toolbar's one row on a desk. */
727    --toolbar-height: 49px;
728}
729
730/* ============================================ */
731/* STUDIO PAGE - Desktop Layout                 */
732/* ============================================ */
733.studio-container {
734    display: flex;
735    flex-direction: column;
736    height: 100vh;
737    height: 100dvh;
738    background: var(--studio-bg);
739    color: var(--studio-text);
740    scrollbar-color: var(--studio-border-hover) transparent;
741    overflow: hidden;
742}
743
744/* Toolbar */
745.studio-toolbar {
746    display: flex;
747    align-items: center;
748    justify-content: space-between;
749    height: var(--toolbar-height);
750    padding: 0 16px;
751    background: var(--studio-panel-bg);
752    border-bottom: 1px solid var(--studio-border);
753    gap: 12px;
754    flex-shrink: 0;
755}
756
757.studio-toolbar-left {
758    display: flex;
759    align-items: center;
760    gap: 12px;
761}
762
763.studio-toolbar-right {
764    display: flex;
765    align-items: center;
766    gap: 8px;
767}
768
769/* A deep link to a file the prerendered copy does not show (`prerender_guard`): the copy's panels
770   keep their place unpainted until the app draws the file the link names. */
771.studio-opens-elsewhere #main .studio-main {
772    visibility: hidden;
773}
774
775/* What stopped an action nobody expected to fail: one warning-orange line just left of the
776   buttons. The whole story — the full message and where it was raised — is in its tooltip. */
777.studio-fault {
778    flex: 0 1 auto;
779    min-width: 0;
780    max-width: 44vw;
781    color: var(--color-warning);
782    font-size: 13px;
783    white-space: nowrap;
784    overflow: hidden;
785    text-overflow: ellipsis;
786    cursor: help;
787}
788
789/* One square button whose drawn icon names what a press does: show the files, or fold them away. */
790.sidebar-toggle-btn {
791    width: 32px;
792    height: 32px;
793    padding: 0;
794    display: inline-flex;
795    align-items: center;
796    justify-content: center;
797    flex: none;
798    background: rgba(255, 255, 255, 0.04);
799    border: 1px solid rgba(255, 255, 255, 0.08);
800    border-radius: 6px;
801    color: rgba(255, 255, 255, 0.7);
802    cursor: pointer;
803    transition: all 0.15s ease;
804}
805
806.sidebar-toggle-btn .toggle-icon {
807    display: flex;
808}
809
810/* Beside the folded file browser's toggle: what it opens, muted, set like the action buttons' text. */
811.files-label {
812    color: var(--studio-text-muted);
813    font-size: 13px;
814    user-select: none;
815}
816
817.sidebar-toggle-btn:hover {
818    background: rgba(255, 255, 255, 0.08);
819    color: rgba(255, 255, 255, 0.9);
820}
821
822/* Main content area with optional sidebar */
823.studio-content {
824    flex: 1 1 0;
825    min-height: 100px;
826    display: flex;
827    overflow: hidden;
828    position: relative;
829}
830
831/* Overlay to close sidebar when clicking outside (mobile) */
832.sidebar-overlay {
833    display: none;
834}
835
836/* Where the files are a drawer (responsive::media::FILES_DRAWER), it opens over the panels, inside
837   the workbench's own content, and stays folded until the reader opens it: no tree covers the
838   editor in the first frame. */
839@media (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse), (max-height: 500px) and (orientation: landscape) {
840    .sidebar-overlay {
841        display: block;
842        position: absolute;
843        inset: 0;
844        background: rgba(0, 0, 0, 0.5);
845        z-index: 99;
846    }
847
848    .sidebar-overlay:not(.drawer-open),
849    .studio-sidebar:not(.drawer-open) {
850        display: none !important;
851    }
852}
853
854/* Sidebar wrapper for controlled width */
855.studio-sidebar {
856    display: flex;
857    flex-shrink: 0;
858    overflow: hidden;
859}
860
861@media (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse), (max-height: 500px) and (orientation: landscape) {
862    .studio-sidebar {
863        position: absolute;
864        left: 0;
865        top: 0;
866        bottom: 0;
867        z-index: 100;
868        width: 280px !important;
869        min-width: 280px !important;
870        max-width: 280px !important;
871        box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);
872        background: var(--studio-surface);
873    }
874
875    /* Text color overrides for Safari compatibility */
876    .studio-sidebar .file-tree-item {
877        color: rgba(255, 255, 255, 0.9) !important;
878        -webkit-text-fill-color: rgba(255, 255, 255, 0.9);
879    }
880
881    .studio-sidebar .file-tree-item.selected {
882        color: #00d4ff !important;
883        -webkit-text-fill-color: #00d4ff;
884    }
885
886    .studio-sidebar .file-tree-item .name {
887        color: inherit;
888        -webkit-text-fill-color: inherit;
889    }
890}
891
892/* Desktop: 3-column panel layout */
893.studio-main {
894    flex: 1;
895    display: flex;
896    overflow: hidden;
897    gap: 1px;
898    background: var(--studio-border);
899}
900
901.studio-panel {
902    background: var(--studio-surface);
903    display: flex;
904    flex-direction: column;
905    overflow: hidden;
906    min-width: 0;
907}
908
909/* Desktop columns. Their widths come from the layout model (studio_layout.rs) as custom
910   properties on .studio-content, so a drag repaints them without re-rendering the page. */
911@media (min-width: 769px) {
912    .studio-sidebar { width: var(--col-sidebar); }
913    .studio-main > .col-left { flex: 0 0 var(--col-left); }
914    .studio-main > .col-center { flex: 1 1 0; }
915    .studio-main > .col-right { flex: 0 0 var(--col-right); }
916}
917
918.studio-panel .panel-header {
919    padding: 0 20px;
920    height: 52px;
921    background: rgba(255, 255, 255, 0.02);
922    border-bottom: 1px solid var(--studio-border);
923    display: flex;
924    justify-content: space-between;
925    align-items: center;
926    flex-shrink: 0;
927}
928
929/* The Studio's one title type: every panel header's title ("English Input", "Logic Output"), the
930   Files header and each collapsible block's heading ("Symbol Dictionary"). */
931.studio-panel .panel-header,
932.panel-title {
933    font-size: 16px;
934    font-weight: 600;
935    letter-spacing: 0.3px;
936    color: var(--studio-text);
937}
938
939@media (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse) {
940    .studio-panel .panel-header,
941    .panel-title {
942        font-size: 14px;
943    }
944}
945
946.studio-panel .panel-content {
947    flex: 1;
948    min-height: 0;
949    overflow: auto;
950    -webkit-overflow-scrolling: touch;
951}
952
953/* Panel Resizers (desktop only). The bar draws 6px (RESIZER in studio_layout.rs); its grab
954   area reaches 4px either side. */
955.panel-resizer {
956    position: relative;
957    width: 6px;
958    background: var(--studio-resizer);
959    cursor: col-resize;
960    transition: background 0.2s ease;
961    flex-shrink: 0;
962    touch-action: none;
963}
964
965.panel-resizer::after {
966    content: "";
967    position: absolute;
968    top: 0;
969    bottom: 0;
970    left: -4px;
971    right: -4px;
972    z-index: 1;
973}
974
975.panel-resizer:hover,
976.panel-resizer.active {
977    background: var(--studio-accent);
978}
979
980/* Format Toggle (Unicode/LaTeX) */
981.format-toggle {
982    display: flex;
983    gap: 4px;
984    background: rgba(255, 255, 255, 0.04);
985    border: 1px solid var(--studio-border);
986    border-radius: 6px;
987    padding: 2px;
988}
989
990.format-btn {
991    padding: 4px 10px;
992    border: none;
993    background: transparent;
994    color: var(--studio-text-muted);
995    font-size: 12px;
996    border-radius: 4px;
997    cursor: pointer;
998    transition: all 0.15s ease;
999    line-height: 1;
1000}
1001
1002.format-btn:hover {
1003    color: var(--studio-text);
1004    background: rgba(255, 255, 255, 0.04);
1005}
1006
1007.format-btn.active {
1008    background: rgba(255, 255, 255, 0.08);
1009    color: var(--studio-text);
1010}
1011
1012/* Guide Bar - above panels */
1013.studio-guide {
1014    background: var(--studio-panel-bg);
1015    border-bottom: 1px solid var(--studio-border);
1016    flex-shrink: 0;
1017}
1018
1019/* The dock bar: one amber line along the bottom, above the status bar, that says what to do next
1020   and holds the way into the drawer that rises from it (Logic's proof, Code's debugger). */
1021.studio-dock {
1022    display: flex;
1023    align-items: center;
1024    gap: 10px;
1025    min-height: 40px;
1026    padding: 4px 12px;
1027    background: rgba(245, 158, 11, 0.10);
1028    border-top: 1px solid rgba(245, 158, 11, 0.35);
1029    color: #fbbf24;
1030    font-size: 13px;
1031    flex-shrink: 0;
1032}
1033
1034.studio-dock-icon {
1035    display: inline-flex;
1036    font-size: 15px;
1037}
1038
1039.studio-dock-text {
1040    flex: 1 1 auto;
1041    min-width: 0;
1042    line-height: 1.4;
1043}
1044
1045.studio-dock-btn {
1046    flex: none;
1047    min-height: 30px;
1048    padding: 5px 12px;
1049    border: 1px solid rgba(245, 158, 11, 0.45);
1050    border-radius: 6px;
1051    background: transparent;
1052    color: #fbbf24;
1053    font: 600 13px/1 inherit;
1054    font-family: inherit;
1055    cursor: pointer;
1056    transition: background 0.15s ease;
1057}
1058
1059.studio-dock-btn:hover:not(:disabled) { background: rgba(245, 158, 11, 0.18); }
1060
1061.studio-dock-btn.primary {
1062    background: #f59e0b;
1063    border-color: #f59e0b;
1064    color: #111;
1065}
1066
1067.studio-dock-btn.primary:hover:not(:disabled) { background: #fbbf24; }
1068
1069.studio-dock-btn:disabled {
1070    opacity: 0.4;
1071    cursor: default;
1072}
1073
1074/* Under a finger the dock's buttons are a finger tall. */
1075@media (pointer: coarse) {
1076    .studio-dock-btn { min-height: 44px; }
1077}
1078
1079/* Execute button for Code mode */
1080.execute-btn {
1081    padding: 8px 14px;
1082    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1083    border: none;
1084    border-radius: 8px;
1085    color: white;
1086    font-size: 13px;
1087    font-weight: 500;
1088    cursor: pointer;
1089    transition: all 0.15s ease;
1090}
1091
1092/* Desktop: show short labels */
1093.execute-btn .mobile-label {
1094    display: none;
1095}
1096
1097.execute-btn .desktop-label {
1098    display: inline;
1099}
1100
1101.execute-btn:hover:not(:disabled) {
1102    transform: translateY(-1px);
1103    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
1104}
1105
1106/* An action the open file cannot take: in its place, dimmed, its tooltip saying why. */
1107.execute-btn:disabled {
1108    opacity: 0.4;
1109    cursor: not-allowed;
1110}
1111
1112.execute-btn:active {
1113    transform: translateY(0);
1114}
1115
1116/* Mobile execute buttons */
1117@media (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse) {
1118    .execute-btn {
1119        padding: 6px 10px;
1120        font-size: 12px;
1121        white-space: nowrap;
1122    }
1123}
1124
1125@media (max-width: 480px) {
1126    .execute-btn {
1127        padding: 5px 8px;
1128        font-size: 11px;
1129    }
1130}
1131
1132/* Output mode toggle for Code mode */
1133/* Labelled output on a panel's own surface — a small-caps label over flat code, set like the
1134   code editor's text — and a verdict marked by its colour and a rule, not a box. */
1135.panel-section-label {
1136    font-size: 11px;
1137    text-transform: uppercase;
1138    letter-spacing: 0.05em;
1139    color: var(--studio-text-secondary);
1140    margin: 4px 0;
1141}
1142
1143/* The first label starts at the panel's inset, like every column's first line. */
1144.panel-section-label:first-child {
1145    margin-top: 0;
1146}
1147
1148.panel-code {
1149    font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
1150    font-size: 14px;
1151    line-height: 1.6;
1152    white-space: pre-wrap;
1153    word-break: break-word;
1154    color: var(--studio-text);
1155    margin: 0 0 12px;
1156}
1157
1158.panel-verdict {
1159    font-size: 13px;
1160    line-height: 1.5;
1161    color: var(--studio-text-secondary);
1162    border-left: 2px solid var(--studio-border-hover);
1163    padding: 2px 0 2px 10px;
1164    margin: 0 0 12px;
1165}
1166
1167/* A picture's caption: what the drawing shows, in the secondary voice. */
1168.panel-caption {
1169    margin-top: 6px;
1170    font-size: 12px;
1171    line-height: 1.5;
1172    color: var(--studio-text-secondary);
1173}
1174
1175.panel-verdict.proved {
1176    color: #4ade80;
1177    border-left-color: #4ade80;
1178}
1179
1180.panel-verdict.refuted {
1181    color: #f87171;
1182    border-left-color: #f87171;
1183}
1184
1185/* The controls on a panel header's right: segmented toggles and one-off actions. */
1186.panel-header-actions {
1187    display: flex;
1188    align-items: center;
1189    gap: 8px;
1190}
1191
1192.output-mode-toggle {
1193    display: flex;
1194    gap: 4px;
1195    background: rgba(255, 255, 255, 0.04);
1196    border: 1px solid var(--studio-border);
1197    border-radius: 6px;
1198    padding: 2px;
1199}
1200
1201.output-mode-btn {
1202    padding: 4px 10px;
1203    border: none;
1204    background: transparent;
1205    color: var(--studio-text-muted);
1206    font-size: 12px;
1207    border-radius: 4px;
1208    cursor: pointer;
1209    transition: all 0.15s ease;
1210    line-height: 1;
1211}
1212
1213.output-mode-btn:hover {
1214    color: var(--studio-text);
1215    background: rgba(255, 255, 255, 0.04);
1216}
1217
1218.output-mode-btn.active {
1219    background: rgba(255, 255, 255, 0.08);
1220    color: var(--studio-text);
1221}
1222
1223/* Interpreter output display */
1224/* A panel's own content — a picture, a list — held at the Studio's inset; `wide` scrolls a
1225   picture wider than its column instead of shrinking it. */
1226.panel-body {
1227    padding: var(--studio-inset);
1228}
1229
1230.panel-body.wide {
1231    overflow-x: auto;
1232}
1233
1234.interpreter-output {
1235    padding: var(--studio-inset);
1236    font-family: 'SF Mono', 'Fira Code', monospace;
1237    font-size: 14px;
1238    line-height: 1.6;
1239}
1240
1241/* A program's output keeps its spacing — padded columns and indents are what it printed. */
1242.interpreter-line {
1243    margin-bottom: 4px;
1244    color: #e8eaed;
1245    white-space: pre-wrap;
1246}
1247
1248.interpreter-error {
1249    color: #e06c75;
1250    padding: 12px;
1251    background: rgba(224, 108, 117, 0.1);
1252    border-radius: 6px;
1253    margin-top: 8px;
1254}
1255
1256.interpreter-empty {
1257    color: rgba(255, 255, 255, 0.4);
1258    text-align: center;
1259    padding: 40px 20px;
1260}
1261
1262/* ============================================ */
1263/* STUDIO PAGE - Mobile Overrides               */
1264/* ============================================ */
1265
1266/* Phones and upright tablets: the panels stack. */
1267@media (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse) {
1268    .studio-toolbar {
1269        flex-wrap: wrap;
1270        height: auto;
1271        padding: 10px 12px;
1272        gap: 10px;
1273        position: relative;
1274        z-index: 101;
1275    }
1276
1277    /* First row: file toggle */
1278    .studio-toolbar-left {
1279        flex-shrink: 0;
1280        order: 1;
1281    }
1282
1283    /* Second row: action buttons - full width */
1284    .studio-toolbar-right {
1285        flex-basis: 100%;
1286        flex-wrap: wrap;
1287        justify-content: center;
1288        gap: 12px;
1289        order: 3;
1290        padding-top: 8px;
1291        border-top: 1px solid rgba(255, 255, 255, 0.06);
1292    }
1293
1294    /* The fault note takes a line of its own above the buttons. */
1295    .studio-fault {
1296        flex-basis: 100%;
1297        max-width: 100%;
1298        text-align: center;
1299    }
1300
1301    /* Full text on mobile buttons */
1302    .execute-btn {
1303        padding: 10px 16px;
1304        font-size: 14px;
1305    }
1306
1307    .files-label {
1308        font-size: 14px;
1309    }
1310
1311    .execute-btn .mobile-label {
1312        display: inline;
1313    }
1314
1315    .execute-btn .desktop-label {
1316        display: none;
1317    }
1318
1319    /* Hide mobile tab bar - panels stack instead */
1320    .mobile-tabs {
1321        display: none !important;
1322    }
1323
1324    /* Hide desktop resizers */
1325    .panel-resizer {
1326        display: none;
1327    }
1328
1329    /* Stacked vertical panel layout */
1330    .studio-main {
1331        flex-direction: column;
1332        gap: 0;
1333        background: var(--studio-bg);
1334    }
1335
1336    /* Both panels visible, stacked vertically */
1337    .studio-panel {
1338        min-width: unset;
1339        min-height: 0;
1340        width: 100% !important;
1341    }
1342
1343    .studio-panel.mobile-expanded {
1344        flex: var(--panel-flex, 1);
1345        overflow: hidden;
1346    }
1347
1348    .studio-panel.mobile-collapsed {
1349        flex: 0 0 auto;
1350    }
1351
1352    .studio-panel.mobile-collapsed .panel-content {
1353        display: none;
1354    }
1355
1356    /* Show panel headers with collapse affordance */
1357    .studio-panel .panel-header {
1358        display: flex !important;
1359        cursor: pointer;
1360        padding: 0 14px;
1361        height: 44px;
1362    }
1363
1364    /* Collapse chevron indicator */
1365    .studio-panel .panel-header::after {
1366        content: '\25BC';
1367        font-size: 10px;
1368        color: rgba(255, 255, 255, 0.4);
1369        margin-left: 8px;
1370        transition: transform 0.15s ease;
1371    }
1372
1373    .studio-panel.mobile-collapsed .panel-header::after {
1374        content: '\25B6';
1375    }
1376
1377    /* Divider between stacked panels */
1378    .studio-panel + .studio-panel {
1379        border-top: 1px solid var(--studio-border);
1380    }
1381
1382    /* Hide Panel 3 (Console/Context/Graph) on mobile */
1383    .studio-main > aside {
1384        display: none !important;
1385    }
1386
1387    /* Mobile-sized format toggle */
1388    .format-toggle {
1389        gap: 4px;
1390        padding: 2px;
1391        border-radius: 6px;
1392    }
1393
1394    .format-btn {
1395        padding: 6px 10px;
1396        font-size: 12px;
1397        border-radius: 4px;
1398        min-height: 32px;
1399        min-width: 32px;
1400        display: flex;
1401        align-items: center;
1402        justify-content: center;
1403    }
1404
1405    /* Footer constraints */
1406    .studio-footer {
1407        max-height: 30vh;
1408        overflow: auto;
1409    }
1410
1411    .mobile-panel-resizer {
1412        display: flex;
1413        align-items: center;
1414        justify-content: center;
1415        height: 16px;
1416        cursor: row-resize;
1417        flex-shrink: 0;
1418        touch-action: none;
1419        -webkit-tap-highlight-color: transparent;
1420        z-index: 2;
1421        position: relative;
1422    }
1423
1424    .mobile-panel-resizer::after {
1425        content: "";
1426        position: absolute;
1427        left: 50%;
1428        top: 50%;
1429        transform: translate(-50%, -50%);
1430        width: 48px;
1431        height: 4px;
1432        border-radius: 2px;
1433        background: rgba(255, 255, 255, 0.15);
1434        transition: background 0.15s ease;
1435    }
1436
1437    .mobile-panel-resizer:hover::after,
1438    .mobile-panel-resizer.active::after {
1439        background: rgba(102, 126, 234, 0.6);
1440    }
1441}
1442
1443/* Extra small screens */
1444@media (max-width: 480px) {
1445    .format-btn {
1446        padding: 4px 8px;
1447        font-size: 11px;
1448    }
1449}
1450
1451/* Desktop: hide mobile resizer */
1452@media (min-width: 769px) {
1453    .mobile-panel-resizer {
1454        display: none;
1455    }
1456}
1457
1458/* Landscape mobile */
1459@media (max-height: 500px) and (orientation: landscape) {
1460    .studio-footer {
1461        max-height: 25vh;
1462    }
1463}
1464
1465/* ============================================ */
1466/* STUDIO PAGE - Phones, tablets and touch      */
1467/* ============================================ */
1468/* Every rule from here on sits under a phone, tablet or touch query (responsive::media), so the
1469   desktop Studio stays as it was (`the_desktop_studio_is_unchanged`). The bands:
1470   phone portrait   one pane at a time, chosen by the switch
1471   phone landscape  the editor beside the output, half and half
1472   tablet portrait  the editor over the output, the split bar between
1473   tablet landscape the desktop's columns, for a finger
1474   The workbench's wrapper lays nothing out of its own on a desk. */
1475.studio-workbench {
1476    display: contents;
1477}
1478
1479/* The switch between a phone's panes, and the lines that stand in for a hover, show only where
1480   they are needed. */
1481.mobile-tabs,
1482.studio-reasons,
1483.studio-fault-detail {
1484    display: none;
1485}
1486
1487/* The switch: a row of tabs under the toolbar, each a finger wide. */
1488@media (max-width: 600px), (max-height: 500px) and (orientation: landscape), (min-width: 601px) and (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse) {
1489    .mobile-tabs {
1490        gap: 4px;
1491        padding: 4px max(12px, var(--safe-right, 0px)) 6px max(12px, var(--safe-left, 0px));
1492        background: var(--studio-panel-bg);
1493        border-bottom: 1px solid var(--studio-border);
1494        flex-shrink: 0;
1495    }
1496
1497    .mobile-tabs .mobile-tab {
1498        flex: 1 1 0;
1499        min-width: 0;
1500        min-height: 44px;
1501        display: flex;
1502        flex-direction: row;
1503        align-items: center;
1504        justify-content: center;
1505        gap: 6px;
1506        padding: 0 8px;
1507        border: 1px solid transparent;
1508        border-radius: 8px;
1509        background: rgba(255, 255, 255, 0.04);
1510        color: var(--studio-text-muted);
1511        font-size: 13px;
1512        font-weight: 500;
1513        cursor: pointer;
1514        -webkit-tap-highlight-color: transparent;
1515    }
1516
1517    .mobile-tabs .mobile-tab.active {
1518        background: rgba(102, 126, 234, 0.2);
1519        border-color: rgba(102, 126, 234, 0.4);
1520        color: var(--studio-text);
1521    }
1522
1523    .mobile-tabs .mobile-tab-icon {
1524        font-size: 15px;
1525        line-height: 1;
1526    }
1527
1528    .mobile-tabs .mobile-tab-label {
1529        font-size: 13px;
1530        white-space: nowrap;
1531        overflow: hidden;
1532        text-overflow: ellipsis;
1533    }
1534}
1535
1536/* One row of toolbar on a phone, either way up: the files toggle on the left, the mode's actions on
1537   the right under their short labels, every one a finger wide. */
1538@media (max-width: 600px), (max-height: 500px) and (orientation: landscape) {
1539    .studio-toolbar {
1540        flex-wrap: wrap;
1541        height: auto;
1542        padding: 8px max(12px, var(--safe-right, 0px)) 8px max(12px, var(--safe-left, 0px));
1543        gap: 8px;
1544    }
1545
1546    .studio-toolbar-right {
1547        flex-basis: auto;
1548        flex: 0 1 auto;
1549        margin-left: auto;
1550        order: 2;
1551        justify-content: flex-end;
1552        gap: 6px;
1553        padding-top: 0;
1554        border-top: none;
1555    }
1556
1557    .execute-btn {
1558        min-height: 44px;
1559        padding: 0 10px;
1560        font-size: 13px;
1561    }
1562
1563    .execute-btn .mobile-label {
1564        display: none;
1565    }
1566
1567    .execute-btn .desktop-label {
1568        display: inline;
1569    }
1570
1571    .files-label {
1572        font-size: 13px;
1573    }
1574
1575    /* A pane's header folds nothing where the panes are fixed. */
1576    .studio-panel .panel-header {
1577        cursor: default;
1578    }
1579
1580    .studio-panel .panel-header::after {
1581        content: none;
1582    }
1583
1584    .studio-panel + .studio-panel {
1585        border-top: none;
1586    }
1587
1588    .studio-panel.mobile-collapsed .panel-content {
1589        display: block;
1590    }
1591
1592    .studio-panel.mobile-collapsed .panel-content
1593    .mobile-panel-resizer,
1594    .panel-resizer {
1595        display: none !important;
1596    }
1597}
1598
1599/* A phone held upright: the pane the switch names, alone, the whole height. */
1600@media (max-width: 600px) {
1601    .mobile-tabs {
1602        display: flex !important;
1603    }
1604
1605    .studio-main > .studio-panel:not(.phone-shown) {
1606        display: none !important;
1607    }
1608
1609    .studio-main > .studio-panel.phone-shown {
1610        display: flex !important;
1611        flex: 1 1 0;
1612        min-height: 0;
1613    }
1614}
1615
1616/* A phone on its side: the editor beside the output (or the third panel the switch names), half and
1617   half, the status bar left out for the height, and the page's nav free to scroll away above a
1618   workbench the window's height. */
1619@media (max-height: 500px) and (orientation: landscape) {
1620    .studio-main {
1621        flex-direction: row;
1622        gap: 1px;
1623        background: var(--studio-border);
1624    }
1625
1626    .studio-main > .studio-panel {
1627        flex: 1 1 0 !important;
1628        min-width: 0;
1629        width: auto !important;
1630    }
1631
1632    .studio-main > .col-center:not(.phone-right),
1633    .studio-main > .col-right:not(.phone-right) {
1634        display: none !important;
1635    }
1636
1637    .studio-main > .col-right.phone-right {
1638        display: flex !important;
1639    }
1640
1641    .mobile-tabs.has-third {
1642        display: flex !important;
1643    }
1644
1645    .mobile-tabs .mobile-tab:first-child {
1646        display: none;
1647    }
1648
1649    .studio-statusbar {
1650        display: none;
1651    }
1652
1653    .studio-container {
1654        height: auto;
1655    }
1656
1657    .studio-container > .studio-workbench {
1658        display: flex;
1659        flex-direction: column;
1660        flex: none;
1661        height: 100svh;
1662    }
1663}
1664
1665/* A tablet held upright: the editor over the lower pane, which shows the output or the third panel
1666   the switch names; the split bar between them takes a finger. */
1667@media (min-width: 601px) and (max-width: 768px), (min-width: 769px) and (max-width: 1024px) and (orientation: portrait) and (pointer: coarse) {
1668    .mobile-tabs.has-third {
1669        display: flex !important;
1670    }
1671
1672    .mobile-tabs .mobile-tab:first-child {
1673        display: none;
1674    }
1675
1676    .studio-main > .col-center:not(.phone-right) {
1677        display: none !important;
1678    }
1679
1680    .studio-main > aside.phone-right {
1681        display: flex !important;
1682    }
1683
1684    .mobile-panel-resizer {
1685        display: flex;
1686    }
1687
1688    .mobile-panel-resizer::before {
1689        content: "";
1690        position: absolute;
1691        left: 0;
1692        right: 0;
1693        top: -14px;
1694        bottom: -14px;
1695    }
1696}
1697
1698/* Every control a finger wide wherever a finger, a phone or an upright tablet may press it: the
1699   files toggle, the actions, the output and format toggles, the proof's tactics, the guide's hint,
1700   the readings and New file. */
1701@media (max-width: 768px), (pointer: coarse), (max-height: 500px) and (orientation: landscape) {
1702    .sidebar-toggle-btn {
1703        width: 44px;
1704        height: 44px;
1705    }
1706
1707    .execute-btn {
1708        min-height: 44px;
1709    }
1710
1711    .output-mode-btn,
1712    .format-btn {
1713        min-height: 44px;
1714        min-width: 44px;
1715    }
1716
1717    .output-mode-toggle,
1718    .format-toggle {
1719        padding: 0;
1720    }
1721
1722    .studio-panel .panel-header {
1723        height: 52px;
1724    }
1725
1726    .studio-workbench .tactic-btn,
1727    .studio-workbench .guide-btn,
1728    .studio-workbench .reading-btn,
1729    .studio-workbench .file-browser-btn {
1730        min-height: 44px;
1731        min-width: 44px;
1732    }
1733}
1734
1735/* Under a finger: the bars' grab areas a finger wide around what they draw, the panes' scrolling
1736   kept to the panes on the Studio page, and the page sized above an on-screen keyboard. */
1737@media (pointer: coarse) {
1738    .panel-resizer::after {
1739        left: -19px;
1740        right: -19px;
1741    }
1742
1743    .studio-container {
1744        height: calc(100dvh - var(--keyboard-inset, 0px));
1745        overscroll-behavior: none;
1746    }
1747
1748    .studio-container .panel-content,
1749    .studio-container .code-editor-textarea {
1750        overscroll-behavior: contain;
1751    }
1752
1753    .code-editor-textarea {
1754        touch-action: pan-x pan-y;
1755    }
1756}
1757
1758/* Where nothing hovers: each disabled action says why on a line under the toolbar, and the fault
1759   note wraps and opens its whole story to a tap. */
1760@media (hover: none) {
1761    .studio-reasons {
1762        display: block;
1763        padding: 6px max(12px, var(--safe-right, 0px)) 6px max(12px, var(--safe-left, 0px));
1764        background: var(--studio-panel-bg);
1765        border-bottom: 1px solid var(--studio-border);
1766        color: var(--studio-text-muted);
1767        font-size: 12px;
1768        line-height: 1.4;
1769        flex-shrink: 0;
1770    }
1771
1772    .studio-reasons > span {
1773        display: block;
1774    }
1775
1776    .studio-fault {
1777        white-space: normal;
1778        text-overflow: clip;
1779        max-width: none;
1780    }
1781
1782    .studio-fault-detail {
1783        display: block;
1784        padding: 6px max(12px, var(--safe-right, 0px)) 6px max(12px, var(--safe-left, 0px));
1785        background: var(--studio-panel-bg);
1786        border-bottom: 1px solid var(--studio-border);
1787        color: var(--color-warning);
1788        font-size: 12px;
1789        line-height: 1.4;
1790        white-space: pre-wrap;
1791        flex-shrink: 0;
1792    }
1793}
1794
1795/* LLM Heal (work/LLM_HEAL.md): the blue button with the fairy, the fairy swirling in to the mended
1796   line and resting there still, and her card, readable whole with Keep and Undo always in view. */
1797.heal-btn {
1798    background: linear-gradient(135deg, var(--accent-primary, #00d4ff) 0%, #2563eb 100%);
1799    display: inline-flex;
1800    align-items: center;
1801    gap: 6px;
1802}
1803.heal-btn-icon {
1804    width: 18px;
1805    height: 18px;
1806    object-fit: contain;
1807    image-rendering: pixelated;
1808}
1809.col-left { position: relative; }
1810.heal-overlay {
1811    position: absolute;
1812    inset: 0;
1813    pointer-events: none;
1814    z-index: 30;
1815}
1816.heal-fairy {
1817    position: absolute;
1818    width: 56px;
1819    height: 56px;
1820    object-fit: contain;
1821    image-rendering: pixelated;
1822    left: 8px;
1823    top: calc(48px + var(--heal-line, 0) * 1.5em);
1824    transform: translateY(-50%);
1825    transition: top 0.7s ease;
1826    filter: drop-shadow(0 0 10px rgba(0, 212, 255, 0.7));
1827}
1828/* The flight: one swirl from the toolbar's side down into the editor, then still. */
1829.heal-fairy.flying { animation: heal-swirl 1.1s cubic-bezier(0.22, 0.8, 0.3, 1) both; }
1830@keyframes heal-swirl {
1831    0%   { transform: translate(60vw, -60px) rotate(0deg) scale(0.4); opacity: 0; }
1832    35%  { transform: translate(28vw, 40px) rotate(-200deg) scale(0.8); opacity: 1; }
1833    70%  { transform: translate(8vw, -16px) rotate(-330deg) scale(1.05); }
1834    100% { transform: translateY(-50%) rotate(-360deg) scale(1); }
1835}
1836.heal-fairy.failed { left: auto; right: 18px; top: 10px; transform: none; }
1837.heal-card {
1838    position: absolute;
1839    left: 70px;
1840    right: 12px;
1841    top: 44px;
1842    bottom: 12px;
1843    display: flex;
1844    flex-direction: column;
1845    pointer-events: auto;
1846    background: #1b1f27;
1847    border: 1px solid rgba(0, 212, 255, 0.45);
1848    border-radius: 10px;
1849    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.55);
1850    padding: 12px 14px;
1851    color: #e6edf3;
1852    font-size: 13px;
1853}
1854.heal-card-cols {
1855    flex: 1 1 auto;
1856    min-height: 0;
1857    overflow: auto;
1858    display: grid;
1859    grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
1860    gap: 14px;
1861}
1862.heal-card-col { min-width: 0; }
1863.heal-card-col h3 { margin: 0 0 6px; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase; color: #9aa3b2; }
1864.heal-card pre { margin: 0; white-space: pre-wrap; word-break: break-word; font: 13px/1.6 var(--font-mono, ui-monospace, monospace); color: #e6edf3; }
1865.heal-before { color: #b7bec9; }
1866.heal-line.mended { background: rgba(0, 212, 255, 0.14); box-shadow: -4px 0 0 rgba(0, 212, 255, 0.7); border-radius: 2px; }
1867.heal-line.replaced { background: rgba(239, 68, 68, 0.14); box-shadow: -4px 0 0 rgba(239, 68, 68, 0.7); border-radius: 2px; text-decoration: line-through; text-decoration-color: rgba(239, 68, 68, 0.6); }
1868.heal-word { background: rgba(0, 212, 255, 0.35); color: #fff; border-radius: 2px; font-weight: 600; }
1869.heal-line.replaced .heal-word { background: rgba(239, 68, 68, 0.4); }
1870.heal-card-actions { flex: none; display: flex; align-items: center; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255, 255, 255, 0.08); }
1871.heal-card-note { flex: 1 1 auto; color: #9aa3b2; }
1872.heal-card .studio-dock-btn { border-color: rgba(0, 212, 255, 0.45); color: var(--accent-primary, #00d4ff); }
1873.heal-card .studio-dock-btn.primary { background: rgba(0, 212, 255, 0.16); }
1874.heal-card-failed { bottom: auto; max-width: 420px; }
1875.heal-card-failed p { margin: 0 0 10px; }
1876@media (max-width: 768px) {
1877    .heal-card { left: 12px; }
1878    .heal-card-cols { grid-template-columns: minmax(0, 1fr); }
1879}
1880@media (prefers-reduced-motion: reduce) {
1881    .heal-fairy { transition: none; animation: none; }
1882}
1883}
1884"#;
1885
1886/// Render the hardware knowledge graph as an animated radial SVG: signal nodes on a ring,
1887/// relations as directed edges. Pure SVG + CSS — edges animate a flowing dash ("signal
1888/// current") and nodes pulse, so a static spec reads like a live circuit. Returns "" if empty.
1889pub(super) fn kg_svg(kg: &logicaffeine_compile::codegen_sva::hw_pipeline::KgSummary) -> String {
1890    use std::fmt::Write as _;
1891    let n = kg.nodes.len();
1892    if n == 0 {
1893        return String::new();
1894    }
1895    let (w, h) = (340.0_f64, 300.0_f64);
1896    let (cx, cy) = (w / 2.0, h / 2.0);
1897    let ring = (w.min(h) / 2.0 - 50.0).max(34.0);
1898    let node_r = 15.0_f64;
1899    let pos: Vec<(f64, f64)> = (0..n)
1900        .map(|i| {
1901            let ang = (i as f64) / (n as f64) * std::f64::consts::TAU - std::f64::consts::FRAC_PI_2;
1902            (cx + ring * ang.cos(), cy + ring * ang.sin())
1903        })
1904        .collect();
1905    let color = |role: &str| match role {
1906        "input" => "#60a5fa",
1907        "output" => "#4ade80",
1908        "clock" => "#fbbf24",
1909        _ => "#a78bfa",
1910    };
1911    let esc = |s: &str| {
1912        s.replace('&', "&amp;")
1913            .replace('<', "&lt;")
1914            .replace('>', "&gt;")
1915    };
1916
1917    let mut svg = String::new();
1918    let _ = write!(
1919        svg,
1920        r##"<svg viewBox="0 0 {w} {h}" width="100%" style="max-height:300px" xmlns="http://www.w3.org/2000/svg">"##
1921    );
1922    svg.push_str(
1923        r##"<defs><marker id="kgar" markerWidth="9" markerHeight="9" refX="8" refY="3" orient="auto"><path d="M0,0 L8,3 L0,6 Z" fill="rgba(255,255,255,0.45)"/></marker></defs>"##,
1924    );
1925    svg.push_str(
1926        r##"<style>
1927.kge{stroke:rgba(167,139,250,0.55);stroke-width:1.5;fill:none;stroke-dasharray:5 4;animation:kgflow .9s linear infinite}
1928.kgn{stroke:rgba(255,255,255,0.9);stroke-width:1.5;animation:kgpulse 2.6s ease-in-out infinite}
1929.kgr{fill:rgba(255,255,255,0.5);font:9px ui-monospace,monospace;text-anchor:middle}
1930.kgl{fill:#e5e7eb;font:11px ui-sans-serif,system-ui;text-anchor:middle;font-weight:600}
1931@keyframes kgflow{to{stroke-dashoffset:-18}}
1932@keyframes kgpulse{0%,100%{opacity:1}50%{opacity:.72}}
1933</style>"##,
1934    );
1935    // Relations between one pair of signals run along one line, either way round, so they
1936    // share one label naming each relation once — apart, they overprint at one midpoint.
1937    let mut labels: Vec<((usize, usize), (f64, f64), Vec<&str>)> = Vec::new();
1938    for l in &kg.links {
1939        let (x1, y1) = pos[l.from];
1940        let (x2, y2) = pos[l.to];
1941        let (dx, dy) = (x2 - x1, y2 - y1);
1942        let len = (dx * dx + dy * dy).sqrt().max(1.0);
1943        let (ux, uy) = (dx / len, dy / len);
1944        let (sx, sy) = (x1 + ux * node_r, y1 + uy * node_r);
1945        let (ex, ey) = (x2 - ux * (node_r + 6.0), y2 - uy * (node_r + 6.0));
1946        let _ = write!(
1947            svg,
1948            r##"<line class="kge" x1="{sx:.1}" y1="{sy:.1}" x2="{ex:.1}" y2="{ey:.1}" marker-end="url(#kgar)"/>"##
1949        );
1950        let pair = (l.from.min(l.to), l.from.max(l.to));
1951        match labels.iter_mut().find(|(p, _, _)| *p == pair) {
1952            Some((_, _, names)) => {
1953                if !names.contains(&l.relation.as_str()) {
1954                    names.push(&l.relation);
1955                }
1956            }
1957            None => labels.push((
1958                pair,
1959                ((sx + ex) / 2.0, (sy + ey) / 2.0 - 2.0),
1960                vec![&l.relation],
1961            )),
1962        }
1963    }
1964    for (_, (mx, my), names) in &labels {
1965        let _ = write!(
1966            svg,
1967            r##"<text class="kgr" x="{mx:.1}" y="{my:.1}">{}</text>"##,
1968            esc(&names.join(" · "))
1969        );
1970    }
1971    for (i, node) in kg.nodes.iter().enumerate() {
1972        let (x, y) = pos[i];
1973        let _ = write!(
1974            svg,
1975            r##"<circle class="kgn" cx="{x:.1}" cy="{y:.1}" r="{node_r}" fill="{}"/>"##,
1976            color(&node.role)
1977        );
1978        let label = if node.width > 1 {
1979            format!("{}[{}]", node.name, node.width)
1980        } else {
1981            node.name.clone()
1982        };
1983        let _ = write!(
1984            svg,
1985            r##"<text class="kgl" x="{x:.1}" y="{:.1}">{}</text>"##,
1986            y + 28.0,
1987            esc(&label)
1988        );
1989    }
1990    svg.push_str("</svg>");
1991    svg
1992}
1993
1994/// Render a counterexample as a logic-analyzer waveform SVG: boolean signals as digital
1995/// square waves, multi-bit registers as value-labeled buses, with a sweeping playhead. Pure
1996/// SVG + CSS, drawn at its own size — a long trace scrolls in its panel rather than shrinking
1997/// its labels. Returns "" if empty.
1998pub(super) fn waveform_svg(wf: &logicaffeine_compile::codegen_sva::hw_pipeline::Waveform) -> String {
1999    use std::fmt::Write as _;
2000    let (ts, n) = (wf.timesteps, wf.signals.len());
2001    if ts == 0 || n == 0 {
2002        return String::new();
2003    }
2004    let (gutter, col_w, row_h, top) = (72.0_f64, 46.0_f64, 34.0_f64, 18.0_f64);
2005    let span = (ts as f64) * col_w;
2006    let (w, h) = (gutter + span + 10.0, top + (n as f64) * row_h + 6.0);
2007    let dur = (0.45 * ts as f64).max(1.2);
2008    let esc = |s: &str| {
2009        s.replace('&', "&amp;")
2010            .replace('<', "&lt;")
2011            .replace('>', "&gt;")
2012    };
2013
2014    let mut s = String::new();
2015    let _ = write!(
2016        s,
2017        r##"<svg viewBox="0 0 {w:.0} {h:.0}" width="{w:.0}" height="{h:.0}" xmlns="http://www.w3.org/2000/svg">"##
2018    );
2019    let _ = write!(
2020        s,
2021        r##"<style>
2022.wfg{{stroke:rgba(255,255,255,0.07);stroke-width:1}}
2023.wft{{fill:none;stroke:#22d3ee;stroke-width:2;stroke-linejoin:round}}
2024.wfb{{fill:rgba(96,165,250,0.12);stroke:#60a5fa;stroke-width:1.5}}
2025.wfv{{fill:#dbeafe;font:11px ui-monospace,monospace;text-anchor:middle}}
2026.wfn{{fill:#e5e7eb;font:11px ui-monospace,monospace;text-anchor:end}}
2027.wftl{{fill:rgba(255,255,255,0.4);font:9px ui-monospace,monospace;text-anchor:middle}}
2028.wfph{{stroke:#f472b6;stroke-width:1.5;opacity:.8;animation:wfsweep {dur:.1}s linear infinite}}
2029@keyframes wfsweep{{from{{transform:translateX(0)}}to{{transform:translateX({span:.0}px)}}}}
2030</style>"##
2031    );
2032    for t in 0..ts {
2033        let x = gutter + (t as f64) * col_w;
2034        let _ = write!(
2035            s,
2036            r##"<line class="wfg" x1="{x:.1}" y1="{top:.1}" x2="{x:.1}" y2="{:.1}"/>"##,
2037            h - 4.0
2038        );
2039        let _ = write!(
2040            s,
2041            r##"<text class="wftl" x="{:.1}" y="12">t{t}</text>"##,
2042            x + col_w / 2.0
2043        );
2044    }
2045    let xe = gutter + span;
2046    let _ = write!(
2047        s,
2048        r##"<line class="wfg" x1="{xe:.1}" y1="{top:.1}" x2="{xe:.1}" y2="{:.1}"/>"##,
2049        h - 4.0
2050    );
2051
2052    for (ri, sig) in wf.signals.iter().enumerate() {
2053        let rtop = top + (ri as f64) * row_h;
2054        let (hi, lo) = (rtop + 6.0, rtop + row_h - 12.0);
2055        let mid = (hi + lo) / 2.0;
2056        let label = if sig.width > 1 {
2057            format!("{}[{}]", sig.name, sig.width)
2058        } else {
2059            sig.name.clone()
2060        };
2061        let _ = write!(
2062            s,
2063            r##"<text class="wfn" x="{:.1}" y="{:.1}">{}</text>"##,
2064            gutter - 8.0,
2065            mid + 4.0,
2066            esc(&label)
2067        );
2068        if sig.width == 1 {
2069            let mut pts = String::new();
2070            for t in 0..ts {
2071                let x0 = gutter + (t as f64) * col_w;
2072                let lvl = match sig.values.get(t as usize) {
2073                    Some(Some(v)) => {
2074                        if *v != 0 {
2075                            hi
2076                        } else {
2077                            lo
2078                        }
2079                    }
2080                    _ => mid,
2081                };
2082                let _ = write!(pts, "{x0:.1},{lvl:.1} {:.1},{lvl:.1} ", x0 + col_w);
2083            }
2084            let _ = write!(s, r##"<polyline class="wft" points="{}"/>"##, pts.trim());
2085        } else {
2086            for t in 0..ts {
2087                if let Some(Some(v)) = sig.values.get(t as usize) {
2088                    let x0 = gutter + (t as f64) * col_w;
2089                    let _ = write!(
2090                        s,
2091                        r##"<rect class="wfb" x="{:.1}" y="{hi:.1}" width="{:.1}" height="{:.1}" rx="3"/>"##,
2092                        x0 + 2.0,
2093                        col_w - 4.0,
2094                        lo - hi
2095                    );
2096                    let _ = write!(
2097                        s,
2098                        r##"<text class="wfv" x="{:.1}" y="{:.1}">{v}</text>"##,
2099                        x0 + col_w / 2.0,
2100                        mid + 4.0
2101                    );
2102                }
2103            }
2104        }
2105    }
2106    let _ = write!(
2107        s,
2108        r##"<line class="wfph" x1="{gutter:.1}" y1="{top:.1}" x2="{gutter:.1}" y2="{:.1}"/>"##,
2109        h - 4.0
2110    );
2111    s.push_str("</svg>");
2112    s
2113}
2114
2115fn wf_val(sig: &logicaffeine_compile::codegen_sva::hw_pipeline::WaveSignal, t: usize) -> u64 {
2116    sig.values.get(t).and_then(|v| *v).unwrap_or(0)
2117}
2118
2119/// One signalized-intersection PHASE: a maximal run of the trace with one identical signal
2120/// state, plus the human wall-clock duration we give it for the animation.
2121#[derive(Clone, Copy, Debug, PartialEq)]
2122struct TrafficPhase {
2123    ns: u64,
2124    ew: u64,
2125    nsl: u64,
2126    ewl: u64,
2127    ped: u64,
2128    start: f64,
2129    dur: f64,
2130}
2131
2132impl TrafficPhase {
2133    fn val(&self, pfx: &str) -> u64 {
2134        match pfx {
2135            "ns" => self.ns,
2136            "ew" => self.ew,
2137            "nsl" => self.nsl,
2138            "ewl" => self.ewl,
2139            "ped" => self.ped,
2140            _ => 0,
2141        }
2142    }
2143}
2144
2145/// The whole animation plan derived from a counterexample/witness trace: the phase sequence on a
2146/// seconds timeline, plus the index of the phase whose state violates safety (the crash).
2147struct TrafficPlan {
2148    phases: Vec<TrafficPhase>,
2149    /// First trace timestep of each phase (so callers can still sample the raw signals).
2150    firsts: Vec<usize>,
2151    total: f64,
2152    conflict: Option<usize>,
2153}
2154
2155/// What the NS-through platoon does during phase `i`: nothing visible (red/yellow), drive straight
2156/// through (a normal green), or drive to the crosswalk and stop (the crash phase).
2157#[derive(Clone, Copy, Debug, PartialEq)]
2158enum NsDrive {
2159    Hidden,
2160    Through,
2161    CrashStop,
2162}
2163
2164/// Collapse a trace into the phase plan. `None` unless both `ns` and `ew` are present.
2165fn traffic_plan(
2166    wf: &logicaffeine_compile::codegen_sva::hw_pipeline::Waveform,
2167) -> Option<TrafficPlan> {
2168    use logicaffeine_compile::codegen_sva::hw_pipeline::WaveSignal;
2169    let get = |name: &str| {
2170        wf.signals
2171            .iter()
2172            .find(|s| s.name.eq_ignore_ascii_case(name))
2173    };
2174    let ns = get("ns")?;
2175    let ew = get("ew")?;
2176    let nsl = get("nsl");
2177    let ewl = get("ewl");
2178    let ped = get("ped");
2179    let n = (wf.timesteps as usize).max(1);
2180    let sv = |sig: &WaveSignal, t: usize| wf_val(sig, t);
2181    let svo = |sig: Option<&WaveSignal>, t: usize| sig.map_or(0u64, |s| wf_val(s, t));
2182    let state = |t: usize| (sv(ns, t), sv(ew, t), svo(nsl, t), svo(ewl, t), svo(ped, t));
2183
2184    let mut firsts: Vec<usize> = Vec::new();
2185    let mut prev: Option<(u64, u64, u64, u64, u64)> = None;
2186    for t in 0..n {
2187        let k = state(t);
2188        if Some(k) != prev {
2189            firsts.push(t);
2190            prev = Some(k);
2191        }
2192    }
2193    let states: Vec<(u64, u64, u64, u64, u64)> = firsts.iter().map(|&t| state(t)).collect();
2194    let nsc = states.len();
2195    let conflict = (0..nsc).find(|&i| {
2196        let (a, b, c, d, e) = states[i];
2197        (a != 0 && b != 0) || (e == 1 && (a != 0 || b != 0 || c != 0 || d != 0))
2198    });
2199    let mut phases = Vec::with_capacity(nsc);
2200    let mut acc = 0.0f64;
2201    for i in 0..nsc {
2202        let (a, b, c, d, e) = states[i];
2203        let dur = if Some(i) == conflict {
2204            3.6
2205        } else if e == 1 {
2206            7.0
2207        } else if a == 2 || b == 2 || c == 2 || d == 2 {
2208            1.3
2209        } else if a == 1 || b == 1 || c == 1 || d == 1 {
2210            2.6
2211        } else {
2212            1.0
2213        };
2214        phases.push(TrafficPhase {
2215            ns: a,
2216            ew: b,
2217            nsl: c,
2218            ewl: d,
2219            ped: e,
2220            start: acc,
2221            dur,
2222        });
2223        acc += dur;
2224    }
2225    Some(TrafficPlan {
2226        phases,
2227        firsts,
2228        total: acc.max(1.0),
2229        conflict,
2230    })
2231}
2232
2233fn ns_drive(plan: &TrafficPlan, i: usize) -> NsDrive {
2234    if plan.phases[i].ns != 1 {
2235        NsDrive::Hidden
2236    } else if plan.conflict == Some(i) {
2237        NsDrive::CrashStop
2238    } else {
2239        NsDrive::Through
2240    }
2241}
2242
2243/// The whole-second countdown shown on a phase's timer: `ceil(dur)`, `ceil(dur)-1`, … 1 (clamped
2244/// to a single digit).
2245fn countdown_seq(dur: f64) -> Vec<u32> {
2246    let secs = dur.ceil() as i32;
2247    (0..secs).map(|j| (secs - j).clamp(0, 9) as u32).collect()
2248}
2249
2250/// Easter egg: if a counterexample carries the signals of a signalized intersection
2251/// (`ns`/`ew` through, optional `nsl`/`ewl` protected left turns, optional `ped` pedestrian),
2252/// render a live intersection whose lamps step through the REAL trace — then flash CONFLICT at
2253/// the exact cycle the safety property is violated. Pure SVG + CSS, no JS. `None` otherwise.
2254///
2255/// Vehicle signals encode 0=red, 1=green, 2=yellow; `ped` encodes 0=don't-walk, 1=walk.
2256pub(super) fn traffic_svg(wf: &logicaffeine_compile::codegen_sva::hw_pipeline::Waveform) -> Option<String> {
2257    use logicaffeine_compile::codegen_sva::hw_pipeline::WaveSignal;
2258    use std::fmt::Write as _;
2259    let get = |name: &str| {
2260        wf.signals
2261            .iter()
2262            .find(|s| s.name.eq_ignore_ascii_case(name))
2263    };
2264    let ns = get("ns")?;
2265    let ew = get("ew")?;
2266    let nsl = get("nsl");
2267    let ewl = get("ewl");
2268    let ped = get("ped");
2269    let sv = |sig: &WaveSignal, t: usize| wf_val(sig, t);
2270
2271    // The phase plan + per-phase predicates are pure and unit-tested (see `traffic_viz_tests`).
2272    let plan = traffic_plan(wf)?;
2273    let scenes = &plan.firsts;
2274    let nsc = plan.phases.len();
2275    let conflict_scene = plan.conflict;
2276    let total = plan.total;
2277    let starts: Vec<f64> = plan.phases.iter().map(|ph| ph.start).collect();
2278    let durs: Vec<f64> = plan.phases.iter().map(|ph| ph.dur).collect();
2279    let p = |sec: f64| (sec / total * 100.0).clamp(0.0, 100.0);
2280
2281    // (prefix, signal, head_x, head_y, label, countdown_x, countdown_y)
2282    let mut vheads: Vec<(&str, &WaveSignal, f64, f64, &str, f64, f64)> = vec![
2283        ("ns", ns, 18.0, 16.0, "NS", 100.0, 17.0),
2284        ("ew", ew, 18.0, 278.0, "EW", 100.0, 279.0),
2285    ];
2286    if let Some(s) = nsl {
2287        vheads.push(("nsl", s, 184.0, 16.0, "NS \u{21B0}", 266.0, 17.0));
2288    }
2289    if let Some(s) = ewl {
2290        vheads.push(("ewl", s, 184.0, 278.0, "EW \u{21B0}", 266.0, 279.0));
2291    }
2292
2293    // A single seven-segment digit (lit segments only) at top-left (x, y).
2294    let seven_seg = |x: f64, y: f64, d: u32, color: &str| -> String {
2295        let segs: &str = match d {
2296            0 => "abcdef",
2297            1 => "bc",
2298            2 => "abged",
2299            3 => "abgcd",
2300            4 => "fgbc",
2301            5 => "afgcd",
2302            6 => "afgecd",
2303            7 => "abc",
2304            8 => "abcdefg",
2305            9 => "abcdfg",
2306            _ => "",
2307        };
2308        let (w, h, t) = (13.0f64, 22.0f64, 2.6f64);
2309        let half = h / 2.0;
2310        let mut g = String::new();
2311        for c in segs.chars() {
2312            let (rx, ry, rw, rh) = match c {
2313                'a' => (x + t, y, w - 2.0 * t, t),
2314                'b' => (x + w - t, y + t, t, half - 1.5 * t),
2315                'c' => (x + w - t, y + half + 0.5 * t, t, half - 1.5 * t),
2316                'd' => (x + t, y + h - t, w - 2.0 * t, t),
2317                'e' => (x, y + half + 0.5 * t, t, half - 1.5 * t),
2318                'f' => (x, y + t, t, half - 1.5 * t),
2319                'g' => (x + t, y + half - 0.5 * t, w - 2.0 * t, t),
2320                _ => (0.0, 0.0, 0.0, 0.0),
2321            };
2322            let _ = write!(
2323                g,
2324                r##"<rect x="{rx:.1}" y="{ry:.1}" width="{rw:.1}" height="{rh:.1}" rx="1" fill="{color}"/>"##
2325            );
2326        }
2327        g
2328    };
2329    // A small upright "walking person" glyph in `color`, centred on (cx, cy).
2330    let walk_icon = |cx: f64, cy: f64, color: &str| -> String {
2331        let mut g = String::new();
2332        let _ = write!(
2333            g,
2334            r##"<g stroke="{color}" stroke-width="2.6" stroke-linecap="round" fill="none">"##
2335        );
2336        let _ = write!(
2337            g,
2338            r##"<circle cx="{cx:.1}" cy="{:.1}" r="2.7" fill="{color}" stroke="none"/>"##,
2339            cy - 9.0
2340        );
2341        let _ = write!(
2342            g,
2343            r##"<line x1="{cx:.1}" y1="{:.1}" x2="{cx:.1}" y2="{:.1}"/>"##,
2344            cy - 6.0,
2345            cy + 1.0
2346        );
2347        let _ = write!(
2348            g,
2349            r##"<line x1="{cx:.1}" y1="{:.1}" x2="{:.1}" y2="{:.1}"/>"##,
2350            cy - 4.0,
2351            cx - 4.0,
2352            cy - 1.0
2353        );
2354        let _ = write!(
2355            g,
2356            r##"<line x1="{cx:.1}" y1="{:.1}" x2="{:.1}" y2="{:.1}"/>"##,
2357            cy - 4.0,
2358            cx + 4.0,
2359            cy - 2.0
2360        );
2361        let _ = write!(
2362            g,
2363            r##"<line x1="{cx:.1}" y1="{:.1}" x2="{:.1}" y2="{:.1}"/>"##,
2364            cy + 1.0,
2365            cx - 4.0,
2366            cy + 8.0
2367        );
2368        let _ = write!(
2369            g,
2370            r##"<line x1="{cx:.1}" y1="{:.1}" x2="{:.1}" y2="{:.1}"/>"##,
2371            cy + 1.0,
2372            cx + 4.0,
2373            cy + 7.0
2374        );
2375        g.push_str("</g>");
2376        g
2377    };
2378    // The orange raised-palm "DON'T WALK / STOP" hand, centred on (cx, cy).
2379    let hand_icon = |cx: f64, cy: f64| -> String {
2380        let mut g = String::from(r##"<g fill="#f59e0b">"##);
2381        let _ = write!(
2382            g,
2383            r##"<rect x="{:.1}" y="{:.1}" width="14" height="13" rx="4.5"/>"##,
2384            cx - 7.0,
2385            cy - 5.0
2386        );
2387        let _ = write!(
2388            g,
2389            r##"<rect x="{:.1}" y="{:.1}" width="3" height="8" rx="1.5"/>"##,
2390            cx - 7.0,
2391            cy - 11.0
2392        );
2393        let _ = write!(
2394            g,
2395            r##"<rect x="{:.1}" y="{:.1}" width="3" height="9" rx="1.5"/>"##,
2396            cx - 3.5,
2397            cy - 12.0
2398        );
2399        let _ = write!(
2400            g,
2401            r##"<rect x="{:.1}" y="{:.1}" width="3" height="9" rx="1.5"/>"##,
2402            cx + 0.5,
2403            cy - 12.0
2404        );
2405        let _ = write!(
2406            g,
2407            r##"<rect x="{:.1}" y="{:.1}" width="3" height="8" rx="1.5"/>"##,
2408            cx + 4.0,
2409            cy - 11.0
2410        );
2411        let _ = write!(
2412            g,
2413            r##"<rect x="{:.1}" y="{:.1}" width="5" height="3" rx="1.5"/>"##,
2414            cx - 10.5,
2415            cy - 1.0
2416        );
2417        g.push_str("</g>");
2418        g
2419    };
2420
2421    let mut style = String::from("<style>");
2422    // Lamp tracks (step-end): bright on the active colour, dim otherwise — one key per phase.
2423    for (pfx, sig, _, _, _, _, _) in &vheads {
2424        for (suffix, want) in [("R", 0u64), ("Y", 2), ("G", 1)] {
2425            let _ = write!(style, "@keyframes {pfx}{suffix}{{");
2426            for i in 0..nsc {
2427                let op = if sv(sig, scenes[i]) == want {
2428                    "1"
2429                } else {
2430                    "0.12"
2431                };
2432                let _ = write!(style, "{:.2}%{{opacity:{op}}}", p(starts[i]));
2433            }
2434            let last = if sv(sig, scenes[nsc - 1]) == want {
2435                "1"
2436            } else {
2437                "0.12"
2438            };
2439            let _ = write!(style, "100%{{opacity:{last}}}}}");
2440        }
2441    }
2442    // Pedestrian WALK / STOP icon swap (full on/off).
2443    if let Some(pp) = ped {
2444        for (name, want) in [("pedWALK", 1u64), ("pedSTOP", 0)] {
2445            let _ = write!(style, "@keyframes {name}{{");
2446            for i in 0..nsc {
2447                let op = if sv(pp, scenes[i]) == want { "1" } else { "0" };
2448                let _ = write!(style, "{:.2}%{{opacity:{op}}}", p(starts[i]));
2449            }
2450            let last = if sv(pp, scenes[nsc - 1]) == want {
2451                "1"
2452            } else {
2453                "0"
2454            };
2455            let _ = write!(style, "100%{{opacity:{last}}}}}");
2456        }
2457    }
2458    // Vehicle platoons — cars are released on GREEN, drive straight THROUGH, and are hidden on
2459    // red (none left drifting/parked in the road). Opacity snaps per phase (step-end); position
2460    // glides (linear); nested groups compose them. On a crash run the NS platoon drives to the
2461    // crosswalk and FREEZES on impact, so its real lead car is the one that strikes the
2462    // pedestrian. Lead glyph base y=-30 / x=-30 → +240px lands on the south crosswalk, +360px
2463    // drives clear off-screen.
2464    {
2465        let _ = write!(style, "@keyframes nsplat_op{{");
2466        for i in 0..nsc {
2467            let o = if ns_drive(&plan, i) == NsDrive::Hidden {
2468                "0"
2469            } else {
2470                "1"
2471            };
2472            let _ = write!(style, "{:.2}%{{opacity:{o}}}", p(starts[i]));
2473        }
2474        let lo = if ns_drive(&plan, nsc - 1) == NsDrive::Hidden {
2475            "0"
2476        } else {
2477            "1"
2478        };
2479        let _ = write!(style, "100%{{opacity:{lo}}}}}");
2480        let _ = write!(style, "@keyframes nsplat_mv{{");
2481        for i in 0..nsc {
2482            let t0 = starts[i];
2483            match ns_drive(&plan, i) {
2484                NsDrive::Through => {
2485                    let _ = write!(style, "{:.2}%{{transform:translateY(0px)}}", p(t0));
2486                    let _ = write!(
2487                        style,
2488                        "{:.2}%{{transform:translateY(360px)}}",
2489                        p(t0 + durs[i])
2490                    );
2491                }
2492                NsDrive::CrashStop => {
2493                    let _ = write!(style, "{:.2}%{{transform:translateY(0px)}}", p(t0));
2494                    let _ = write!(style, "{:.2}%{{transform:translateY(240px)}}", p(t0 + 1.8));
2495                    let _ = write!(
2496                        style,
2497                        "{:.2}%{{transform:translateY(240px)}}",
2498                        p(t0 + durs[i])
2499                    );
2500                }
2501                NsDrive::Hidden => {
2502                    let _ = write!(style, "{:.2}%{{transform:translateY(0px)}}", p(t0));
2503                }
2504            }
2505        }
2506        let lty = match ns_drive(&plan, nsc - 1) {
2507            NsDrive::Through => "360px",
2508            NsDrive::CrashStop => "240px",
2509            NsDrive::Hidden => "0px",
2510        };
2511        let _ = write!(style, "100%{{transform:translateY({lty})}}}}");
2512    }
2513    {
2514        let _ = write!(style, "@keyframes ewplat_op{{");
2515        for i in 0..nsc {
2516            let o = if sv(ew, scenes[i]) == 1 { "1" } else { "0" };
2517            let _ = write!(style, "{:.2}%{{opacity:{o}}}", p(starts[i]));
2518        }
2519        let lo = if sv(ew, scenes[nsc - 1]) == 1 {
2520            "1"
2521        } else {
2522            "0"
2523        };
2524        let _ = write!(style, "100%{{opacity:{lo}}}}}");
2525        let _ = write!(style, "@keyframes ewplat_mv{{");
2526        for i in 0..nsc {
2527            let t0 = starts[i];
2528            if sv(ew, scenes[i]) == 1 {
2529                let _ = write!(style, "{:.2}%{{transform:translateX(0px)}}", p(t0));
2530                let _ = write!(
2531                    style,
2532                    "{:.2}%{{transform:translateX(360px)}}",
2533                    p(t0 + durs[i])
2534                );
2535            } else {
2536                let _ = write!(style, "{:.2}%{{transform:translateX(0px)}}", p(t0));
2537            }
2538        }
2539        let lty = if sv(ew, scenes[nsc - 1]) == 1 {
2540            "360px"
2541        } else {
2542            "0px"
2543        };
2544        let _ = write!(style, "100%{{transform:translateX({lty})}}}}");
2545    }
2546    // Safe runs: the pedestrian crosses the south crosswalk and reaches the far side unharmed.
2547    if ped.is_some() && conflict_scene.is_none() {
2548        let pp = ped.unwrap();
2549        let mut off = 0.0f64;
2550        let _ = write!(style, "@keyframes pedcross{{");
2551        for i in 0..nsc {
2552            let vis = if sv(pp, scenes[i]) == 1 { "1" } else { "0" };
2553            let _ = write!(
2554                style,
2555                "{:.2}%{{transform:translateX({off:.1}px);opacity:{vis}}}",
2556                p(starts[i])
2557            );
2558            if sv(pp, scenes[i]) == 1 {
2559                off += 11.0 * durs[i];
2560            }
2561        }
2562        let _ = write!(
2563            style,
2564            "100%{{transform:translateX({off:.1}px);opacity:0}}}}"
2565        );
2566    }
2567    // Crash runs: the pedestrian walks into the lane and is struck as the queue reaches them.
2568    if let Some(csi) = conflict_scene {
2569        let c0 = starts[csi];
2570        let impact = c0 + 1.8;
2571        let _ = write!(style, "@keyframes doomwalk{{0%{{opacity:0;transform:translateX(0px)}}{:.2}%{{opacity:0;transform:translateX(0px)}}{:.2}%{{opacity:1;transform:translateX(0px)}}{:.2}%{{opacity:1;transform:translateX(30px)}}{:.2}%{{opacity:0}}100%{{opacity:0}}}}", p(c0), p(c0 + 0.2), p(impact), p(impact + 0.25));
2572        let _ = write!(style, "@keyframes impact{{0%{{opacity:0}}{:.2}%{{opacity:0}}{:.2}%{{opacity:1}}100%{{opacity:0.95}}}}", p(impact), p(impact + 0.2));
2573    }
2574    // Protected-left turn cars: one vehicle curves through the intersection during each nsl/ewl
2575    // GREEN, so the left phases aren't visually dead. An L-path (approach, then turn).
2576    let nsl_g = nsl.and_then(|sig| (0..nsc).find(|&i| sv(sig, scenes[i]) == 1));
2577    let ewl_g = ewl.and_then(|sig| (0..nsc).find(|&i| sv(sig, scenes[i]) == 1));
2578    if let Some(i) = nsl_g {
2579        let (w0, wm, w1) = (
2580            p(starts[i]),
2581            p(starts[i] + durs[i] * 0.5),
2582            p(starts[i] + durs[i]),
2583        );
2584        let we = (w1 + 1.0).min(100.0);
2585        let _ = write!(style, "@keyframes nslturn{{0%{{opacity:0;transform:translate(0px,-210px)}}{w0:.2}%{{opacity:1;transform:translate(0px,-210px)}}{wm:.2}%{{opacity:1;transform:translate(0px,0px)}}{w1:.2}%{{opacity:1;transform:translate(175px,0px)}}{we:.2}%{{opacity:0;transform:translate(175px,0px)}}100%{{opacity:0}}}}");
2586    }
2587    if let Some(i) = ewl_g {
2588        let (w0, wm, w1) = (
2589            p(starts[i]),
2590            p(starts[i] + durs[i] * 0.5),
2591            p(starts[i] + durs[i]),
2592        );
2593        let we = (w1 + 1.0).min(100.0);
2594        let _ = write!(style, "@keyframes ewlturn{{0%{{opacity:0;transform:translate(-210px,0px)}}{w0:.2}%{{opacity:1;transform:translate(-210px,0px)}}{wm:.2}%{{opacity:1;transform:translate(0px,0px)}}{w1:.2}%{{opacity:1;transform:translate(0px,175px)}}{we:.2}%{{opacity:0;transform:translate(0px,175px)}}100%{{opacity:0}}}}");
2595    }
2596    // Seven-segment countdown timers: one digit per second of each lit phase, on the pedestrian
2597    // signal (amber) and beside each vehicle head (green while go, amber while caution).
2598    let mut cds: Vec<(f64, f64, &str, usize)> = Vec::new();
2599    if let Some(pp) = ped {
2600        for i in 0..nsc {
2601            if sv(pp, scenes[i]) == 1 {
2602                cds.push((286.0, 68.0, "#fbbf24", i));
2603            }
2604        }
2605    }
2606    for (_pfx, sig, _hx, _hy, _lab, cdx, cdy) in &vheads {
2607        for i in 0..nsc {
2608            let v = sv(sig, scenes[i]);
2609            if v == 1 || v == 2 {
2610                cds.push((*cdx, *cdy, if v == 1 { "#22c55e" } else { "#fbbf24" }, i));
2611            }
2612        }
2613    }
2614    let mut cd_body = String::new();
2615    let mut cdc = 0usize;
2616    for (x, y, color, i) in &cds {
2617        for (k, val) in countdown_seq(durs[*i]).into_iter().enumerate() {
2618            let t0 = starts[*i] + k as f64;
2619            let t1 = (t0 + 1.0).min(starts[*i] + durs[*i]);
2620            let name = format!("cd{cdc}");
2621            cdc += 1;
2622            let _ = write!(style, "@keyframes {name}{{0%{{opacity:0}}{:.2}%{{opacity:0}}{:.2}%{{opacity:1}}{:.2}%{{opacity:0}}100%{{opacity:0}}}}", p(t0), p(t0), p(t1));
2623            let _ = write!(
2624                cd_body,
2625                r##"<g class="st" style="animation-name:{name}">{}</g>"##,
2626                seven_seg(*x, *y, val, *color)
2627            );
2628        }
2629    }
2630    let _ = write!(style, ".st{{animation-duration:{total:.1}s;animation-timing-function:step-end;animation-iteration-count:infinite}}");
2631    let _ = write!(style, ".fl{{animation-duration:{total:.1}s;animation-timing-function:linear;animation-iteration-count:infinite}}");
2632    style.push_str("</style>");
2633
2634    let mut s = String::new();
2635    let _ = write!(
2636        s,
2637        r##"<svg viewBox="0 0 320 320" width="100%" style="max-height:320px" xmlns="http://www.w3.org/2000/svg">"##
2638    );
2639    s.push_str(&style);
2640    // cross roads + lane markings
2641    s.push_str(r##"<rect x="0" y="128" width="320" height="64" fill="#26262b"/><rect x="128" y="0" width="64" height="320" fill="#26262b"/>"##);
2642    s.push_str(r##"<line x1="0" y1="160" x2="320" y2="160" stroke="#6b5d2e" stroke-width="2" stroke-dasharray="11 9"/><line x1="160" y1="0" x2="160" y2="320" stroke="#6b5d2e" stroke-width="2" stroke-dasharray="11 9"/>"##);
2643    // crosswalk hatching across the south leg
2644    if ped.is_some() {
2645        for i in 0..6 {
2646            let x = 133.0 + i as f64 * 10.0;
2647            let _ = write!(
2648                s,
2649                r##"<rect x="{x:.0}" y="202" width="5" height="22" fill="rgba(255,255,255,0.22)"/>"##
2650            );
2651        }
2652    }
2653    // NS platoon (cyan, southbound) + EW platoon (pink, eastbound). Outer group snaps opacity per
2654    // phase (released on green / hidden on red); inner group glides the position. Three cars each
2655    // so a green release reads as a small platoon; lead car base y=-30 / x=-30.
2656    s.push_str(r##"<g class="st" style="animation-name:nsplat_op"><g class="fl" style="animation-name:nsplat_mv">"##);
2657    for k in 0..3 {
2658        let y = -30 - k * 52;
2659        let _ = write!(
2660            s,
2661            r##"<rect x="139" y="{y}" width="18" height="30" rx="3" fill="#38bdf8"/><rect x="143" y="{}" width="10" height="4" rx="1" fill="rgba(0,0,0,0.35)"/>"##,
2662            y + 6
2663        );
2664    }
2665    s.push_str("</g></g>");
2666    s.push_str(r##"<g class="st" style="animation-name:ewplat_op"><g class="fl" style="animation-name:ewplat_mv">"##);
2667    for k in 0..3 {
2668        let x = -30 - k * 52;
2669        let _ = write!(
2670            s,
2671            r##"<rect x="{x}" y="163" width="30" height="18" rx="3" fill="#f472b6"/><rect x="{}" y="167" width="4" height="10" rx="1" fill="rgba(0,0,0,0.35)"/>"##,
2672            x + 6
2673        );
2674    }
2675    s.push_str("</g></g>");
2676    // Safe run: the pedestrian crosses unharmed.
2677    if ped.is_some() && conflict_scene.is_none() {
2678        let _ = write!(
2679            s,
2680            r##"<g class="fl" style="animation-name:pedcross">{}</g>"##,
2681            walk_icon(120.0, 209.0, "#fde047")
2682        );
2683    }
2684    // Protected-left turn cars (one per left phase) — cyan for NS-left, pink for EW-left.
2685    if nsl_g.is_some() {
2686        s.push_str(r##"<g class="fl" style="animation-name:nslturn"><rect x="140" y="142" width="16" height="16" rx="3" fill="#38bdf8"/><rect x="143" y="145" width="10" height="4" rx="1" fill="rgba(0,0,0,0.35)"/></g>"##);
2687    }
2688    if ewl_g.is_some() {
2689        s.push_str(r##"<g class="fl" style="animation-name:ewlturn"><rect x="140" y="142" width="16" height="16" rx="3" fill="#f472b6"/><rect x="143" y="145" width="10" height="4" rx="1" fill="rgba(0,0,0,0.35)"/></g>"##);
2690    }
2691    // Crash run: the doomed pedestrian who walks into the lane and is struck.
2692    if conflict_scene.is_some() && ped.is_some() {
2693        let _ = write!(
2694            s,
2695            r##"<g class="fl" style="animation-name:doomwalk">{}</g>"##,
2696            walk_icon(120.0, 209.0, "#fde047")
2697        );
2698    }
2699    // vehicle signal heads + dim "8" backdrop for each countdown
2700    for (pfx, _sig, x, y, label, cdx, cdy) in &vheads {
2701        let (rx, yx, gx) = (x + 16.0, x + 39.0, x + 62.0);
2702        let cy = y + 14.0;
2703        let lab_y = if *y < 100.0 { y - 4.0 } else { y + 42.0 };
2704        let _ = write!(
2705            s,
2706            r##"<rect x="{x:.0}" y="{y:.0}" width="78" height="28" rx="7" fill="#141418" stroke="rgba(255,255,255,0.15)"/>"##
2707        );
2708        let _ = write!(
2709            s,
2710            r##"<circle class="st" style="animation-name:{pfx}R" cx="{rx:.0}" cy="{cy:.0}" r="9" fill="#ef4444"/><circle class="st" style="animation-name:{pfx}Y" cx="{yx:.0}" cy="{cy:.0}" r="9" fill="#fbbf24"/><circle class="st" style="animation-name:{pfx}G" cx="{gx:.0}" cy="{cy:.0}" r="9" fill="#22c55e"/>"##
2711        );
2712        let _ = write!(
2713            s,
2714            r##"<text x="{:.0}" y="{lab_y:.0}" fill="rgba(255,255,255,0.6)" text-anchor="middle" font-size="11" font-family="ui-monospace,monospace">{label}</text>"##,
2715            x + 39.0
2716        );
2717        s.push_str(&seven_seg(*cdx, *cdy, 8, "rgba(255,255,255,0.06)"));
2718    }
2719    // pedestrian signal head: WALK person / STOP hand + a dim "8" countdown backdrop
2720    if ped.is_some() {
2721        s.push_str(r##"<rect x="238" y="54" width="72" height="52" rx="6" fill="#141418" stroke="rgba(255,255,255,0.15)"/>"##);
2722        let _ = write!(
2723            s,
2724            r##"<g class="st" style="animation-name:pedWALK">{}</g>"##,
2725            walk_icon(258.0, 80.0, "#34d399")
2726        );
2727        let _ = write!(
2728            s,
2729            r##"<g class="st" style="animation-name:pedSTOP">{}</g>"##,
2730            hand_icon(258.0, 80.0)
2731        );
2732        s.push_str(&seven_seg(286.0, 68.0, 8, "rgba(255,255,255,0.06)"));
2733        s.push_str(r##"<text x="274" y="100" fill="rgba(255,255,255,0.55)" text-anchor="middle" font-size="9" font-family="ui-monospace,monospace">PED</text>"##);
2734    }
2735    // the ticking countdown digits, drawn over their dim backdrops
2736    s.push_str(&cd_body);
2737    // Impact: the felled pedestrian (red), an impact burst, and the banner.
2738    if conflict_scene.is_some() {
2739        let mut g = String::from(r##"<g class="st" style="animation-name:impact">"##);
2740        g.push_str(r##"<circle cx="150" cy="207" r="15" fill="rgba(251,191,36,0.6)"/>"##);
2741        g.push_str(r##"<path d="M150,190 L155,202 L168,207 L155,212 L150,224 L145,212 L132,207 L145,202 Z" fill="#fbbf24"/>"##);
2742        if ped.is_some() {
2743            g.push_str(r##"<ellipse cx="174" cy="216" rx="12" ry="4.5" fill="#ef4444"/><circle cx="160" cy="214" r="4" fill="#ef4444"/>"##);
2744            g.push_str(r##"<text x="160" y="116" fill="#fca5a5" text-anchor="middle" font-size="13" font-weight="700" font-family="ui-sans-serif">⚠ CAR HITS PEDESTRIAN</text>"##);
2745        } else {
2746            g.push_str(r##"<text x="160" y="116" fill="#fca5a5" text-anchor="middle" font-size="14" font-weight="700" font-family="ui-sans-serif">⚠ CONFLICT</text>"##);
2747        }
2748        g.push_str("</g>");
2749        s.push_str(&g);
2750    }
2751    s.push_str("</svg>");
2752    Some(s)
2753}
2754
2755#[cfg(test)]
2756#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/formula_on_screen_tests.rs"]
2757mod formula_on_screen_tests;
2758
2759#[cfg(test)]
2760#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/panel_title_tests.rs"]
2761mod panel_title_tests;
2762
2763#[cfg(test)]
2764#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/logic_column_tests.rs"]
2765mod logic_column_tests;
2766
2767#[cfg(test)]
2768#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/knowledge_graph_tests.rs"]
2769mod knowledge_graph_tests;
2770
2771#[cfg(test)]
2772#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/waveform_tests.rs"]
2773mod waveform_tests;
2774
2775#[cfg(test)]
2776#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/traffic_viz_tests.rs"]
2777mod traffic_viz_tests;
2778
2779/// The prerendered Studio is the page for a bare `/studio`, opened on `opened`, and the site serves
2780/// that one copy for every deep link to a file as well. So, before the copy paints its panels, this
2781/// reads the link's `file` and, when it names another file, sets the class that keeps the copy's
2782/// panels unpainted until the app draws the file the link asked for. It runs only in the prerendered
2783/// copy, ahead of the app and its router, and only compares: nothing from the address reaches the
2784/// page.
2785fn prerender_guard(opened: &str) -> String {
2786    let opened = serde_json::to_string(opened)
2787        .unwrap_or_default()
2788        .replace("</", "<\\/");
2789    PRERENDER_GUARD.replace("__OPENED__", &opened)
2790}
2791
2792/// [`prerender_guard`]'s script. It reads `file` exactly as the router does: the whole query
2793/// percent-decoded (a `%` without two hex digits kept as it is, and the query left undecoded when the
2794/// bytes are not UTF-8), then split into pairs at `&` and `=`, the last `file` winning. Then it reads
2795/// the path as the opening does: an empty one is no file, and a path without a leading slash gains
2796/// one.
2797const PRERENDER_GUARD: &str = r#"(function () {
2798  var opened = __OPENED__;
2799  function decode(text) {
2800    var bytes = [], at = 0, utf8 = new TextEncoder();
2801    while (at < text.length) {
2802      if (text[at] === '%' && /^[0-9A-Fa-f]{2}$/.test(text.slice(at + 1, at + 3))) {
2803        bytes.push(parseInt(text.slice(at + 1, at + 3), 16));
2804        at += 3;
2805      } else {
2806        var ch = String.fromCodePoint(text.codePointAt(at));
2807        utf8.encode(ch).forEach(function (b) { bytes.push(b); });
2808        at += ch.length;
2809      }
2810    }
2811    try { return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(new Uint8Array(bytes)); }
2812    catch (e) { return text; }
2813  }
2814  var file = null;
2815  decode(location.search.slice(1)).split('&').forEach(function (pair) {
2816    var at = pair.indexOf('=');
2817    if (at >= 0 && pair.slice(0, at) === 'file') file = pair.slice(at + 1);
2818  });
2819  if (file === null || file === '' || (file.charAt(0) === '/' ? file : '/' + file) === opened) return;
2820  document.documentElement.classList.add('studio-opens-elsewhere');
2821})();"#;
2822
2823/// Why New file cannot make a file yet: it writes to the reader's store, which has not answered, or
2824/// could not be opened. `None` once the store is ready.
2825fn why_new_file_waits(ready: bool, failed: bool) -> Option<String> {
2826    match (ready, failed) {
2827        (true, _) => None,
2828        (false, true) => Some("Your files could not be opened".to_string()),
2829        (false, false) => Some("Your files are still loading".to_string()),
2830    }
2831}
2832
2833/// Keep the address bar on the canonical shareable URL for the open file
2834/// without pushing a history entry.
2835#[cfg(target_arch = "wasm32")]
2836fn sync_studio_url(vfs_path: &str) {
2837    crate::ui::router::replace_bar_url(&crate::ui::router::studio_file_url(vfs_path));
2838}
2839
2840/// The next free `untitled[-N].<ext>` filename for a new Studio file, skipping any
2841/// name that already exists in `/workspace` (via `exists`). `untitled.logos`, then
2842/// `untitled-1.logos`, `untitled-2.logos`, … — so repeated "New file" clicks never
2843/// collide or overwrite an existing user file.
2844#[cfg(any(target_arch = "wasm32", test))]
2845fn fresh_untitled_name(ext: &str, exists: impl Fn(&str) -> bool) -> String {
2846    let base = format!("untitled.{ext}");
2847    if !exists(&base) {
2848        return base;
2849    }
2850    let mut n = 1;
2851    loop {
2852        let candidate = format!("untitled-{n}.{ext}");
2853        if !exists(&candidate) {
2854            return candidate;
2855        }
2856        n += 1;
2857    }
2858}
2859
2860#[cfg(test)]
2861#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/new_file_tests.rs"]
2862mod new_file_tests;
2863
2864#[cfg(test)]
2865#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/studio/new_file_wait_tests.rs"]
2866mod new_file_wait_tests;
2867
2868#[component(lazy)]
2869pub fn Studio(file: Option<String>) -> Element {
2870    // What the Studio opens on, decided from the route alone — the same on the server that
2871    // prerenders the page as in the browser — so its first frame is already the open file's mode
2872    // and text (studio_opening.rs).
2873    let opening = use_hook(|| StudioOpening::for_route(file.as_deref()));
2874    // The workbench: the Studio's toolbar, files, editor and output columns (studio_workbench.rs).
2875    // The examples' part of the tree is the site's own, there from the first frame. The reader's
2876    // files join it once their store answers.
2877    let state = use_workbench(&opening, examples_tree);
2878    #[cfg(target_arch = "wasm32")]
2879    let WorkbenchState { mut file_tree, mut current_file, mut fault, mut program_store, mode, .. } = state;
2880    let mut active_tab = state.active_tab;
2881
2882    let mut vfs_error = use_signal(|| None::<String>); // Track VFS errors for display
2883    let vfs_is_fallback = use_signal(|| false); // Track if using IndexedDB fallback
2884
2885    // VFS initialization flag
2886    let mut vfs_initialized = use_signal(|| false);
2887
2888    // The Studio's files once the reader's store has answered: the shipped examples over that
2889    // store (studio_files.rs). Acquired once, then reused for every file switch instead of
2890    // spawning (and leaking) a fresh worker each time.
2891    #[cfg(target_arch = "wasm32")]
2892    let mut vfs_handle = use_signal(|| None::<StudioFiles<WebVfs>>);
2893
2894    // Touch gesture state for swipe detection
2895    let mut touch_start_x = use_signal(|| 0.0f64);
2896    let mut touch_start_y = use_signal(|| 0.0f64);
2897    // Whether the touch began where a sideways swipe may change the pane: not in the editor or a wide
2898    // picture, which scroll sideways themselves, nor in the files or the debugger.
2899    let mut swipe_switches = use_signal(|| false);
2900
2901    // On mount, the address bar names the opening's file, and the reader's store loads beside the
2902    // workbench (which runs that file at once when the site carries its text): its files join the
2903    // tree, and it answers for the opening's file, which changes the page only as
2904    // `StudioOpening::arrival` allows. Nothing is written to open the Studio; afterwards, copies of
2905    // the examples an earlier Studio wrote are removed.
2906    #[cfg(target_arch = "wasm32")]
2907    use_effect({
2908        let opening = opening.clone();
2909        move || {
2910            if *vfs_initialized.read() {
2911                return;
2912            }
2913            vfs_initialized.set(true);
2914
2915            let opening = opening.clone();
2916            let mut vfs_is_fallback = vfs_is_fallback;
2917            if opening.text.is_some() {
2918                sync_studio_url(&opening.path);
2919            }
2920
2921            spawn(async move {
2922                // The reader's store: OPFS, or IndexedDB where the browser offers no OPFS.
2923                let read = match get_platform_vfs_with_fallback().await {
2924                    Ok(store) => {
2925                        if store.is_fallback() {
2926                            vfs_is_fallback.set(true);
2927                        }
2928                        let files = StudioFiles::new(store);
2929                        vfs_handle.set(Some(files.clone()));
2930                        program_store.set(Some(std::sync::Arc::new(files.clone()) as std::sync::Arc<dyn Vfs>));
2931                        let (tree, read) = open_store(&files, &opening.path).await;
2932                        match tree {
2933                            Ok(tree) => {
2934                                let tree = tree.with_expansion_of(&file_tree.peek());
2935                                if *file_tree.peek() != tree {
2936                                    file_tree.set(tree);
2937                                }
2938                            }
2939                            Err(e) => {
2940                                vfs_error.set(Some(format!("Failed to load file tree: {:?}", e)));
2941                            }
2942                        }
2943                        read
2944                    }
2945                    Err(e) => {
2946                        vfs_error.set(Some(format!("VFS INIT FAILED: {:?}", e)));
2947                        None
2948                    }
2949                };
2950
2951                let open = current_file.peek().clone();
2952                let shown = state.editor(opening.mode).peek().clone();
2953                let replacement = match opening.arrival(open.as_deref(), &shown, read) {
2954                    Arrival::Keep => None,
2955                    Arrival::Open(content) => Some((opening.path, content)),
2956                    Arrival::Fallback(first) => {
2957                        Some((first.path, first.text.unwrap_or_default().to_string()))
2958                    }
2959                };
2960                if let Some((path, content)) = replacement {
2961                    current_file.set(Some(path.clone()));
2962                    sync_studio_url(&path);
2963                    state.open(path, content).await;
2964                }
2965
2966                let files = vfs_handle.peek().clone();
2967                if let Some(files) = files {
2968                    let _ = files.retire_old_copies().await;
2969                }
2970            });
2971        }
2972    });
2973
2974    // On native, no VFS - just show empty tree with message
2975    #[cfg(not(target_arch = "wasm32"))]
2976    use_effect(move || {
2977        if *vfs_initialized.read() {
2978            return;
2979        }
2980        vfs_initialized.set(true);
2981        vfs_error.set(Some("VFS not available on native".to_string()));
2982    });
2983
2984    // Mobile touch handlers for swipe gestures
2985    let panes_fixed = state.panes_fixed;
2986    let handle_touch_start = move |evt: TouchEvent| {
2987        let touches = evt.data().touches();
2988        if let Some(touch) = touches.first() {
2989            let coords = touch.client_coordinates();
2990            touch_start_x.set(coords.x);
2991            touch_start_y.set(coords.y);
2992        }
2993        #[cfg(target_arch = "wasm32")]
2994        let scrolls_itself = {
2995            use wasm_bindgen::JsCast;
2996            evt.data()
2997                .downcast::<web_sys::TouchEvent>()
2998                .and_then(|e| e.target())
2999                .and_then(|t| t.dyn_into::<web_sys::Element>().ok())
3000                .and_then(|el| el.closest(".code-editor, .panel-body.wide, .studio-sidebar, .dbg-drawer").ok().flatten())
3001                .is_some()
3002        };
3003        #[cfg(not(target_arch = "wasm32"))]
3004        let scrolls_itself = false;
3005        swipe_switches.set(*panes_fixed.peek() && !scrolls_itself);
3006    };
3007
3008    let handle_touch_end = move |evt: TouchEvent| {
3009        let changed = evt.data().touches_changed();
3010        if let Some(touch) = changed.first() {
3011            let coords = touch.client_coordinates();
3012            let end_x = coords.x;
3013            let end_y = coords.y;
3014            let dx = end_x - *touch_start_x.read();
3015            let dy = end_y - *touch_start_y.read();
3016
3017            if *swipe_switches.peek() && dx.abs() > dy.abs() && dx.abs() > 50.0 {
3018                let current = *active_tab.read();
3019                if dx < 0.0 {
3020                    match current {
3021                        MobileTab::Panel1 => active_tab.set(MobileTab::Panel2),
3022                        MobileTab::Panel2 => active_tab.set(MobileTab::Panel3),
3023                        MobileTab::Panel3 => {}
3024                    }
3025                } else {
3026                    match current {
3027                        MobileTab::Panel1 => {}
3028                        MobileTab::Panel2 => active_tab.set(MobileTab::Panel1),
3029                        MobileTab::Panel3 => active_tab.set(MobileTab::Panel2),
3030                    }
3031                }
3032            }
3033        }
3034    };
3035
3036    // New file writes to the reader's store, so it waits, and says so, until the store has answered.
3037    #[cfg(target_arch = "wasm32")]
3038    let files_ready = vfs_handle.read().is_some();
3039    #[cfg(not(target_arch = "wasm32"))]
3040    let files_ready = false;
3041    let new_file_waits = why_new_file_waits(files_ready, vfs_error.read().is_some());
3042
3043    // A file chosen in the Files tree, which the workbench has opened when the site carries it: the
3044    // address bar names it, and a reader's own file is read from their store.
3045    let on_choose = move |path: String| {
3046        #[cfg(target_arch = "wasm32")]
3047        {
3048            // Update URL with file parameter for shareable links
3049            sync_studio_url(&path);
3050            if example_text(&path).is_none() {
3051                let path_clone = path.clone();
3052                spawn(async move {
3053                    // Reuse the cached files (one worker) instead of spawning a
3054                    // fresh one per file switch; acquire once if not ready yet.
3055                    // Bind the clone first so the peek() read-guard drops before
3056                    // the None arm calls vfs_handle.set() (avoids a borrow panic).
3057                    let cached = vfs_handle.peek().clone();
3058                    let vfs_result = match cached {
3059                        Some(vfs) => Ok(vfs),
3060                        None => get_platform_vfs_with_fallback().await.map(|store| {
3061                            let files = StudioFiles::new(store);
3062                            vfs_handle.set(Some(files.clone()));
3063                            program_store.set(Some(std::sync::Arc::new(files.clone()) as std::sync::Arc<dyn Vfs>));
3064                            files
3065                        }),
3066                    };
3067                    match vfs_result {
3068                        Ok(vfs) => {
3069                            match vfs.read_to_string(&path_clone).await {
3070                                Ok(content) => {
3071                                    active_tab.set(MobileTab::Panel2);
3072                                    state.open(path_clone, content).await;
3073                                }
3074                                Err(e) => {
3075                                    vfs_error.set(Some(format!("Failed to read file: {:?}", e)));
3076                                }
3077                            }
3078                        }
3079                        Err(e) => {
3080                            vfs_error.set(Some(format!("VFS INIT FAILED: {:?}", e)));
3081                        }
3082                    }
3083                });
3084            }
3085        }
3086        #[cfg(not(target_arch = "wasm32"))]
3087        let _ = path;
3088    };
3089
3090    // New file writes a file into the reader's store and opens it.
3091    let on_new_file = move |_: ()| {
3092        // VFS + editor signals are the browser's; the SSR prerender has no
3093        // filesystem, so the whole action is wasm-only (mirrors on_select).
3094        #[cfg(target_arch = "wasm32")]
3095        {
3096            let vfs = vfs_handle.read().clone();
3097            let current = *mode.read();
3098            spawn(async move {
3099                let Some(vfs) = vfs else { return; };
3100                let (ext, template): (&str, &str) = match current {
3101                    StudioMode::Code => ("logos", "Show \"Hello from a new file!\".\n"),
3102                    StudioMode::Math => ("math", "-- A fresh proof. Define your terms, then prove them.\n"),
3103                    StudioMode::Hardware => ("hw", "The grant signal is asserted within 2 cycles of a request.\n"),
3104                    StudioMode::Logic => ("logic", "Every philosopher thinks.\n"),
3105                    // The Studio's own counter example, minus the commentary: a new Web
3106                    // file has to COMPILE, because the preview builds it on the next
3107                    // keystroke — an empty or prose placeholder would greet the user
3108                    // with a build error.
3109                    StudioMode::Web => (
3110                        "web",
3111                        "## Component App\nState:\n    Let count be 0.\nActions:\n    To bump:\n        Set count to count + 1.\nView:\n    <h1>Count: {count}</h1>\n    <button on-click={bump}>+1</button>\n\n## Main\nMount App.\n",
3112                    ),
3113                };
3114                // A user file lives under /workspace, apart from the shipped examples
3115                // (so it survives reloads), and we create the folder on demand so
3116                // the tree never shows an empty workspace.
3117                let existing: std::collections::HashSet<String> = match vfs.list_dir("/workspace").await {
3118                    Ok(entries) => entries.into_iter().map(|e| e.name).collect(),
3119                    Err(_) => std::collections::HashSet::new(),
3120                };
3121                let path = format!("/workspace/{}", fresh_untitled_name(ext, |n| existing.contains(n)));
3122                if vfs.create_dir_all("/workspace").await.is_err() { return; }
3123                if vfs.write(&path, template.as_bytes()).await.is_err() { return; }
3124                // Rebuild the tree so the new file appears, every folder left open
3125                // or closed as the reader had it.
3126                let mut root = FileNode::root();
3127                if load_dir_recursive(&vfs, "/", &mut root).await.is_ok() {
3128                    let root = root.with_expansion_of(&file_tree.peek());
3129                    file_tree.set(root);
3130                }
3131                // Open it in the current mode's editor.
3132                current_file.set(Some(path.clone()));
3133                if fault.peek().is_some() {
3134                    fault.set(None);
3135                }
3136                state.editor(current).set(template.to_string());
3137                sync_studio_url(&path);
3138            });
3139        }
3140    };
3141
3142    rsx! {
3143        PageHead {
3144            title: seo_pages::STUDIO.title,
3145            description: seo_pages::STUDIO.description,
3146            canonical_path: seo_pages::STUDIO.canonical_path,
3147        }
3148        style { "{MOBILE_BASE_STYLES}" }
3149        style { "{MOBILE_TAB_BAR_STYLES}" }
3150        style { "{STUDIO_STYLE}" }
3151        style { "{crate::ui::drag::DRAG_STYLE}" }
3152        if cfg!(not(target_arch = "wasm32")) {
3153            script { dangerous_inner_html: prerender_guard(&opening.path) }
3154        }
3155        JsonLdMultiple { schemas: vec![
3156            organization_schema(),
3157            software_application_schema(),
3158            breadcrumb_schema(&[
3159                BreadcrumbItem { name: "Home", path: "/" },
3160                BreadcrumbItem { name: "Studio", path: "/studio" },
3161            ]),
3162        ] }
3163
3164        div {
3165            class: "studio-container",
3166            ontouchstart: handle_touch_start,
3167            ontouchend: handle_touch_end,
3168
3169            MainNav { active: ActivePage::Studio, subtitle: Some("Your logic workspace") }
3170            Workbench {
3171                state,
3172                host: Host::Page,
3173                store: StoreNote {
3174                    error: vfs_error.read().clone(),
3175                    private_mode: *vfs_is_fallback.read(),
3176                    new_file_waits,
3177                },
3178                on_new_file: Some(EventHandler::new(on_new_file)),
3179                on_choose: Some(EventHandler::new(on_choose)),
3180            }
3181        }
3182    }
3183}