Skip to main content

logicaffeine_web/ui/components/
code_editor.rs

1//! Syntax-highlighted code editor component.
2//!
3//! Provides a textarea with real-time syntax highlighting overlay. Uses a
4//! transparent textarea layered over a highlighted `pre` element for editing.
5//!
6//! # Components
7//!
8//! - [`CodeEditor`] - Editable code editor with syntax highlighting
9//! - [`CodeView`] - Read-only syntax highlighted display
10//!
11//! # Languages
12//!
13//! - **Logos**: Imperative `.logos` files (zones, parallel, etc.)
14//! - **Vernacular**: Math/theorem mode (Definition, Check, Eval)
15//! - **Rust**: Generated Rust output
16//!
17//! # Props (CodeEditor)
18//!
19//! - `value` - Current code content
20//! - `on_change` - Callback when content changes
21//! - `language` - Syntax highlighting mode
22//! - `placeholder` - Optional placeholder text
23//! - `readonly` - Whether editing is disabled
24
25use dioxus::prelude::*;
26use logicaffeine_lsp::document::DocumentState;
27
28#[cfg(target_arch = "wasm32")]
29use super::hover_hint::{hover_markdown, markdown_to_html};
30#[cfg(target_arch = "wasm32")]
31use super::indent::Indentation;
32#[cfg(target_arch = "wasm32")]
33use super::problems::problems_html;
34use super::problems::{problems, rebase, squiggle_class, Problem};
35use super::status_bar::{Caret, EditorStatus, ProblemCount};
36#[cfg(target_arch = "wasm32")]
37use super::vernacular::Snap;
38
39/// Language mode for syntax highlighting.
40#[derive(Clone, Copy, PartialEq, Eq, Default)]
41pub enum Language {
42    #[default]
43    Logos, // Imperative .logos files
44    Vernacular, // Math/theorem mode (Definition, Check, Eval)
45    Rust,       // Generated Rust output
46    Hardware,   // Hardware mode: English specs and Verilog
47    Logic,      // Logic mode: English sentences, theorems and proofs
48}
49
50impl Language {
51    /// The language's name as a status bar shows it; Hardware names Verilog apart from the
52    /// English specs by what `source` is.
53    pub fn name(self, source: &str) -> &'static str {
54        use crate::ui::pages::hardware_report::is_verilog;
55        match self {
56            Language::Logos => "LOGOS",
57            Language::Logic => "Logic",
58            Language::Vernacular => "Vernacular",
59            Language::Rust => "Rust",
60            Language::Hardware if is_verilog(source) => "Verilog",
61            Language::Hardware => "Hardware",
62        }
63    }
64
65    /// The class the editor's root carries for this language (`lang-vernacular`, …).
66    pub fn css_class(self) -> &'static str {
67        match self {
68            Language::Logos => "logos",
69            Language::Logic => "logic",
70            Language::Vernacular => "vernacular",
71            Language::Rust => "rust",
72            Language::Hardware => "hardware",
73        }
74    }
75}
76
77/// Token type for syntax highlighting.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub(crate) enum TokenKind {
80    Keyword,
81    Type,
82    String,
83    Number,
84    Comment,
85    Operator,
86    Punctuation,
87    Identifier,
88    Builtin,
89}
90
91/// A highlighted token with its text and kind.
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub(crate) struct Token {
94    pub(crate) text: String,
95    pub(crate) kind: TokenKind,
96}
97
98/// The editor's stylesheet: inlined ahead of each editor, unless its host places it once ahead of
99/// its own markup (see [`CodeEditor`]'s `stylesheet`).
100pub const CODE_EDITOR_STYLE: &str = r#"
101.code-editor {
102    display: flex;
103    flex-direction: column;
104    height: 100%;
105    background: var(--studio-surface, #0f1419);
106    font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
107}
108
109/* Math sets its text in Logos Math Mono, whose ligatures draw the kernel's ASCII spellings as the
110   symbols they stand for (forall as ∀, fun as λ, -> as →). Both layers shape the same glyphs, so
111   the caret, selection and clicks stay on the text; the file stays ASCII. */
112@font-face {
113    font-family: 'Logos Math Mono';
114    src: url('/assets/fonts/LogosMathMono.woff2') format('woff2');
115    font-display: swap;
116}
117.code-editor.lang-vernacular .code-editor-textarea,
118.code-editor.lang-vernacular .code-editor-highlight {
119    font-family: 'Logos Math Mono', 'SF Mono', 'Fira Code', 'Consolas', monospace;
120    font-variant-ligatures: contextual;
121}
122
123.code-editor-input {
124    position: relative;
125    flex: 1;
126    min-height: 200px;
127}
128
129.code-editor-textarea {
130    position: absolute;
131    top: 0;
132    left: 0;
133    width: 100%;
134    height: 100%;
135    /* The host's inset, and room to scroll the last line up the editor — which the Studio
136       declines, ending every column's scroll at its last line. */
137    padding: var(--studio-inset, 16px);
138    padding-bottom: var(--editor-overscroll, 50%);
139    margin: 0;
140    font-size: 14px;
141    font-family: inherit;
142    line-height: 1.6;
143    tab-size: 4;
144    background: transparent;
145    color: transparent;
146    caret-color: #667eea;
147    border: none;
148    outline: none;
149    resize: none;
150    white-space: pre-wrap;
151    word-wrap: break-word;
152    overflow-wrap: break-word;
153    overflow: auto;
154    z-index: 2;
155    box-sizing: border-box;
156}
157
158.code-editor-highlight {
159    position: absolute;
160    top: 0;
161    left: 0;
162    width: 100%;
163    height: 100%;
164    /* The host's inset, and room to scroll the last line up the editor — which the Studio
165       declines, ending every column's scroll at its last line. */
166    padding: var(--studio-inset, 16px);
167    padding-bottom: var(--editor-overscroll, 50%);
168    margin: 0;
169    font-size: 14px;
170    font-family: inherit;
171    line-height: 1.6;
172    tab-size: 4;
173    color: #e8eaed;
174    white-space: pre-wrap;
175    word-wrap: break-word;
176    overflow-wrap: break-word;
177    overflow: auto;
178    pointer-events: none;
179    z-index: 1;
180    box-sizing: border-box;
181    /* Hide scrollbar but keep scroll functionality for sync */
182    scrollbar-width: none;
183    -ms-overflow-style: none;
184}
185
186.code-editor-highlight::-webkit-scrollbar {
187    display: none;
188}
189
190/* Syntax highlighting colors - no font-weight/style changes to keep heights identical */
191.tok-keyword { color: #c678dd; }
192.tok-type { color: #e5c07b; }
193.tok-string { color: #98c379; }
194.tok-number { color: #d19a66; }
195.tok-comment { color: var(--studio-text-secondary, #9ca3af); }
196.tok-operator { color: #56b6c2; }
197.tok-punctuation { color: #abb2bf; }
198.tok-identifier { color: #e8eaed; }
199.tok-builtin { color: #61afef; }
200
201/* A hover hint in VS Code's manner: a quiet panel over the code, never in the pointer's way.
202   Its parts (a problem and its source, code, prose, lists, rules) sit one even gap apart, and
203   nothing inside adds space of its own. */
204.hover-hint {
205    position: fixed;
206    z-index: 1000;
207    max-width: 520px;
208    max-height: 40vh;
209    overflow: auto;
210    display: flex;
211    flex-direction: column;
212    gap: 4px;
213    padding: 4px 8px;
214    background: #252526;
215    border: 1px solid #454545;
216    border-radius: 4px;
217    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.45);
218    color: #cccccc;
219    font: 13px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
220}
221/* Problems, VS Code's way: a wavy underline in the severity's colour; unused code faded. */
222.sq-error, .sq-warning, .sq-info {
223    text-decoration-line: underline;
224    text-decoration-style: wavy;
225    text-decoration-skip-ink: none;
226    text-underline-offset: 3px;
227}
228.sq-error { text-decoration-color: #f14c4c; }
229.sq-warning { text-decoration-color: #cca700; }
230.sq-info { text-decoration-color: #3794ff; }
231.sq-hint {
232    text-decoration: underline dotted rgba(238, 238, 238, 0.55);
233    text-underline-offset: 3px;
234}
235.sq-unnecessary { opacity: 0.6; }
236
237.hover-hint .hint-problem { display: flex; flex-direction: column; gap: 4px; }
238.hover-hint > *, .hover-hint .hint-problem > * { flex: none; margin: 0; }
239.hover-hint .hint-source { color: #9ca3af; font-size: 12px; }
240.hover-hint a { color: #3794ff; text-decoration: none; }
241.hover-hint a:hover { text-decoration: underline; }
242.hover-hint hr { border: none; border-top: 1px solid #454545; margin: 0 -8px; }
243.hover-hint strong { color: #e8eaed; }
244.hover-hint code { font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; font-size: 12px; background: rgba(255, 255, 255, 0.06); padding: 0 3px; border-radius: 3px; }
245.hover-hint pre { padding: 4px 8px; background: #1e1e1e; border-radius: 3px; overflow-x: auto; }
246.hover-hint pre code { background: none; padding: 0; }
247.hover-hint ul { padding-left: 18px; }
248
249/* Mobile optimizations */
250@media (max-width: 768px) {
251    .code-editor-textarea,
252    .code-editor-highlight {
253        font-size: 16px; /* Prevent iOS zoom */
254        padding: var(--studio-inset, 12px);
255    }
256}
257"#;
258
259/// The byte offset of every word inside a comparison written in English (`is less than`,
260/// `greater than or equal to`, `at least`, `is equal to`, `equals`), read by the language's own
261/// phrase reader (the one its hover teaches from), so the editor colours the words as operators.
262fn comparison_word_starts(source: &str, lexed: &[logicaffeine_language::token::Token]) -> std::collections::HashSet<usize> {
263    let mut starts = std::collections::HashSet::new();
264    for at in 0..lexed.len() {
265        if let Some((_, span)) = logicaffeine_language::teach::doc_for_phrase(source, lexed, at) {
266            let mut in_word = false;
267            for (i, c) in source[span.start..span.end].char_indices() {
268                let word_char = c.is_alphanumeric() || c == '_';
269                if word_char && !in_word {
270                    starts.insert(span.start + i);
271                }
272                in_word = word_char;
273            }
274        }
275    }
276    starts
277}
278
279/// The byte ranges of a Code file that are prose, not code: the literate doc before the first
280/// `## ` header (what `teach::module_doc` reads) and the body of every `## Note` block. The editor
281/// colours them as comments and the language server's hover leaves them alone (the user,
282/// 2026-11-01: comments in Web mode showed hints). A file with no header at all is all code.
283fn prose_spans(source: &str) -> Vec<std::ops::Range<usize>> {
284    let mut spans = Vec::new();
285    let headers: Vec<usize> = source
286        .match_indices("## ")
287        .map(|(i, _)| i)
288        .filter(|&i| i == 0 || source.as_bytes()[i - 1] == b'\n')
289        .collect();
290    let Some(&first) = headers.first() else { return spans };
291    if first > 0 {
292        spans.push(0..first);
293    }
294    for (n, &at) in headers.iter().enumerate() {
295        let line_end = source[at..].find('\n').map_or(source.len(), |i| at + i);
296        let title = source[at + 3..line_end].trim();
297        if title.eq_ignore_ascii_case("Note") || title.to_ascii_lowercase().starts_with("note:") {
298            let body_end = headers.get(n + 1).copied().unwrap_or(source.len());
299            if line_end < body_end {
300                spans.push(line_end + 1..body_end);
301            }
302        }
303    }
304    spans
305}
306
307/// Whether the byte at `offset` sits in text the editor colours as a comment (a `#` or `--` note,
308/// or Code prose): nothing there is a word the language server should explain.
309pub(crate) fn comment_at(source: &str, language: Language, offset: usize) -> bool {
310    let mut at = 0;
311    for token in tokenize(source, language) {
312        let end = at + token.text.len();
313        if (at..end).contains(&offset) {
314            return token.kind == TokenKind::Comment;
315        }
316        at = end;
317    }
318    false
319}
320
321/// A LOGOS token the editor colours as a keyword: a statement word of the language, or a word
322/// it teaches as a keyword (`If` classes as a connective but is taught as a statement).
323fn is_logos_keyword(kind: &logicaffeine_language::token::TokenType) -> bool {
324    logicaffeine_language::token_class::is_imperative_keyword(kind)
325        || logicaffeine_language::teach::doc_for(kind).is_some()
326}
327
328/// A Hardware spec's field (`pigeons`, `registers`), named as its parser reads it.
329fn is_spec_field(word: &str) -> bool {
330    use crate::ui::pages::hardware_spec::{is_field, FIELDS};
331    FIELDS.iter().any(|field| is_field(word, field))
332}
333
334/// `source` cut into the tokens the editor colours; Verilog and Math through their own lexers.
335fn tokenize(source: &str, language: Language) -> Vec<Token> {
336    if language == Language::Hardware && crate::ui::pages::hardware_report::is_verilog(source) {
337        return super::verilog::tokens(source);
338    }
339    if language == Language::Vernacular {
340        return super::vernacular::tokens(source);
341    }
342    let mut tokens = Vec::new();
343    let chars: Vec<char> = source.chars().collect();
344    let len = chars.len();
345    let mut i = 0;
346
347    let keywords = match language {
348        Language::Logos => &[
349            "let",
350            "set",
351            "if",
352            "then",
353            "else",
354            "while",
355            "repeat",
356            "for",
357            "in",
358            "return",
359            "match",
360            "with",
361            "end",
362            "function",
363            "struct",
364            "enum",
365            "show",
366            "read",
367            "write",
368            "push",
369            "pop",
370            "add",
371            "remove",
372            "and",
373            "or",
374            "not",
375            "true",
376            "false",
377            "nothing",
378            "zone",
379            "concurrent",
380            "parallel",
381            "launch",
382            "send",
383            "receive",
384            "select",
385            "mount",
386            "sync",
387            "merge",
388            "increase",
389            "decrease",
390        ][..],
391        Language::Vernacular => &[
392            "Definition",
393            "Check",
394            "Eval",
395            "Inductive",
396            "Theorem",
397            "Lemma",
398            "Proof",
399            "Qed",
400            "Axiom",
401            "Hypothesis",
402            "Variable",
403            "Parameter",
404            "fun",
405            "forall",
406            "exists",
407            "match",
408            "with",
409            "end",
410            "let",
411            "in",
412            "Prop",
413            "Type",
414            "Set",
415            "Nat",
416            "Bool",
417            "True",
418            "False",
419            "Not",
420            "And",
421            "Or",
422            "Eq",
423            "Ex",
424            "All",
425        ][..],
426        // English specs ("Always, if request is high, then …", signal plans) and Verilog.
427        // Theorem structure. Tactics join them on a `Proof:` line (see `in_proof` below).
428        Language::Logic => &[
429            "Theorem",
430            "Lemma",
431            "Definition",
432            "Axiom",
433            "Given",
434            "Prove",
435            "Proof",
436            "Auto",
437        ][..],
438        Language::Hardware => &[
439            "Always",
440            "always",
441            "If",
442            "if",
443            "then",
444            "else",
445            "is",
446            "are",
447            "Not",
448            "not",
449            "both",
450            "and",
451            "or",
452            "only",
453            "Never",
454            "never",
455            "Eventually",
456            "eventually",
457            "until",
458            "within",
459            "next",
460            "cycle",
461            "cycles",
462            "high",
463            "low",
464            "Movements",
465            "conflicts",
466            "with",
467            "module",
468            "endmodule",
469            "input",
470            "output",
471            "inout",
472            "reg",
473            "wire",
474            "logic",
475            "assign",
476            "posedge",
477            "negedge",
478            "begin",
479            "end",
480            "initial",
481            "case",
482            "endcase",
483            "assert",
484            "property",
485            "parameter",
486            "localparam",
487        ][..],
488        Language::Rust => &[
489            "fn", "let", "mut", "const", "static", "if", "else", "match", "loop", "while", "for",
490            "in", "return", "break", "continue", "struct", "enum", "impl", "trait", "type", "pub",
491            "mod", "use", "crate", "self", "super", "async", "await", "move", "ref", "where",
492            "true", "false",
493        ][..],
494    };
495
496    let types = match language {
497        Language::Logos => &[
498            "Int",
499            "Text",
500            "Bool",
501            "Real",
502            "Char",
503            "Byte",
504            "Nothing",
505            "Seq",
506            "Map",
507            "Set",
508            "Option",
509            "Result",
510            "Tuple",
511            "Persistent",
512            "Distributed",
513        ][..],
514        Language::Vernacular => &[
515            "Prop",
516            "Type",
517            "Set",
518            "Nat",
519            "Bool",
520            "Int",
521            "List",
522            "Option",
523            "Syntax",
524            "Derivation",
525            "Term",
526        ][..],
527        // Modal auxiliaries: necessity and possibility.
528        Language::Logic => &[
529            "must", "Must", "can", "Can", "cannot", "Cannot", "might", "Might", "may", "May",
530            "should", "Should", "would", "Would", "could", "Could",
531        ][..],
532        Language::Hardware => &[][..],
533        Language::Rust => &[
534            "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
535            "f32", "f64", "bool", "char", "str", "String", "Vec", "HashMap", "Option", "Result",
536            "Box", "Rc", "Arc",
537        ][..],
538    };
539
540    let builtins = match language {
541        Language::Logos => &[
542            "show", "length", "first", "last", "rest", "append", "contains", "keys", "values",
543            "range",
544        ][..],
545        Language::Vernacular => &[
546            "Zero",
547            "Succ",
548            "Nil",
549            "Cons",
550            "Some",
551            "None",
552            "refl",
553            "eq_ind",
554            "nat_ind",
555            "syn_diag",
556            "syn_quote",
557            "syn_size",
558            "concludes",
559            "Provable",
560            "Consistent",
561        ][..],
562        // Quantifiers.
563        Language::Logic => &[
564            "Every", "every", "All", "all", "Some", "some", "No", "no", "Each", "each", "Exactly",
565            "exactly", "Few", "few", "Most", "most", "Many", "many", "Any", "any",
566        ][..],
567        Language::Hardware => &[][..],
568        Language::Rust => &[
569            "println", "print", "format", "vec", "panic", "assert", "Some", "None", "Ok", "Err",
570        ][..],
571    };
572
573    // Logic's connectives read as operators.
574    let connectives: &[&str] = match language {
575        Language::Logic => &[
576            "If", "if", "then", "Then", "and", "or", "not", "iff", "Neither", "neither", "nor",
577            "unless", "Unless", "only",
578        ],
579        _ => &[],
580    };
581    // On a Logic `Proof:` line, the tactic engine's vocabulary is keywords too.
582    let mut in_proof = false;
583    // LOGOS words take the lexer's own reading: a word it reads as a statement word
584    // (`Let`, `Otherwise`, `Give`, …) or a keyword the language teaches (`If`) colours as one at
585    // whatever case it is written, and `Set of Int` — which the lexer reads as a type — does not.
586    let (lexer_keywords, lexer_operators): (std::collections::HashSet<usize>, std::collections::HashSet<usize>) =
587        if language == Language::Logos {
588            let mut interner = logicaffeine_base::Interner::new();
589            let lexed = logicaffeine_language::Lexer::new(source, &mut interner).tokenize();
590            let keywords = lexed.iter().filter(|t| is_logos_keyword(&t.kind)).map(|t| t.span.start).collect();
591            (keywords, comparison_word_starts(source, &lexed))
592        } else {
593            Default::default()
594        };
595    // The byte offset where each character starts: the lexer speaks in bytes.
596    let byte_at: Vec<usize> = chars
597        .iter()
598        .scan(0usize, |at, c| {
599            let here = *at;
600            *at += c.len_utf8();
601            Some(here)
602        })
603        .collect();
604    let prose: Vec<std::ops::Range<usize>> = if language == Language::Logos { prose_spans(source) } else { Vec::new() };
605
606    while i < len {
607        let c = chars[i];
608
609        // Skip whitespace (preserve it)
610        if c.is_whitespace() {
611            let start = i;
612            while i < len && chars[i].is_whitespace() {
613                i += 1;
614            }
615            if chars[start..i].contains(&'\n') {
616                in_proof = false;
617            }
618            tokens.push(Token {
619                text: chars[start..i].iter().collect(),
620                kind: TokenKind::Identifier, // Whitespace uses default color
621            });
622            continue;
623        }
624
625        // Code prose (the literate doc before the first header, a `## Note` body) reads as a
626        // comment, a line at a time.
627        if language == Language::Logos && c != '\n' && prose.iter().any(|span| span.contains(&byte_at[i])) {
628            let start = i;
629            let span_end = prose.iter().find(|span| span.contains(&byte_at[i])).map(|span| span.end).unwrap_or(usize::MAX);
630            while i < len && chars[i] != '\n' && byte_at[i] < span_end {
631                i += 1;
632            }
633            tokens.push(Token {
634                text: chars[start..i].iter().collect(),
635                kind: TokenKind::Comment,
636            });
637            continue;
638        }
639
640        // LOGOS (Code and Logic alike): one `#` opens a comment to the end of the line, wherever
641        // it stands; `##` opens a block header (`## Main`, `## Theorem: …`), whose words keep
642        // their highlighting — exactly as the lexer reads them.
643        if matches!(language, Language::Logos | Language::Logic) && c == '#' {
644            let run = chars[i..].iter().take_while(|&&ch| ch == '#').count();
645            let start = i;
646            if run == 1 {
647                while i < len && chars[i] != '\n' {
648                    i += 1;
649                }
650                tokens.push(Token {
651                    text: chars[start..i].iter().collect(),
652                    kind: TokenKind::Comment,
653                });
654            } else {
655                i += run;
656                tokens.push(Token {
657                    text: chars[start..i].iter().collect(),
658                    kind: TokenKind::Punctuation,
659                });
660            }
661            continue;
662        }
663
664        // A Hardware spec comments with a `#` run and a space (`# note`, `## Title`), as its
665        // parsers read it; Verilog's `#5` and `#(10)` delays stay code.
666        if language == Language::Hardware && c == '#' {
667            let run = chars[i..].iter().take_while(|&&ch| ch == '#').count();
668            if crate::ui::pages::hardware_spec::opens_comment(chars.get(i + run).copied()) {
669                let start = i;
670                while i < len && chars[i] != '\n' {
671                    i += 1;
672                }
673                tokens.push(Token {
674                    text: chars[start..i].iter().collect(),
675                    kind: TokenKind::Comment,
676                });
677                continue;
678            }
679        }
680
681        // Comments
682        let comment_start = match language {
683            Language::Logos | Language::Vernacular => "--",
684            Language::Rust | Language::Hardware => "//",
685            Language::Logic => "",
686        };
687        if !comment_start.is_empty() && i + comment_start.len() <= len {
688            let slice: String = chars[i..i + comment_start.len()].iter().collect();
689            if slice == comment_start {
690                let start = i;
691                while i < len && chars[i] != '\n' {
692                    i += 1;
693                }
694                tokens.push(Token {
695                    text: chars[start..i].iter().collect(),
696                    kind: TokenKind::Comment,
697                });
698                continue;
699            }
700        }
701
702        // Strings
703        if c == '"' {
704            let start = i;
705            i += 1;
706            while i < len && chars[i] != '"' {
707                if chars[i] == '\\' && i + 1 < len {
708                    i += 2;
709                } else {
710                    i += 1;
711                }
712            }
713            if i < len {
714                i += 1; // closing quote
715            }
716            tokens.push(Token {
717                text: chars[start..i].iter().collect(),
718                kind: TokenKind::String,
719            });
720            continue;
721        }
722
723        // Numbers
724        if c.is_ascii_digit() {
725            let start = i;
726            while i < len && (chars[i].is_ascii_digit() || chars[i] == '.' || chars[i] == '_') {
727                i += 1;
728            }
729            tokens.push(Token {
730                text: chars[start..i].iter().collect(),
731                kind: TokenKind::Number,
732            });
733            continue;
734        }
735
736        // Identifiers and keywords
737        if c.is_alphabetic() || c == '_' {
738            let start = i;
739            while i < len && (chars[i].is_alphanumeric() || chars[i] == '_') {
740                i += 1;
741            }
742            let word: String = chars[start..i].iter().collect();
743            let kind = if lexer_operators.contains(&byte_at[start]) {
744                // `is less than`, `at least`, `is equal to`: the comparison the words spell, coloured
745                // as `<`, `>=` and `==` are.
746                TokenKind::Operator
747            } else if keywords.contains(&word.as_str())
748                || lexer_keywords.contains(&byte_at[start])
749            {
750                TokenKind::Keyword
751            } else if language == Language::Hardware
752                && chars.get(i) == Some(&':')
753                && is_spec_field(&word)
754            {
755                TokenKind::Keyword
756            } else if in_proof && logicaffeine_proof::tactic_script::canonical(&word).is_some() {
757                TokenKind::Keyword
758            } else if types.contains(&word.as_str()) {
759                TokenKind::Type
760            } else if builtins.contains(&word.as_str()) {
761                TokenKind::Builtin
762            } else if connectives.contains(&word.as_str()) {
763                TokenKind::Operator
764            } else {
765                TokenKind::Identifier
766            };
767            if language == Language::Logic && word == "Proof" {
768                in_proof = true;
769            }
770            tokens.push(Token { text: word, kind });
771            continue;
772        }
773
774        // Operators
775        let operators = [
776            "->", "=>", ":=", "<=", ">=", "==", "!=", "&&", "||", "+", "-", "*", "/", "%", "=",
777            "<", ">", "!", "&", "|", "^",
778        ];
779        let mut matched = false;
780        for op in operators {
781            if i + op.len() <= len {
782                let slice: String = chars[i..i + op.len()].iter().collect();
783                if slice == op {
784                    tokens.push(Token {
785                        text: slice,
786                        kind: TokenKind::Operator,
787                    });
788                    i += op.len();
789                    matched = true;
790                    break;
791                }
792            }
793        }
794        if matched {
795            continue;
796        }
797
798        // Punctuation
799        if "(){}[].,;:".contains(c) {
800            tokens.push(Token {
801                text: c.to_string(),
802                kind: TokenKind::Punctuation,
803            });
804            i += 1;
805            continue;
806        }
807
808        // Default: single character
809        tokens.push(Token {
810            text: c.to_string(),
811            kind: TokenKind::Identifier,
812        });
813        i += 1;
814    }
815
816    if language == Language::Logic {
817        join_counting_quantifiers(&mut tokens);
818    }
819    tokens
820}
821
822/// Logic's counting quantifiers read as one phrase, the way the lexer reads them as one
823/// quantifier: "at least three", "at most 2", "exactly one", "more than two", "fewer than 3".
824fn join_counting_quantifiers(tokens: &mut [Token]) {
825    let words: Vec<usize> = tokens
826        .iter()
827        .enumerate()
828        .filter(|(_, t)| !t.text.trim().is_empty())
829        .map(|(i, _)| i)
830        .collect();
831    let text = |k: usize| tokens[words[k]].text.to_lowercase();
832    let mut phrases = Vec::new();
833    for w in 0..words.len() {
834        let next = |k: usize| (w + k < words.len()).then(|| text(w + k));
835        let count_at = match text(w).as_str() {
836            "at" if matches!(next(1).as_deref(), Some("least" | "most")) => w + 2,
837            "more" | "fewer" | "less" if next(1).as_deref() == Some("than") => w + 2,
838            "exactly" => w + 1,
839            _ => continue,
840        };
841        if count_at < words.len() && is_count(&text(count_at)) {
842            phrases.push(w..=count_at);
843        }
844    }
845    for phrase in phrases {
846        for k in phrase {
847            tokens[words[k]].kind = TokenKind::Builtin;
848        }
849    }
850}
851
852/// A count: digits, or a number word the lexicon reads as one.
853fn is_count(word: &str) -> bool {
854    (!word.is_empty() && word.chars().all(|c| c.is_ascii_digit()))
855        || logicaffeine_language::lexicon::word_to_number(word).is_some()
856}
857
858/// Get CSS class for a token kind.
859fn token_class(kind: TokenKind) -> &'static str {
860    match kind {
861        TokenKind::Keyword => "tok-keyword",
862        TokenKind::Type => "tok-type",
863        TokenKind::String => "tok-string",
864        TokenKind::Number => "tok-number",
865        TokenKind::Comment => "tok-comment",
866        TokenKind::Operator => "tok-operator",
867        TokenKind::Punctuation => "tok-punctuation",
868        TokenKind::Identifier => "tok-identifier",
869        TokenKind::Builtin => "tok-builtin",
870    }
871}
872
873/// Syntax-highlighted code editor component.
874#[component]
875pub fn CodeEditor(
876    value: String,
877    on_change: EventHandler<String>,
878    language: Language,
879    #[props(default = "Enter code...".to_string())] placeholder: String,
880    #[props(default = false)] readonly: bool,
881    /// Run the language's service over the source — the LOGOS language server, or the Hardware
882    /// specs' own (`hardware_spec`): a VS Code-style hover for the word under a resting pointer,
883    /// and squiggles under the problems it finds.
884    #[props(default = false)]
885    language_server: bool,
886    /// Inline [`CODE_EDITOR_STYLE`] ahead of the editor. A host that sets editors into its own
887    /// markup places the stylesheet once, ahead of that markup, and turns this off.
888    #[props(default = true)]
889    stylesheet: bool,
890    /// Where to tell a status bar where the caret is, what is selected, and how many problems
891    /// the language service found.
892    #[props(default)]
893    status: Option<Signal<EditorStatus>>,
894) -> Element {
895    // Each token with its byte offset in the source, so a hover can ask about exactly it.
896    let mut at = 0usize;
897    let tokens: Vec<(Token, usize)> = tokenize(&value, language)
898        .into_iter()
899        .map(|t| {
900            let o = at;
901            at += t.text.len();
902            (t, o)
903        })
904        .collect();
905    let mut hint = use_signal(|| None::<HoverHint>);
906    // Bumped to void a hover waiting to appear, and a hide waiting to happen.
907    let hint_gen = use_signal(|| 0u64);
908    let hide_gen = use_signal(|| 0u64);
909    let mut hide_pending = use_signal(|| false);
910    let mut hint_hovered = use_signal(|| false);
911    let analysis =
912        use_hook(|| std::rc::Rc::new(std::cell::RefCell::new(None::<std::rc::Rc<DocumentState>>)));
913    let source = value.clone();
914    #[cfg(target_arch = "wasm32")]
915    let source_for_tap = value.clone();
916
917    // The problems the language server found, and the text it found them in. Re-analysed once
918    // typing pauses; until then the last problems move with the text they sit under.
919    let mut found = use_signal(|| (String::new(), Vec::<Problem>::new()));
920    let analysis_gen = use_signal(|| 0u64);
921    {
922        let analysis = analysis.clone();
923        let value = value.clone();
924        use_effect(use_reactive!(|(value, language_server, language)| {
925            let generation = bump(analysis_gen);
926            if !language_server {
927                if !found.peek().1.is_empty() {
928                    found.set((String::new(), Vec::new()));
929                }
930                return;
931            }
932            let analysis = analysis.clone();
933            #[cfg(target_arch = "wasm32")]
934            spawn(async move {
935                gloo_timers::future::TimeoutFuture::new(ANALYSIS_DELAY_MS).await;
936                if *analysis_gen.peek() == generation {
937                    let now = service_problems(language, &analysis, &value);
938                    found.set((value, now));
939                }
940            });
941            #[cfg(not(target_arch = "wasm32"))]
942            {
943                let _ = generation;
944                let now = service_problems(language, &analysis, &value);
945                found.set((value, now));
946            }
947        }));
948    }
949    let shown: Vec<Problem> = {
950        let found = found.read();
951        if found.0 == value {
952            found.1.clone()
953        } else {
954            rebase(&found.1, &found.0, &value)
955        }
956    };
957
958    // The status bar: the problem counts as the squiggles show them, and the caret, read from
959    // the textarea whenever it may have moved.
960    let counted = ProblemCount::of(&shown);
961    use_effect(use_reactive!(|counted| {
962        if let Some(mut status) = status {
963            if status.peek().problems != counted {
964                status.with_mut(|s| s.problems = counted);
965            }
966        }
967    }));
968    let textarea_id = use_hook(|| CopyValue::new(next_textarea_id()));
969    let dom_id = textarea_id.read().clone();
970    let report_caret = move || {
971        #[cfg(target_arch = "wasm32")]
972        if let (Some(mut status), Some(caret)) = (status, caret_in(&textarea_id.read())) {
973            if status.peek().caret != caret {
974                status.with_mut(|s| s.caret = caret);
975            }
976        }
977        #[cfg(not(target_arch = "wasm32"))]
978        let _ = (status, textarea_id);
979    };
980    // The last text this editor's own typing produced. Any other new value was loaded from
981    // outside — a file opened, a template chosen — and opens with the caret at its start, the
982    // way VS Code opens a file.
983    let typed = use_hook(|| CopyValue::new(None::<String>));
984    // Escape hands Tab back to the page, so the keyboard can leave the editor; any other key
985    // takes it back.
986    let tab_released = use_hook(|| CopyValue::new(false));
987    use_effect(use_reactive!(|value| {
988        if typed.peek().as_deref() != Some(value.as_str()) {
989            #[cfg(target_arch = "wasm32")]
990            caret_to_start(&textarea_id.read());
991            if let Some(mut status) = status {
992                if status.peek().caret != Caret::default() {
993                    status.with_mut(|s| s.caret = Caret::default());
994                }
995            }
996        }
997    }));
998    // The on-screen keyboard opening or closing moves the part of the editor the reader can see:
999    // the caret's line stays in it.
1000    #[cfg(target_arch = "wasm32")]
1001    {
1002        use wasm_bindgen::prelude::*;
1003        use wasm_bindgen::JsCast;
1004        let on_resize = use_hook(move || {
1005            let on_resize = Closure::<dyn FnMut()>::new(move || keep_caret_in_view(&textarea_id.read()));
1006            if let Some(visual) = web_sys::window().and_then(|w| w.visual_viewport()) {
1007                let _ = visual.add_event_listener_with_callback("resize", on_resize.as_ref().unchecked_ref());
1008            }
1009            std::rc::Rc::new(on_resize)
1010        });
1011        use_drop(move || {
1012            if let Some(visual) = web_sys::window().and_then(|w| w.visual_viewport()) {
1013                let _ = visual.remove_event_listener_with_callback("resize", (*on_resize).as_ref().unchecked_ref());
1014            }
1015        });
1016    }
1017    let mut keep_hint = move || {
1018        bump(hide_gen);
1019        hide_pending.set(false);
1020    };
1021    // Hide now: typing, scrolling, or the pointer leaving the hint itself.
1022    let mut hide_hint = move || {
1023        if hint.peek().is_some() {
1024            hint.set(None);
1025        }
1026        hint_hovered.set(false);
1027        bump(hint_gen);
1028        keep_hint();
1029    };
1030    // Hide once the grace period runs out, unless the pointer comes back to the word or reaches
1031    // the hint first — the way VS Code lets you move into a hover to click its links.
1032    let mut release_hint = move || {
1033        bump(hint_gen);
1034        if hint.peek().is_none() || *hide_pending.peek() {
1035            return;
1036        }
1037        hide_pending.set(true);
1038        let generation = bump(hide_gen);
1039        #[cfg(target_arch = "wasm32")]
1040        spawn(async move {
1041            gloo_timers::future::TimeoutFuture::new(HIDE_GRACE_MS).await;
1042            if *hide_gen.peek() == generation {
1043                hide_pending.set(false);
1044                if !*hint_hovered.peek() {
1045                    hint.set(None);
1046                }
1047            }
1048        });
1049        #[cfg(not(target_arch = "wasm32"))]
1050        let _ = generation;
1051    };
1052
1053    rsx! {
1054        if stylesheet {
1055            style { "{CODE_EDITOR_STYLE}" }
1056        }
1057
1058        div { class: "code-editor lang-{language.css_class()}",
1059            div { class: "code-editor-input",
1060                // Highlighted overlay
1061                div { class: "code-editor-highlight",
1062                    for run in tokens.chunks(TOKEN_RUN) {
1063                        span {
1064                            for (token, offset) in run.iter() {
1065                                if token.text.chars().all(|c| c.is_whitespace()) {
1066                                    // Output whitespace as raw text to match textarea rendering
1067                                    "{token.text}"
1068                                } else {
1069                                    span {
1070                                        class: "{token_class(token.kind)} {squiggle_class(&shown, *offset, offset + token.text.len())}",
1071                                        "data-o": "{offset}",
1072                                        "{token.text}"
1073                                    }
1074                                }
1075                            }
1076                        }
1077                    }
1078                }
1079
1080                // Actual textarea for input
1081                textarea {
1082                    class: "code-editor-textarea",
1083                    placeholder: "{placeholder}",
1084                    value: "{value}",
1085                    id: "{dom_id}",
1086                    readonly: readonly,
1087                    spellcheck: "false",
1088                    autocomplete: "off",
1089                    autocapitalize: "off",
1090                    onmousemove: move |evt| {
1091                        if !language_server {
1092                            return;
1093                        }
1094                        #[cfg(target_arch = "wasm32")]
1095                        {
1096                            let point = evt.data().client_coordinates();
1097                            let Some((offset, rect)) = token_under(point.x, point.y) else {
1098                                release_hint();
1099                                return;
1100                            };
1101                            if hint.peek().as_ref().is_some_and(|h| h.offset == offset) {
1102                                keep_hint();
1103                                return;
1104                            }
1105                            release_hint();
1106                            let generation = *hint_gen.peek();
1107                            let source = source.clone();
1108                            let analysis = analysis.clone();
1109                            spawn(async move {
1110                                gloo_timers::future::TimeoutFuture::new(HOVER_DELAY_MS).await;
1111                                if *hint_gen.peek() != generation {
1112                                    return;
1113                                }
1114                                // VS Code's order: the problems under the word, then its lesson.
1115                                let here = {
1116                                    let found = found.peek();
1117                                    if found.0 == source { found.1.clone() } else { rebase(&found.1, &found.0, &source) }
1118                                };
1119                                let problem = problems_html(&here, offset);
1120                                let lesson = service_hover(language, &analysis, &source, offset).map(|m| markdown_to_html(&m));
1121                                let html = match (problem, lesson) {
1122                                    (Some(p), Some(l)) => format!("{p}<hr>{l}"),
1123                                    (Some(only), None) | (None, Some(only)) => only,
1124                                    (None, None) => return,
1125                                };
1126                                if *hint_gen.peek() == generation {
1127                                    keep_hint();
1128                                    hint.set(Some(HoverHint { offset, html, style: hint_placement(&rect) }));
1129                                }
1130                            });
1131                        }
1132                        #[cfg(not(target_arch = "wasm32"))]
1133                        let _ = (evt, &source, &analysis);
1134                    },
1135                    onmouseleave: move |_| release_hint(),
1136                    onkeydown: move |evt: KeyboardEvent| {
1137                        hide_hint();
1138                        #[cfg(target_arch = "wasm32")]
1139                        {
1140                            let mut tab_released = tab_released;
1141                            let released = *tab_released.peek();
1142                            tab_released.set(evt.key() == Key::Escape);
1143                            let mods = evt.modifiers();
1144                            let plain = !mods.ctrl() && !mods.meta() && !mods.alt();
1145                            let key = match evt.key() {
1146                                Key::Tab if plain && !released => Some(if mods.shift() { EditKey::Outdent } else { EditKey::Indent }),
1147                                Key::Enter if plain && !mods.shift() && !evt.is_composing() => Some(EditKey::Enter),
1148                                _ => None,
1149                            };
1150                            if let Some(key) = key.filter(|_| !readonly) {
1151                                if edit_on_key(&textarea_id.read(), language, key) {
1152                                    evt.prevent_default();
1153                                }
1154                            }
1155                            // The key moves the caret after this handler; read it once it has — in
1156                            // Math, first stepping it over a symbol whose spelling it landed in.
1157                            let snap_to = match evt.key() {
1158                                _ if language != Language::Vernacular => None,
1159                                Key::ArrowLeft => Some(Snap::Start),
1160                                Key::ArrowRight => Some(Snap::End),
1161                                Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End | Key::PageUp | Key::PageDown => Some(Snap::Nearest),
1162                                _ => None,
1163                            };
1164                            spawn(async move {
1165                                gloo_timers::future::TimeoutFuture::new(0).await;
1166                                if let Some(toward) = snap_to {
1167                                    snap_caret(&textarea_id.read(), toward);
1168                                }
1169                                report_caret();
1170                            });
1171                        }
1172                        #[cfg(not(target_arch = "wasm32"))]
1173                        let _ = (evt, tab_released);
1174                    },
1175                    onkeyup: move |_| report_caret(),
1176                    onmouseup: move |_| {
1177                        #[cfg(target_arch = "wasm32")]
1178                        if language == Language::Vernacular {
1179                            snap_caret(&textarea_id.read(), Snap::Nearest);
1180                        }
1181                        report_caret();
1182                    },
1183                    onselect: move |_| report_caret(),
1184                    onfocus: move |_| {
1185                        report_caret();
1186                        #[cfg(target_arch = "wasm32")]
1187                        keep_caret_in_view(&textarea_id.read());
1188                    },
1189                    // A finger cannot rest on a word: a tap that puts the caret inside a problem
1190                    // shows that problem, as a resting pointer would.
1191                    onpointerup: move |evt: PointerEvent| {
1192                        if !language_server || evt.data().pointer_type() != "touch" {
1193                            return;
1194                        }
1195                        #[cfg(target_arch = "wasm32")]
1196                        {
1197                            let source = source_for_tap.clone();
1198                            spawn(async move {
1199                                gloo_timers::future::TimeoutFuture::new(0).await;
1200                                let Some(area) = textarea(&textarea_id.read()) else { return };
1201                                let Some(units) = area.selection_start().ok().flatten() else { return };
1202                                let offset = byte_at(&area.value(), units as usize);
1203                                let here = {
1204                                    let found = found.peek();
1205                                    if found.0 == source { found.1.clone() } else { rebase(&found.1, &found.0, &source) }
1206                                };
1207                                match (problems_html(&here, offset), token_box(&area, offset)) {
1208                                    (Some(html), Some(rect)) => {
1209                                        keep_hint();
1210                                        hint.set(Some(HoverHint { offset, html, style: hint_placement(&rect) }));
1211                                    }
1212                                    _ => hide_hint(),
1213                                }
1214                            });
1215                        }
1216                    },
1217                    oninput: move |evt| {
1218                        hide_hint();
1219                        let text = evt.value();
1220                        let mut typed = typed;
1221                        typed.set(Some(text.clone()));
1222                        on_change.call(text);
1223                        report_caret();
1224                        #[cfg(target_arch = "wasm32")]
1225                        spawn(async move {
1226                            gloo_timers::future::TimeoutFuture::new(0).await;
1227                            keep_caret_in_view(&textarea_id.read());
1228                        });
1229                        // Sync scroll after input in case highlight re-renders
1230                        #[cfg(target_arch = "wasm32")]
1231                        {
1232                            let _ = js_sys::eval(r#"
1233                                requestAnimationFrame(function() {
1234                                    document.querySelectorAll('.code-editor-textarea').forEach(function(ta) {
1235                                        var highlight = ta.previousElementSibling;
1236                                        if (highlight && highlight.classList.contains('code-editor-highlight')) {
1237                                            var taMax = ta.scrollHeight - ta.clientHeight;
1238                                            var hlMax = highlight.scrollHeight - highlight.clientHeight;
1239                                            // Cap scroll to the shorter element's max
1240                                            var maxScroll = Math.min(taMax, hlMax);
1241                                            if (ta.scrollTop > maxScroll) {
1242                                                ta.scrollTop = maxScroll;
1243                                            }
1244                                            highlight.scrollTop = ta.scrollTop;
1245                                            highlight.scrollLeft = ta.scrollLeft;
1246                                        }
1247                                    });
1248                                });
1249                            "#);
1250                        }
1251                    },
1252                    onscroll: move |_| {
1253                        hide_hint();
1254                        #[cfg(target_arch = "wasm32")]
1255                        {
1256                            let _ = js_sys::eval(r#"
1257                                document.querySelectorAll('.code-editor-textarea').forEach(function(ta) {
1258                                    var highlight = ta.previousElementSibling;
1259                                    if (highlight && highlight.classList.contains('code-editor-highlight')) {
1260                                        var taMax = ta.scrollHeight - ta.clientHeight;
1261                                        var hlMax = highlight.scrollHeight - highlight.clientHeight;
1262                                        // Cap scroll to the shorter element's max
1263                                        var maxScroll = Math.min(taMax, hlMax);
1264                                        if (ta.scrollTop > maxScroll) {
1265                                            ta.scrollTop = maxScroll;
1266                                        }
1267                                        highlight.scrollTop = ta.scrollTop;
1268                                        highlight.scrollLeft = ta.scrollLeft;
1269                                    }
1270                                });
1271                            "#);
1272                        }
1273                    },
1274                }
1275            }
1276            if let Some(h) = hint.read().as_ref() {
1277                div {
1278                    class: "hover-hint",
1279                    style: "{h.style}",
1280                    onmouseenter: move |_| {
1281                        hint_hovered.set(true);
1282                        bump(hint_gen);
1283                        keep_hint();
1284                    },
1285                    onmouseleave: move |_| hide_hint(),
1286                    dangerous_inner_html: "{h.html}",
1287                }
1288            }
1289        }
1290    }
1291}
1292
1293/// How long the pointer rests on a word before its hover appears — VS Code's default.
1294#[cfg(target_arch = "wasm32")]
1295const HOVER_DELAY_MS: u32 = 300;
1296
1297/// A key the editor handles itself.
1298#[cfg(target_arch = "wasm32")]
1299#[derive(Clone, Copy)]
1300enum EditKey {
1301    Enter,
1302    Indent,
1303    Outdent,
1304}
1305
1306/// Enter, Tab or Shift-Tab in the textarea `id`, as its language indents (see [`Indentation`]):
1307/// the edit goes through the browser's own editing, so it can be undone like typing. False when
1308/// the browser should do what it does.
1309#[cfg(target_arch = "wasm32")]
1310fn edit_on_key(id: &str, language: Language, key: EditKey) -> bool {
1311    let Some(area) = textarea(id) else {
1312        return false;
1313    };
1314    let text = area.value();
1315    let (Ok(Some(start)), Ok(Some(end))) = (area.selection_start(), area.selection_end()) else {
1316        return false;
1317    };
1318    let (start, end) = (byte_at(&text, start as usize), byte_at(&text, end as usize));
1319    let indentation = Indentation::of(language, &text);
1320    let line_start = text[..start].rfind('\n').map_or(0, |i| i + 1);
1321    let line_end = text[start..].find('\n').map_or(text.len(), |i| start + i);
1322    let select = |from: usize, to: usize| {
1323        let _ = area.set_selection_range(utf16_at(&text, from) as u32, utf16_at(&text, to) as u32);
1324    };
1325    match key {
1326        EditKey::Enter => {
1327            let line = &text[line_start..line_end];
1328            let enter = indentation.enter(line, start - line_start);
1329            let own = line.len() - line.trim_start().len();
1330            if let (Some(reindent), true) =
1331                (&enter.reindent, start == end && start >= line_start + own)
1332            {
1333                select(line_start, line_start + own);
1334                insert_text(&area, reindent);
1335                let caret = area.selection_start().ok().flatten().unwrap_or(0) as usize
1336                    + utf16_len(&text[line_start + own..start]);
1337                let _ = area.set_selection_range(caret as u32, caret as u32);
1338            }
1339            insert_text(&area, &enter.insert);
1340        }
1341        EditKey::Indent if !text[start..end].contains('\n') => {
1342            let column = text[line_start..start].chars().count();
1343            insert_text(&area, &indentation.tab_fill(column));
1344        }
1345        EditKey::Indent | EditKey::Outdent => {
1346            // Every line the selection touches — but not a last line it only reaches the start of.
1347            let last = if end > start && text[..end].ends_with('\n') {
1348                end - 1
1349            } else {
1350                end
1351            };
1352            let block_end = text[last..].find('\n').map_or(text.len(), |i| last + i);
1353            let block = &text[line_start..block_end];
1354            let moved = match key {
1355                EditKey::Indent => indentation.indent_lines(block),
1356                _ => indentation.outdent_lines(block),
1357            };
1358            if moved == block {
1359                return true;
1360            }
1361            let shift = utf16_len(block) as isize - utf16_len(&moved) as isize;
1362            select(line_start, block_end);
1363            insert_text(&area, &moved);
1364            if start == end {
1365                let caret = (utf16_at(&text, start) as isize - shift)
1366                    .max(utf16_at(&text, line_start) as isize) as u32;
1367                let _ = area.set_selection_range(caret, caret);
1368            } else {
1369                let from = utf16_at(&text, line_start) as u32;
1370                let _ = area.set_selection_range(from, from + utf16_len(&moved) as u32);
1371            }
1372        }
1373    }
1374    true
1375}
1376
1377/// Replace the textarea's selection with `text` through the browser's editing command, which
1378/// keeps the undo history and raises `input` like typing; where the command is missing, set
1379/// the text directly and raise `input` by hand.
1380#[cfg(target_arch = "wasm32")]
1381fn insert_text(area: &web_sys::HtmlTextAreaElement, text: &str) {
1382    use wasm_bindgen::JsCast;
1383    let document = area
1384        .owner_document()
1385        .and_then(|d| d.dyn_into::<web_sys::HtmlDocument>().ok());
1386    let command = if text.is_empty() {
1387        "delete"
1388    } else {
1389        "insertText"
1390    };
1391    let done = document.is_some_and(|d| {
1392        d.exec_command_with_show_ui_and_value(command, false, text)
1393            .unwrap_or(false)
1394    });
1395    if !done {
1396        let start = area.selection_start().ok().flatten().unwrap_or(0);
1397        let end = area.selection_end().ok().flatten().unwrap_or(start);
1398        let _ = area.set_range_text_with_start_and_end(text, start, end);
1399        let caret = start + utf16_len(text) as u32;
1400        let _ = area.set_selection_range(caret, caret);
1401        if let Ok(event) = web_sys::InputEvent::new("input") {
1402            let _ = area.dispatch_event(&event);
1403        }
1404    }
1405}
1406
1407/// The byte offset in `text` of the UTF-16 offset `units`, as the browser counts selections.
1408#[cfg(target_arch = "wasm32")]
1409fn byte_at(text: &str, units: usize) -> usize {
1410    let mut seen = 0;
1411    for (at, c) in text.char_indices() {
1412        if seen >= units {
1413            return at;
1414        }
1415        seen += c.len_utf16();
1416    }
1417    text.len()
1418}
1419
1420/// The UTF-16 offset of the byte offset `at` in `text`.
1421#[cfg(target_arch = "wasm32")]
1422fn utf16_at(text: &str, at: usize) -> usize {
1423    utf16_len(&text[..at])
1424}
1425
1426#[cfg(target_arch = "wasm32")]
1427fn utf16_len(text: &str) -> usize {
1428    text.encode_utf16().count()
1429}
1430
1431/// A fresh id for an editor's textarea, so its caret can be read back.
1432fn next_textarea_id() -> String {
1433    use std::sync::atomic::{AtomicUsize, Ordering};
1434    static NEXT: AtomicUsize = AtomicUsize::new(0);
1435    format!("code-editor-{}", NEXT.fetch_add(1, Ordering::Relaxed))
1436}
1437
1438/// The editor's textarea `id`.
1439#[cfg(target_arch = "wasm32")]
1440fn textarea(id: &str) -> Option<web_sys::HtmlTextAreaElement> {
1441    use wasm_bindgen::JsCast;
1442    web_sys::window()?
1443        .document()?
1444        .get_element_by_id(id)?
1445        .dyn_into::<web_sys::HtmlTextAreaElement>()
1446        .ok()
1447}
1448
1449/// Where the caret sits in the textarea `id`.
1450#[cfg(target_arch = "wasm32")]
1451fn caret_in(id: &str) -> Option<Caret> {
1452    let area = textarea(id)?;
1453    let start = area.selection_start().ok()?? as usize;
1454    let end = area.selection_end().ok()?? as usize;
1455    let backward = area.selection_direction().ok().flatten().as_deref() == Some("backward");
1456    Some(Caret::of(&area.value(), start, end, backward))
1457}
1458
1459/// Put the textarea `id`'s caret at the start of its text.
1460#[cfg(target_arch = "wasm32")]
1461fn caret_to_start(id: &str) {
1462    if let Some(area) = textarea(id) {
1463        let _ = area.set_selection_range(0, 0);
1464    }
1465}
1466
1467/// In Math, a symbol the font draws for a spelling (`forall` as ∀) is one character to the
1468/// reader: a caret that lands inside the spelling moves to an edge of it.
1469#[cfg(target_arch = "wasm32")]
1470fn snap_caret(id: &str, toward: Snap) {
1471    let Some(area) = textarea(id) else { return };
1472    let (Ok(Some(start)), Ok(Some(end))) = (area.selection_start(), area.selection_end()) else {
1473        return;
1474    };
1475    if start != end {
1476        return;
1477    }
1478    let text = area.value();
1479    let at = byte_at(&text, start as usize);
1480    let snapped = super::vernacular::snap(&text, at, toward);
1481    if snapped != at {
1482        let caret = utf16_at(&text, snapped) as u32;
1483        let _ = area.set_selection_range(caret, caret);
1484    }
1485}
1486
1487/// How long a hover waits, once the pointer leaves its word, for the pointer to reach it.
1488#[cfg(target_arch = "wasm32")]
1489const HIDE_GRACE_MS: u32 = 300;
1490
1491/// How long typing pauses before the language server looks again.
1492#[cfg(target_arch = "wasm32")]
1493const ANALYSIS_DELAY_MS: u32 = 350;
1494
1495/// The problems `language`'s service finds in `source`.
1496fn service_problems(
1497    language: Language,
1498    cache: &std::rc::Rc<std::cell::RefCell<Option<std::rc::Rc<DocumentState>>>>,
1499    source: &str,
1500) -> Vec<Problem> {
1501    match language {
1502        Language::Logos | Language::Logic => problems(&analysed(cache, source)),
1503        Language::Hardware => crate::ui::pages::hardware_spec::problems(source),
1504        Language::Vernacular | Language::Rust => Vec::new(),
1505    }
1506}
1507
1508/// What `language`'s service says about the word at byte `offset`, as markdown.
1509#[cfg(target_arch = "wasm32")]
1510fn service_hover(
1511    language: Language,
1512    cache: &std::rc::Rc<std::cell::RefCell<Option<std::rc::Rc<DocumentState>>>>,
1513    source: &str,
1514    offset: usize,
1515) -> Option<String> {
1516    if comment_at(source, language, offset) {
1517        return None;
1518    }
1519    match language {
1520        Language::Logos | Language::Logic => hover_markdown(&analysed(cache, source), offset),
1521        Language::Hardware => crate::ui::pages::hardware_spec::hover(source, offset),
1522        Language::Vernacular | Language::Rust => None,
1523    }
1524}
1525
1526/// The language server's analysis of `source`, from the cache when it is of the same text.
1527fn analysed(
1528    cache: &std::rc::Rc<std::cell::RefCell<Option<std::rc::Rc<DocumentState>>>>,
1529    source: &str,
1530) -> std::rc::Rc<DocumentState> {
1531    let mut cached = cache.borrow_mut();
1532    match cached.as_ref() {
1533        Some(doc) if doc.source == source => doc.clone(),
1534        _ => {
1535            let doc = std::rc::Rc::new(DocumentState::new(source.to_string(), 0));
1536            *cached = Some(doc.clone());
1537            doc
1538        }
1539    }
1540}
1541
1542/// Advance a generation counter, voiding whatever was waiting on its old value.
1543fn bump(mut generation: Signal<u64>) -> u64 {
1544    let next = *generation.peek() + 1;
1545    generation.set(next);
1546    next
1547}
1548
1549/// A hover on screen: the token it describes, its HTML, and where it sits.
1550#[derive(Clone, PartialEq)]
1551struct HoverHint {
1552    offset: usize,
1553    html: String,
1554    style: String,
1555}
1556
1557/// The highlighted token under a viewport point, as its source offset and on-screen box: the
1558/// editor's textarea sits over the highlight layer, so find the textarea there and test the
1559/// token spans beside it.
1560#[cfg(target_arch = "wasm32")]
1561fn token_under(x: f64, y: f64) -> Option<(usize, web_sys::DomRect)> {
1562    use wasm_bindgen::JsCast;
1563    let document = web_sys::window()?.document()?;
1564    let textarea = document
1565        .elements_from_point(x as f32, y as f32)
1566        .iter()
1567        .filter_map(|v| v.dyn_into::<web_sys::Element>().ok())
1568        .find(|e| e.class_list().contains("code-editor-textarea"))?;
1569    let highlight = textarea.previous_element_sibling()?;
1570    let spans = highlight.query_selector_all("[data-o]").ok()?;
1571    for i in 0..spans.length() {
1572        let Some(span) = spans
1573            .item(i)
1574            .and_then(|n| n.dyn_into::<web_sys::Element>().ok())
1575        else {
1576            continue;
1577        };
1578        let boxes = span.get_client_rects();
1579        for j in 0..boxes.length() {
1580            let Some(r) = boxes.item(j) else { continue };
1581            if x >= r.left() && x <= r.right() && y >= r.top() && y <= r.bottom() {
1582                return Some((span.get_attribute("data-o")?.parse().ok()?, r));
1583            }
1584        }
1585    }
1586    None
1587}
1588
1589/// The on-screen box of the highlighted token at byte `offset` of the textarea `area`'s source.
1590#[cfg(target_arch = "wasm32")]
1591fn token_box(area: &web_sys::HtmlTextAreaElement, offset: usize) -> Option<web_sys::DomRect> {
1592    use wasm_bindgen::JsCast;
1593    let spans = area.previous_element_sibling()?.query_selector_all("[data-o]").ok()?;
1594    (0..spans.length()).rev().filter_map(|i| spans.item(i)?.dyn_into::<web_sys::Element>().ok()).find_map(|span| {
1595        let start: usize = span.get_attribute("data-o")?.parse().ok()?;
1596        let end = start + span.text_content().map_or(0, |t| t.len());
1597        (start <= offset && offset <= end).then(|| span.get_bounding_client_rect())
1598    })
1599}
1600
1601/// Scroll the focused textarea `id` so its caret's line shows in the part of it the reader can see,
1602/// above an on-screen keyboard ([`caret_in_view`]). Lines do not wrap, so the caret's line is its
1603/// count of line breaks down the text.
1604#[cfg(target_arch = "wasm32")]
1605fn keep_caret_in_view(id: &str) {
1606    use crate::ui::pages::studio_layout::{caret_in_view, Extent};
1607    let (Some(area), Some(window)) = (textarea(id), web_sys::window()) else { return };
1608    let focused = window.document().and_then(|d| d.active_element()).is_some_and(|active| active == **area);
1609    let Some(style) = window.get_computed_style(&area).ok().flatten() else { return };
1610    let length = |name: &str| style.get_property_value(name).ok().and_then(|v| v.trim_end_matches("px").parse::<f64>().ok());
1611    let (Some(line_height), Some(padding_top), Some(units)) = (length("line-height"), length("padding-top"), area.selection_start().ok().flatten()) else { return };
1612    if !focused || line_height <= 0.0 {
1613        return;
1614    }
1615    let line = area.value().encode_utf16().take(units as usize).filter(|&unit| unit == u16::from(b'\n')).count() as f64;
1616    let rect = area.get_bounding_client_rect();
1617    let top = rect.top() + padding_top + line * line_height - f64::from(area.scroll_top());
1618    let (seen_top, seen_bottom) = match window.visual_viewport() {
1619        Some(visual) => (visual.offset_top(), visual.offset_top() + visual.height()),
1620        None => (0.0, window.inner_height().ok().and_then(|h| h.as_f64()).unwrap_or(rect.bottom())),
1621    };
1622    let view = Extent { top: rect.top().max(seen_top), bottom: rect.bottom().min(seen_bottom) };
1623    let dy = caret_in_view(Extent { top, bottom: top + line_height }, view);
1624    if dy.abs() >= 1.0 {
1625        area.set_scroll_top(area.scroll_top() + dy.round() as i32);
1626    }
1627}
1628
1629/// Above the word when there is room (VS Code's habit), otherwise below; never off-screen.
1630#[cfg(target_arch = "wasm32")]
1631fn hint_placement(word: &web_sys::DomRect) -> String {
1632    let window = web_sys::window();
1633    let size = |f: fn(&web_sys::Window) -> Result<wasm_bindgen::JsValue, wasm_bindgen::JsValue>| {
1634        window
1635            .as_ref()
1636            .and_then(|w| f(w).ok())
1637            .and_then(|v| v.as_f64())
1638            .unwrap_or(1080.0)
1639    };
1640    let (width, height) = (
1641        size(web_sys::Window::inner_width),
1642        size(web_sys::Window::inner_height),
1643    );
1644    let left = word.left().min(width - HINT_MAX_WIDTH - 8.0).max(8.0);
1645    if word.top() > height * 0.35 {
1646        format!(
1647            "left: {left:.0}px; bottom: {:.0}px;",
1648            height - word.top() + 6.0
1649        )
1650    } else {
1651        format!("left: {left:.0}px; top: {:.0}px;", word.bottom() + 6.0)
1652    }
1653}
1654
1655/// The widest a hover grows, matching `.hover-hint`'s `max-width`.
1656#[cfg(target_arch = "wasm32")]
1657const HINT_MAX_WIDTH: f64 = 520.0;
1658
1659/// The most tokens a highlight layer draws as siblings. dioxus-interpreter sends the number of
1660/// nodes an edit moves as a `u16`, so a longer row of siblings wraps the count and the page stops
1661/// answering; the highlighters group their tokens into inline runs no longer than this (locked by
1662/// tests/code_view_channel_lock.rs).
1663const TOKEN_RUN: usize = 4096;
1664
1665/// Read-only syntax-highlighted code view.
1666#[component]
1667pub fn CodeView(code: String, language: Language) -> Element {
1668    let tokens = tokenize(&code, language);
1669
1670    rsx! {
1671        style { "{CODE_EDITOR_STYLE}" }
1672
1673        div { class: "code-editor lang-{language.css_class()}",
1674            div { class: "code-editor-highlight",
1675                style: "position: relative; height: 100%; overflow: auto; pointer-events: auto;",
1676                for run in tokens.chunks(TOKEN_RUN) {
1677                    span {
1678                        for token in run.iter() {
1679                            if token.text.chars().all(|c| c.is_whitespace()) {
1680                                "{token.text}"
1681                            } else {
1682                                span {
1683                                    class: "{token_class(token.kind)}",
1684                                    "{token.text}"
1685                                }
1686                            }
1687                        }
1688                    }
1689                }
1690            }
1691        }
1692    }
1693}
1694
1695#[cfg(test)]
1696#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/components/code_editor/hardware_highlighting_tests.rs"]
1697mod hardware_highlighting_tests;
1698
1699#[cfg(test)]
1700#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/components/code_editor/logic_highlighting_tests.rs"]
1701mod logic_highlighting_tests;
1702
1703#[cfg(test)]
1704#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/components/code_editor/hash_comment_tests.rs"]
1705mod hash_comment_tests;
1706
1707#[cfg(test)]
1708#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/components/code_editor/logos_keyword_tests.rs"]
1709mod logos_keyword_tests;