cliboard 0.1.0

Live math whiteboard for your terminal — render LaTeX equations in the browser with per-step AI chat
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use crate::document::{Block, Document, Theme};

/// Render a single LaTeX equation to HTML using KaTeX (display mode).
pub fn render_equation(latex: &str) -> Result<String, String> {
    let opts = katex::Opts::builder()
        .display_mode(true)
        .build()
        .unwrap();
    katex::render_with_opts(latex, opts).map_err(|e| e.to_string())
}

/// Render inline LaTeX (not display mode).
pub fn render_inline_math(latex: &str) -> Result<String, String> {
    let opts = katex::Opts::builder()
        .display_mode(false)
        .build()
        .unwrap();
    katex::render_with_opts(latex, opts).map_err(|e| e.to_string())
}

/// Render chat text with inline math support.
pub fn render_chat_text(text: &str) -> String {
    process_inline_math(text)
}

/// Render reply content with display equations (sub-numbered) and inline math.
///
/// Splits on `$$...$$` delimiters:
/// - Display equations → KaTeX display mode with sub-numbering `(step_id.1)`, `(step_id.2)`, ...
/// - Prose between equations → inline math processed, wrapped in `<p class="reply-prose">`
pub fn render_reply_content(text: &str, step_id: usize) -> String {
    let mut result = String::with_capacity(text.len() * 2);
    result.push_str("<div class=\"reply-content\">");

    let mut eq_sub = 0usize;
    let mut rest = text;

    loop {
        match rest.find("$$") {
            Some(start) => {
                // Prose before the equation
                let prose = &rest[..start];
                let prose_trimmed = prose.trim();
                if !prose_trimmed.is_empty() {
                    result.push_str("<p class=\"reply-prose\">");
                    result.push_str(&process_inline_math(prose_trimmed));
                    result.push_str("</p>");
                }

                // Find closing $$
                let after_open = &rest[start + 2..];
                match after_open.find("$$") {
                    Some(end) => {
                        let latex = after_open[..end].trim();
                        eq_sub += 1;

                        if latex.is_empty() {
                            // Empty equation, skip
                            rest = &after_open[end + 2..];
                            continue;
                        }

                        match render_equation(latex) {
                            Ok(rendered) => {
                                result.push_str(&format!(
                                    "<div class=\"equation-card reply-equation\" data-latex=\"{}\" data-eq-num=\"{}.{}\"><div class=\"equation-content\">{}</div><span class=\"equation-number\">({}.{})</span></div>",
                                    html_escape(latex), step_id, eq_sub, rendered, step_id, eq_sub
                                ));
                            }
                            Err(err_msg) => {
                                result.push_str("<div class=\"equation-card reply-equation error-card\">");
                                result.push_str("<code>");
                                result.push_str(&html_escape(latex));
                                result.push_str("</code>");
                                result.push_str("<div class=\"error-msg\">");
                                result.push_str(&html_escape(&err_msg));
                                result.push_str("</div></div>");
                            }
                        }
                        rest = &after_open[end + 2..];
                    }
                    None => {
                        // Unclosed $$, treat rest as prose
                        let remaining = rest.trim();
                        if !remaining.is_empty() {
                            result.push_str("<p class=\"reply-prose\">");
                            result.push_str(&process_inline_math(remaining));
                            result.push_str("</p>");
                        }
                        break;
                    }
                }
            }
            None => {
                // No more equations, remaining is prose
                let remaining = rest.trim();
                if !remaining.is_empty() {
                    result.push_str("<p class=\"reply-prose\">");
                    result.push_str(&process_inline_math(remaining));
                    result.push_str("</p>");
                }
                break;
            }
        }
    }

    result.push_str("</div>");
    result
}

/// HTML-escape a string for use in attributes.
fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

/// Process inline math (`$...$`) in text, rendering each with KaTeX.
/// Non-math text is HTML-escaped to prevent XSS.
/// Does not match `$$...$$` (display math).
pub(crate) fn process_inline_math(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let chars: Vec<char> = text.chars().collect();
    let len = chars.len();
    let mut i = 0;

    // Collect runs of non-math text and escape them together
    let mut text_buf = String::new();

    let flush_text = |buf: &mut String, out: &mut String| {
        if !buf.is_empty() {
            out.push_str(&html_escape(buf));
            buf.clear();
        }
    };

    while i < len {
        // Skip $$ (not inline math)
        if i + 1 < len && chars[i] == '$' && chars[i + 1] == '$' {
            text_buf.push('$');
            text_buf.push('$');
            i += 2;
            continue;
        }

        if chars[i] == '$' {
            // Look for closing $
            let start = i + 1;
            let mut end = None;
            let mut j = start;
            while j < len {
                if j + 1 < len && chars[j] == '$' && chars[j + 1] == '$' {
                    j += 2;
                    continue;
                }
                if chars[j] == '$' {
                    end = Some(j);
                    break;
                }
                j += 1;
            }

            if let Some(end_pos) = end {
                let latex: String = chars[start..end_pos].iter().collect();
                if latex.is_empty() {
                    text_buf.push('$');
                    i += 1;
                    continue;
                }
                flush_text(&mut text_buf, &mut result);
                match render_inline_math(&latex) {
                    Ok(html) => result.push_str(&html),
                    Err(_) => {
                        result.push_str("<code class=\"error-inline\">");
                        result.push('$');
                        result.push_str(&html_escape(&latex));
                        result.push('$');
                        result.push_str("</code>");
                    }
                }
                i = end_pos + 1;
            } else {
                text_buf.push('$');
                i += 1;
            }
        } else {
            text_buf.push(chars[i]);
            i += 1;
        }
    }

    flush_text(&mut text_buf, &mut result);
    result
}

/// Render a single block to HTML (used by tests that don't need equation numbers).
fn render_block(block: &Block) -> String {
    let mut eq_num: usize = 0;
    render_block_numbered(block, &mut eq_num)
}

/// Render a single block to HTML with sequential equation numbering.
fn render_block_numbered(block: &Block, eq_number: &mut usize) -> String {
    match block {
        Block::Step {
            id,
            title,
            equations,
            notes,
            is_result,
        } => {
            let class = if *is_result { "step result" } else { "step" };
            let data_latex = equations
                .first()
                .map(|eq| html_escape(eq))
                .unwrap_or_default();

            let mut html = format!(
                "<div class=\"{}\" data-step-id=\"{}\" data-step-title=\"{}\" data-latex=\"{}\">",
                class,
                id,
                html_escape(title),
                data_latex
            );

            // Step header (titles support inline math via $...$)
            html.push_str(&format!(
                "<div class=\"step-header\"><span class=\"step-number\">{}.</span><span class=\"step-title\">{}</span></div>",
                id,
                process_inline_math(title)
            ));

            // Equations with numbers
            for eq in equations {
                *eq_number += 1;
                match render_equation(eq) {
                    Ok(rendered) => {
                        html.push_str(&format!(
                            "<div class=\"equation-card\"><div class=\"equation-content\">{}</div><span class=\"equation-number\">({})</span></div>",
                            rendered, eq_number
                        ));
                    }
                    Err(err_msg) => {
                        html.push_str("<div class=\"equation-card error-card\">");
                        html.push_str("<code>");
                        html.push_str(&html_escape(eq));
                        html.push_str("</code>");
                        html.push_str("<div class=\"error-msg\">");
                        html.push_str(&html_escape(&err_msg));
                        html.push_str("</div></div>");
                    }
                }
            }

            // Notes (with inline math)
            for note in notes {
                html.push_str("<div class=\"note\">");
                html.push_str(&process_inline_math(note));
                html.push_str("</div>");
            }

            html.push_str("</div>");
            html
        }
        Block::Prose { content } => {
            format!(
                "<div class=\"prose\">{}</div>",
                process_inline_math(content)
            )
        }
        Block::Divider => "<hr class=\"divider\">".to_string(),
    }
}

/// Render all blocks to HTML string (just the blocks, not the full page).
pub fn render_blocks_html(doc: &Document) -> String {
    // Pre-allocate: ~1KB per block is a reasonable estimate
    let mut html = String::with_capacity(doc.blocks.len() * 1024);
    let mut eq_number: usize = 0;
    for block in &doc.blocks {
        html.push_str(&render_block_numbered(block, &mut eq_number));
    }
    html
}

/// Render the full HTML page (viewer shell + rendered blocks).
pub fn render_full_page(doc: &Document) -> String {
    let theme_class = match doc.theme {
        Theme::Dark => "dark",
        Theme::Light => "light",
    };
    let blocks_html = render_blocks_html(doc);
    let title_escaped = html_escape(&doc.title);

    format!(
        r#"<!DOCTYPE html>
<html lang="en" data-theme="{theme_class}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title_escaped} — cliboard</title>
    <link rel="stylesheet" href="/katex.min.css">
    <link rel="stylesheet" href="/viewer.css">
</head>
<body>
    <div id="board">
        <header id="board-header">
            <h1>{title_escaped}</h1>
        </header>
        <main id="board-content">
            {blocks_html}
        </main>
    </div>
    <script src="/viewer.js"></script>
</body>
</html>"#
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::Document;

    #[test]
    fn test_render_equation_success() {
        let result = render_equation("E = mc^2");
        assert!(result.is_ok());
        let html = result.unwrap();
        assert!(html.contains("katex"));
    }

    #[test]
    fn test_render_equation_error() {
        let result = render_equation(r"\");
        assert!(result.is_err());
    }

    #[test]
    fn test_render_inline_math() {
        let result = render_inline_math("x^2");
        assert!(result.is_ok());
        let html = result.unwrap();
        assert!(html.contains("katex"));
        // Inline mode should NOT contain katex-display
        assert!(!html.contains("katex-display"));
    }

    #[test]
    fn test_html_escape() {
        assert_eq!(html_escape("<div>"), "&lt;div&gt;");
        assert_eq!(html_escape("a&b"), "a&amp;b");
        assert_eq!(html_escape("x=\"y\""), "x=&quot;y&quot;");
    }

    #[test]
    fn test_process_inline_math() {
        let result = process_inline_math("The value $x^2$ is positive");
        assert!(result.contains("katex"));
        assert!(result.contains("The value "));
        assert!(result.contains(" is positive"));
    }

    #[test]
    fn test_process_inline_math_no_math() {
        let result = process_inline_math("No math here");
        assert_eq!(result, "No math here");
    }

    #[test]
    fn test_process_inline_math_error() {
        let result = process_inline_math("Bad: $\\$ end");
        assert!(result.contains("error-inline"));
    }

    #[test]
    fn test_render_blocks_html_step() {
        let doc = Document {
            title: "Test".to_string(),
            theme: Theme::Dark,
            blocks: vec![Block::Step {
                id: 1,
                title: "First Step".to_string(),
                equations: vec!["E = mc^2".to_string()],
                notes: vec!["Energy equation".to_string()],
                is_result: false,
            }],
        };
        let html = render_blocks_html(&doc);
        assert!(html.contains("data-step-id=\"1\""));
        assert!(html.contains("First Step"));
        assert!(html.contains("equation-card"));
        assert!(html.contains("note"));
    }

    #[test]
    fn test_render_blocks_html_result_step() {
        let doc = Document {
            title: "Test".to_string(),
            theme: Theme::Dark,
            blocks: vec![Block::Step {
                id: 2,
                title: "Result".to_string(),
                equations: vec!["F = ma".to_string()],
                notes: vec![],
                is_result: true,
            }],
        };
        let html = render_blocks_html(&doc);
        assert!(html.contains("class=\"step result\""));
    }

    #[test]
    fn test_render_blocks_html_prose() {
        let doc = Document {
            title: "Test".to_string(),
            theme: Theme::Dark,
            blocks: vec![Block::Prose {
                content: "Some text with $x$ inline".to_string(),
            }],
        };
        let html = render_blocks_html(&doc);
        assert!(html.contains("class=\"prose\""));
        assert!(html.contains("katex"));
    }

    #[test]
    fn test_render_blocks_html_divider() {
        let doc = Document {
            title: "Test".to_string(),
            theme: Theme::Dark,
            blocks: vec![Block::Divider],
        };
        let html = render_blocks_html(&doc);
        assert!(html.contains("<hr class=\"divider\">"));
    }

    #[test]
    fn test_render_full_page() {
        let doc = Document {
            title: "Physics".to_string(),
            theme: Theme::Dark,
            blocks: vec![Block::Divider],
        };
        let html = render_full_page(&doc);
        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("Physics"));
        assert!(html.contains("data-theme=\"dark\""));
        assert!(html.contains("viewer.js"));
    }

    #[test]
    fn test_render_full_page_light_theme() {
        let doc = Document {
            title: "Math".to_string(),
            theme: Theme::Light,
            blocks: vec![],
        };
        let html = render_full_page(&doc);
        assert!(html.contains("data-theme=\"light\""));
    }

    #[test]
    fn test_render_equation_simple_display() {
        let result = render_equation("a + b = c");
        assert!(result.is_ok());
        let html = result.unwrap();
        assert!(html.contains("katex-display"));
    }

    #[test]
    fn test_render_equation_invalid_latex_error_card() {
        // Completely invalid LaTeX should produce an error
        let result = render_equation(r"\invalidcommand{");
        assert!(result.is_err());
    }

    #[test]
    fn test_render_block_step_html_structure() {
        let block = Block::Step {
            id: 3,
            title: "Test Step".to_string(),
            equations: vec!["x = 1".to_string()],
            notes: vec!["A note".to_string()],
            is_result: false,
        };
        let html = render_block(&block);
        assert!(html.contains("class=\"step\""));
        assert!(html.contains("data-step-id=\"3\""));
        assert!(html.contains("data-step-title=\"Test Step\""));
        assert!(html.contains("step-number"));
        assert!(html.contains("3."));
        assert!(html.contains("step-title"));
        assert!(html.contains("equation-card"));
        assert!(html.contains("class=\"note\""));
        assert!(html.contains("A note"));
    }

    #[test]
    fn test_render_block_prose() {
        let block = Block::Prose {
            content: "Simple paragraph".to_string(),
        };
        let html = render_block(&block);
        assert!(html.contains("class=\"prose\""));
        assert!(html.contains("Simple paragraph"));
    }

    #[test]
    fn test_render_block_divider() {
        let block = Block::Divider;
        let html = render_block(&block);
        assert_eq!(html, "<hr class=\"divider\">");
    }

    #[test]
    fn test_render_block_result_class() {
        let block = Block::Step {
            id: 1,
            title: "Final".to_string(),
            equations: vec!["y = 42".to_string()],
            notes: vec![],
            is_result: true,
        };
        let html = render_block(&block);
        assert!(html.contains("class=\"step result\""));
    }

    #[test]
    fn test_render_block_multiple_equations() {
        let block = Block::Step {
            id: 1,
            title: "Multi".to_string(),
            equations: vec!["a = 1".to_string(), "b = 2".to_string(), "c = 3".to_string()],
            notes: vec![],
            is_result: false,
        };
        let html = render_block(&block);
        // Should have 3 equation-card divs
        let count = html.matches("equation-card").count();
        assert_eq!(count, 3);
    }

    #[test]
    fn test_render_block_notes_with_inline_math() {
        let block = Block::Step {
            id: 1,
            title: "Notes".to_string(),
            equations: vec!["x = 1".to_string()],
            notes: vec!["Where $x$ is a variable".to_string()],
            is_result: false,
        };
        let html = render_block(&block);
        // Inline math should be rendered via KaTeX
        assert!(html.contains("katex"));
        assert!(html.contains("class=\"note\""));
    }

    #[test]
    fn test_html_escape_single_quote() {
        assert_eq!(html_escape("it's"), "it&#x27;s");
    }

    #[test]
    fn test_render_block_data_latex_escaped() {
        let block = Block::Step {
            id: 1,
            title: "Test".to_string(),
            equations: vec!["a < b & c > d".to_string()],
            notes: vec![],
            is_result: false,
        };
        let html = render_block(&block);
        assert!(html.contains("data-latex=\"a &lt; b &amp; c &gt; d\""));
    }

    #[test]
    fn test_render_empty_document() {
        let doc = Document {
            title: "Empty".to_string(),
            theme: Theme::Dark,
            blocks: vec![],
        };
        let html = render_blocks_html(&doc);
        assert!(html.is_empty());

        let full = render_full_page(&doc);
        assert!(full.contains("Empty"));
        assert!(full.contains("board-content"));
    }

    #[test]
    fn test_render_equation_error_card_in_step() {
        // Use invalid LaTeX that will trigger error-card rendering within a step
        let block = Block::Step {
            id: 1,
            title: "Bad".to_string(),
            equations: vec!["\\frac{".to_string()],
            notes: vec![],
            is_result: false,
        };
        let html = render_block(&block);
        assert!(html.contains("error-card"));
        assert!(html.contains("error-msg"));
    }

    #[test]
    fn test_render_reply_content_prose_only() {
        let html = render_reply_content("Just some text with $x^2$ inline", 1);
        assert!(html.contains("reply-content"));
        assert!(html.contains("reply-prose"));
        assert!(html.contains("katex"));
        assert!(!html.contains("equation-card"));
    }

    #[test]
    fn test_render_reply_content_single_equation() {
        let html = render_reply_content("Before $$E = mc^2$$ after", 3);
        assert!(html.contains("reply-content"));
        assert!(html.contains("reply-equation"));
        assert!(html.contains("(3.1)"));
        assert!(html.contains("Before"));
        assert!(html.contains("after"));
    }

    #[test]
    fn test_render_reply_content_multiple_equations() {
        let html = render_reply_content("Start $$a = 1$$ middle $$b = 2$$ end", 2);
        assert!(html.contains("(2.1)"));
        assert!(html.contains("(2.2)"));
        assert!(html.contains("Start"));
        assert!(html.contains("middle"));
        assert!(html.contains("end"));
    }

    #[test]
    fn test_render_reply_content_equation_only() {
        let html = render_reply_content("$$x = 1$$", 1);
        assert!(html.contains("(1.1)"));
        assert!(html.contains("equation-card"));
        // No prose paragraphs
        assert!(!html.contains("reply-prose"));
    }

    #[test]
    fn test_render_reply_content_invalid_latex() {
        let html = render_reply_content("Bad: $$\\frac{$$ ok", 1);
        assert!(html.contains("error-card"));
        assert!(html.contains("ok"));
    }

    #[test]
    fn test_render_reply_content_empty() {
        let html = render_reply_content("", 1);
        assert!(html.contains("reply-content"));
        assert!(!html.contains("reply-prose"));
        assert!(!html.contains("equation-card"));
    }

    #[test]
    fn test_render_reply_content_inline_math_in_prose() {
        let html = render_reply_content("Where $n$ is the quantum number $$E_n = -13.6/n^2$$", 1);
        assert!(html.contains("(1.1)"));
        // Inline math in prose should be rendered
        assert!(html.contains("katex"));
    }

    #[test]
    fn test_render_reply_content_unclosed_display_math() {
        let html = render_reply_content("Text $$ unclosed", 1);
        // Should treat as prose, not crash
        assert!(html.contains("reply-prose"));
        assert!(!html.contains("equation-card"));
    }
}