mkgraphic 0.4.4

A Rust port of the cycfi/elements GUI framework
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! A scrollable chat message list rendered as colored bubbles per sender,
//! word-wrapped to the available width. Built for `mkide-app`'s Assistant
//! chat panel, which used to render its history as plain `"You: ..."` /
//! `"Assistant: ..."` lines inside a read-only `CodeEditor` -- a plain
//! monospace text widget can't render distinct colored, aligned bubbles,
//! so this is a purpose-built element instead, modeled on `List`'s
//! scroll/clip/draw conventions (`src/element/list.rs`).
//!
//! Display-only, like `List`/`Dropdown` -- no text selection/copy of
//! history content (a real trade-off against the old `CodeEditor`-backed
//! history, inherent to bubble rendering).
//!
//! An assistant message can be built up incrementally -- see
//! [`ChatHistory::start_streaming_message`]/[`append_thinking`]/
//! [`append_response`] -- for a model whose reply streams in token by
//! token rather than arriving all at once. `thinking`/`response` are
//! separate fields (not one `text` string) because a model's reasoning,
//! when present, is meant to read as a distinct, de-emphasized section
//! above the real answer, not just more paragraph text. Both are
//! rendered as real Markdown (bold/italic/code/lists) via
//! `crate::support::markdown`, not the plain wrapped text this element
//! used to draw.
//!
//! [`append_thinking`]: ChatHistory::append_thinking
//! [`append_response`]: ChatHistory::append_response

use super::context::{BasicContext, Context};
use super::{Element, ViewLimits, ViewStretch};
use crate::support::canvas::Canvas;
use crate::support::color::Color;
use crate::support::markdown::{self, LaidOutRun, StyledRun, TextRun, WrappedLine};
use crate::support::math;
use crate::support::point::Point;
use crate::support::rect::Rect;
use crate::support::theme::get_theme;
use std::any::Any;
use std::sync::RwLock;

/// Who sent a [`ChatMessage`] -- controls bubble alignment and color.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatSender {
    User,
    Assistant,
    /// Status/banner/error lines -- rendered full-width, centered, and
    /// muted, with no distinct bubble background, so they read as
    /// out-of-band notices rather than a conversation turn.
    System,
}

#[derive(Debug, Clone)]
pub struct ChatMessage {
    pub sender: ChatSender,
    /// The model's reasoning, if any -- empty for User/System messages
    /// and for an Assistant reply whose raw text never contained a
    /// `<|channel>thought`/`<channel|>` pair (see `mkide_llm::channel`).
    pub thinking: String,
    pub response: String,
}

impl ChatMessage {
    pub fn new(sender: ChatSender, text: impl Into<String>) -> Self {
        Self {
            sender,
            thinking: String::new(),
            response: text.into(),
        }
    }
}

/// One laid-out message: its wrapped, styled lines and the bubble rect to
/// draw them in, already positioned in `ctx`-absolute coordinates with
/// scroll applied. `thinking_lines` is empty for any message with no
/// thinking text -- callers skip that whole section rather than drawing
/// an empty label.
struct LaidOutMessage {
    sender: ChatSender,
    thinking_lines: Vec<WrappedLine>,
    response_lines: Vec<WrappedLine>,
    bubble: Rect,
}

/// A message's cached wrapped layout, keyed on exactly the inputs that
/// actually determine it -- the message's own raw text and the wrap
/// width -- never on frame count or scroll position (the anti-pattern
/// `layout_messages`'s own doc comment warns against; that comment is
/// about *this crate's general re-layout-every-call convention*, which
/// is still correct for plain text -- math layout is real box-model
/// computation, not string measurement, so it's worth caching correctly
/// rather than not caching at all).
struct CachedMessageLayout {
    thinking_text: String,
    response_text: String,
    max_width: f32,
    thinking_lines: Option<Vec<WrappedLine>>,
    response_lines: Option<Vec<WrappedLine>>,
}

/// A scrollable list of chat bubbles.
pub struct ChatHistory {
    messages: RwLock<Vec<ChatMessage>>,
    /// Parallel-indexed to `messages` (`layout_cache.len() ==
    /// messages.len()` always) -- see `CachedMessageLayout`'s own doc
    /// comment for the caching rationale.
    layout_cache: RwLock<Vec<Option<CachedMessageLayout>>>,
    scroll_offset: RwLock<f32>,
    width: f32,
    height: f32,
    font_size: f32,
    padding: f32,
    bubble_padding: f32,
    bubble_max_width_ratio: f32,
    corner_radius: f32,
    gap: f32,
    background_color: Color,
    user_bubble_color: Color,
    assistant_bubble_color: Color,
    user_text_color: Color,
    assistant_text_color: Color,
    system_text_color: Color,
    thinking_text_color: Color,
    enabled: bool,
}

impl ChatHistory {
    /// Creates a new, empty chat history.
    pub fn new() -> Self {
        let theme = get_theme();
        Self {
            messages: RwLock::new(Vec::new()),
            layout_cache: RwLock::new(Vec::new()),
            scroll_offset: RwLock::new(0.0),
            width: 400.0,
            height: 300.0,
            font_size: theme.label_font_size,
            padding: 10.0,
            bubble_padding: 10.0,
            bubble_max_width_ratio: 0.75,
            corner_radius: 10.0,
            gap: 8.0,
            background_color: theme.input_box_color,
            user_bubble_color: theme.chat_user_bubble_color,
            assistant_bubble_color: theme.chat_assistant_bubble_color,
            user_text_color: Color::from_rgb_u8(255, 255, 255),
            assistant_text_color: theme.label_font_color,
            system_text_color: theme.chat_system_text_color,
            thinking_text_color: theme.chat_thinking_text_color,
            enabled: true,
        }
    }

    /// Sets the width.
    pub fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }

    /// Sets the height.
    pub fn height(mut self, height: f32) -> Self {
        self.height = height;
        self
    }

    /// Appends a message and requests a scroll to the bottom to reveal
    /// it. The real clamped scroll position (which needs a wrapped-text
    /// measurement pass against the current width) is resolved the next
    /// time `layout_messages` runs -- see its own doc comment.
    pub fn push_message(&self, sender: ChatSender, text: impl Into<String>) {
        self.messages
            .write()
            .unwrap()
            .push(ChatMessage::new(sender, text));
        self.layout_cache.write().unwrap().push(None);
        *self.scroll_offset.write().unwrap() = f32::MAX;
    }

    /// Starts a new, empty message that [`append_thinking`]/
    /// [`append_response`] grow in place -- for a reply that streams in
    /// token by token rather than arriving all at once. Requests a
    /// scroll to the bottom the same way `push_message` does.
    ///
    /// [`append_thinking`]: Self::append_thinking
    /// [`append_response`]: Self::append_response
    pub fn start_streaming_message(&self, sender: ChatSender) {
        self.messages
            .write()
            .unwrap()
            .push(ChatMessage::new(sender, ""));
        self.layout_cache.write().unwrap().push(None);
        *self.scroll_offset.write().unwrap() = f32::MAX;
    }

    /// Appends `delta` to the thinking text of whatever message is
    /// currently last (the one [`start_streaming_message`] started) --
    /// a no-op if there is no message yet.
    ///
    /// [`start_streaming_message`]: Self::start_streaming_message
    pub fn append_thinking(&self, delta: &str) {
        if let Some(last) = self.messages.write().unwrap().last_mut() {
            last.thinking.push_str(delta);
        }
        *self.scroll_offset.write().unwrap() = f32::MAX;
    }

    /// Appends `delta` to the response text of whatever message is
    /// currently last -- see [`append_thinking`](Self::append_thinking).
    pub fn append_response(&self, delta: &str) {
        if let Some(last) = self.messages.write().unwrap().last_mut() {
            last.response.push_str(delta);
        }
        *self.scroll_offset.write().unwrap() = f32::MAX;
    }

    /// Removes every message and resets scroll.
    pub fn clear(&self) {
        self.messages.write().unwrap().clear();
        self.layout_cache.write().unwrap().clear();
        *self.scroll_offset.write().unwrap() = 0.0;
    }

    fn max_text_width(&self) -> f32 {
        (self.width * self.bubble_max_width_ratio - 2.0 * self.bubble_padding).max(20.0)
    }

    /// Markdown-parses and word-wraps `text` to `max_width`, or `None` if
    /// `text` is empty (a streaming message's thinking/response section
    /// before its first chunk has arrived, or a message with no thinking
    /// at all) -- callers skip an empty section entirely rather than
    /// drawing a lone blank line for it.
    fn wrap_markdown(
        canvas: &mut Canvas,
        text: &str,
        max_width: f32,
        force_italic: bool,
    ) -> Option<Vec<WrappedLine>> {
        if text.is_empty() {
            return None;
        }
        let mut runs = markdown::markdown_to_runs(text);
        if force_italic {
            for line in &mut runs {
                for run in line.iter_mut() {
                    if let StyledRun::Text(text_run) = run {
                        text_run.italic = true;
                    }
                }
            }
        }
        Some(markdown::wrap_runs(canvas, &runs, max_width))
    }

    fn measure_lines_width(canvas: &mut Canvas, lines: &[WrappedLine]) -> f32 {
        lines
            .iter()
            .map(|line| {
                line.runs
                    .iter()
                    .map(|run| match run {
                        LaidOutRun::Text(text_run) => {
                            canvas.font(markdown::run_font(text_run));
                            canvas.text_width(&text_run.text)
                        }
                        LaidOutRun::Math { layout, .. } => layout.width,
                    })
                    .sum::<f32>()
            })
            .fold(0.0f32, f32::max)
    }

    /// Lays out every message top-down, in scroll-adjusted absolute
    /// coordinates matching `ctx.bounds`, returning `(messages,
    /// total_content_height)`. Called on every draw/scroll/hit-test (all
    /// receive `&Context`, which carries the `Canvas` measurement needs),
    /// but each message's actual Markdown parse + wrap + math layout is
    /// only *recomputed* when `layout_cache`'s snapshot of that message's
    /// text/width is stale -- see `CachedMessageLayout`'s own doc comment
    /// for why this is a real cache (keyed on content, not frame/scroll
    /// state), unlike the general "just recompute, chat histories are
    /// small" stance the rest of this crate takes for plain text.
    ///
    /// As a side effect, self-corrects `scroll_offset` against the fresh
    /// `total_content_height` (clamping it into a valid range) -- this is
    /// what actually resolves `push_message`'s `f32::MAX` "scroll to
    /// bottom" sentinel into a real position.
    fn layout_messages(&self, ctx: &Context) -> (Vec<LaidOutMessage>, f32) {
        let messages = self.messages.read().unwrap();
        let max_text_width = self.max_text_width();

        let mut out = Vec::with_capacity(messages.len());
        let mut y = self.padding;

        {
            let mut canvas = ctx.canvas.borrow_mut();
            canvas.font_size(self.font_size);
            let mut cache = self.layout_cache.write().unwrap();
            debug_assert_eq!(
                cache.len(),
                messages.len(),
                "layout_cache must stay parallel-indexed to messages"
            );

            for (i, msg) in messages.iter().enumerate() {
                let cache_hit = cache
                    .get(i)
                    .and_then(|slot| slot.as_ref())
                    .is_some_and(|c| {
                        c.thinking_text == msg.thinking
                            && c.response_text == msg.response
                            && c.max_width == max_text_width
                    });

                if !cache_hit {
                    // The "Thinking" label is folded into `thinking_lines`
                    // as its own first line rather than tracked
                    // separately -- draw_messages then just draws
                    // whatever's in `thinking_lines` uniformly, no
                    // special-cased label draw.
                    let thinking_lines =
                        Self::wrap_markdown(&mut canvas, &msg.thinking, max_text_width, true).map(
                            |mut lines| {
                                canvas.font_size(self.font_size);
                                let metrics = canvas.font_metrics();
                                lines.insert(
                                    0,
                                    WrappedLine {
                                        runs: vec![LaidOutRun::Text(TextRun {
                                            text: "Thinking".to_string(),
                                            bold: false,
                                            italic: true,
                                            monospace: false,
                                        })],
                                        height: metrics.ascent,
                                        depth: metrics.descent,
                                    },
                                );
                                lines
                            },
                        );
                    let response_lines =
                        Self::wrap_markdown(&mut canvas, &msg.response, max_text_width, false);

                    if i < cache.len() {
                        cache[i] = Some(CachedMessageLayout {
                            thinking_text: msg.thinking.clone(),
                            response_text: msg.response.clone(),
                            max_width: max_text_width,
                            thinking_lines,
                            response_lines,
                        });
                    }
                }

                let cached = cache[i].as_ref().unwrap();
                let thinking_lines = cached.thinking_lines.clone();
                let response_lines = cached.response_lines.clone();

                let thinking_height = thinking_lines.as_ref().map_or(0.0, |l| {
                    markdown::measure_wrapped_height(&mut canvas, l, self.font_size)
                });
                let response_height = response_lines.as_ref().map_or(0.0, |l| {
                    markdown::measure_wrapped_height(&mut canvas, l, self.font_size)
                });
                let section_gap = if thinking_lines.is_some() && response_lines.is_some() {
                    self.gap * 0.5
                } else {
                    0.0
                };
                let text_height = thinking_height + section_gap + response_height;

                let thinking_lines = thinking_lines.unwrap_or_default();
                let response_lines = response_lines.unwrap_or_default();

                let bubble = match msg.sender {
                    ChatSender::System => {
                        Rect::new(self.padding, y, self.width - self.padding, y + text_height)
                    }
                    ChatSender::User | ChatSender::Assistant => {
                        let natural_width = Self::measure_lines_width(&mut canvas, &thinking_lines)
                            .max(Self::measure_lines_width(&mut canvas, &response_lines))
                            + 2.0 * self.bubble_padding;
                        let bubble_width =
                            natural_width.min(self.width * self.bubble_max_width_ratio);
                        let (left, right) = if msg.sender == ChatSender::User {
                            (
                                self.width - self.padding - bubble_width,
                                self.width - self.padding,
                            )
                        } else {
                            (self.padding, self.padding + bubble_width)
                        };
                        Rect::new(left, y, right, y + text_height + 2.0 * self.bubble_padding)
                    }
                };

                y = bubble.bottom + self.gap;
                out.push(LaidOutMessage {
                    sender: msg.sender,
                    thinking_lines,
                    response_lines,
                    bubble,
                });
            }
        }

        let total_height = (y - self.gap + self.padding).max(0.0);
        drop(messages);

        let visible_height = ctx.bounds.height();
        let scroll = {
            let mut scroll_guard = self.scroll_offset.write().unwrap();
            *scroll_guard = if total_height <= visible_height {
                0.0
            } else {
                (*scroll_guard).min(total_height - visible_height).max(0.0)
            };
            *scroll_guard
        };

        let dx = ctx.bounds.left;
        let dy = ctx.bounds.top - scroll;
        let out = out
            .into_iter()
            .map(|m| LaidOutMessage {
                bubble: m.bubble.translate(dx, dy),
                ..m
            })
            .collect();

        (out, total_height)
    }

    fn draw_background(&self, ctx: &Context) {
        let mut canvas = ctx.canvas.borrow_mut();
        canvas.fill_style(self.background_color);
        canvas.fill_round_rect(ctx.bounds, self.corner_radius);
    }

    fn draw_messages(&self, ctx: &Context, messages: &[LaidOutMessage]) {
        let mut canvas = ctx.canvas.borrow_mut();
        canvas.font_size(self.font_size);

        for msg in messages {
            if msg.bubble.bottom < ctx.bounds.top || msg.bubble.top > ctx.bounds.bottom {
                continue;
            }

            match msg.sender {
                ChatSender::System => {
                    // System messages are display-only status text (see
                    // this module's own doc comment) and never carry
                    // `thinking` -- only `response_lines` is ever
                    // populated for them, but each line is still centered
                    // per-line rather than left-aligned like a bubble.
                    let leading = {
                        canvas.font_size(self.font_size);
                        canvas.font_metrics().leading.max(self.font_size * 0.2)
                    };
                    let mut y = msg.bubble.top + self.font_size * 0.85;
                    for line in &msg.response_lines {
                        canvas.font_size(self.font_size);
                        let text_metrics = canvas.font_metrics();
                        let width: f32 = line
                            .runs
                            .iter()
                            .map(|run| match run {
                                LaidOutRun::Text(text_run) => {
                                    canvas.font(markdown::run_font(text_run));
                                    canvas.text_width(&text_run.text)
                                }
                                LaidOutRun::Math { layout, .. } => layout.width,
                            })
                            .sum();
                        canvas.fill_style(self.system_text_color);
                        let mut x = msg.bubble.left + (msg.bubble.width() - width) * 0.5;
                        let baseline = y + line.height.max(text_metrics.ascent);
                        for run in &line.runs {
                            match run {
                                LaidOutRun::Text(text_run) => {
                                    canvas.font(markdown::run_font(text_run));
                                    canvas.fill_text(&text_run.text, Point::new(x, baseline));
                                    x += canvas.text_width(&text_run.text);
                                }
                                LaidOutRun::Math { layout, .. } => {
                                    math::draw::draw_math_box(
                                        &mut canvas,
                                        layout,
                                        Point::new(x, baseline),
                                        self.system_text_color,
                                    );
                                    x += layout.width;
                                }
                            }
                        }
                        y = baseline + line.depth.max(text_metrics.descent) + leading;
                    }
                }
                ChatSender::User | ChatSender::Assistant => {
                    let (bubble_color, text_color) = if msg.sender == ChatSender::User {
                        (self.user_bubble_color, self.user_text_color)
                    } else {
                        (self.assistant_bubble_color, self.assistant_text_color)
                    };

                    canvas.fill_style(bubble_color);
                    canvas.fill_round_rect(msg.bubble, self.corner_radius);

                    let mut y = msg.bubble.top + self.bubble_padding + self.font_size * 0.85;
                    if !msg.thinking_lines.is_empty() {
                        markdown::draw_runs(
                            &mut canvas,
                            &msg.thinking_lines,
                            Point::new(msg.bubble.left + self.bubble_padding, y),
                            self.font_size,
                            self.thinking_text_color,
                        );
                        y += markdown::measure_wrapped_height(
                            &mut canvas,
                            &msg.thinking_lines,
                            self.font_size,
                        );
                        if !msg.response_lines.is_empty() {
                            y += self.gap * 0.5;
                        }
                    }
                    if !msg.response_lines.is_empty() {
                        markdown::draw_runs(
                            &mut canvas,
                            &msg.response_lines,
                            Point::new(msg.bubble.left + self.bubble_padding, y),
                            self.font_size,
                            text_color,
                        );
                    }
                }
            }
        }
    }

    fn draw_scrollbar(&self, ctx: &Context, total_height: f32, visible_height: f32) {
        if total_height <= visible_height {
            return;
        }

        let theme = get_theme();
        let scroll = *self.scroll_offset.read().unwrap();

        let scrollbar_height = (visible_height / total_height * visible_height).max(20.0);
        let scrollbar_y =
            scroll / (total_height - visible_height) * (visible_height - scrollbar_height);

        let scrollbar_rect = Rect::new(
            ctx.bounds.right - 8.0,
            ctx.bounds.top + scrollbar_y,
            ctx.bounds.right - 2.0,
            ctx.bounds.top + scrollbar_y + scrollbar_height,
        );

        let mut canvas = ctx.canvas.borrow_mut();
        canvas.fill_style(theme.scrollbar_color);
        canvas.fill_round_rect(scrollbar_rect, 3.0);
    }
}

impl Default for ChatHistory {
    fn default() -> Self {
        Self::new()
    }
}

impl Element for ChatHistory {
    fn limits(&self, _ctx: &BasicContext) -> ViewLimits {
        ViewLimits::min_size(self.width, self.height)
    }

    fn stretch(&self) -> ViewStretch {
        ViewStretch::new(1.0, 1.0)
    }

    fn draw(&self, ctx: &Context) {
        self.draw_background(ctx);

        let (messages, total_height) = self.layout_messages(ctx);
        let visible_height = ctx.bounds.height();

        {
            let mut canvas = ctx.canvas.borrow_mut();
            canvas.save();
            let clip_bounds = Rect::new(
                ctx.bounds.left + self.corner_radius,
                ctx.bounds.top + self.corner_radius,
                ctx.bounds.right - self.corner_radius,
                ctx.bounds.bottom - self.corner_radius,
            );
            canvas.clip(clip_bounds);
        }

        self.draw_messages(ctx, &messages);

        {
            let mut canvas = ctx.canvas.borrow_mut();
            canvas.restore();
        }

        self.draw_scrollbar(ctx, total_height, visible_height);
    }

    fn hit_test(
        &self,
        ctx: &Context,
        p: Point,
        _leaf: bool,
        _control: bool,
    ) -> Option<&dyn Element> {
        if ctx.bounds.contains(p) && self.enabled {
            Some(self)
        } else {
            None
        }
    }

    fn wants_control(&self) -> bool {
        self.enabled
    }

    fn scroll(&mut self, ctx: &Context, dir: Point, p: Point) -> bool {
        self.handle_scroll(ctx, dir, p)
    }

    fn handle_scroll(&self, ctx: &Context, dir: Point, _p: Point) -> bool {
        if !self.enabled {
            return false;
        }

        // Also self-corrects `scroll_offset` against the fresh
        // `total_height` as a side effect -- see `layout_messages`'s doc
        // comment.
        let (_, total_height) = self.layout_messages(ctx);
        let visible_height = ctx.bounds.height();

        if total_height <= visible_height {
            return false;
        }

        let mut scroll = self.scroll_offset.write().unwrap();
        *scroll = (*scroll - dir.y * 20.0)
            .min(total_height - visible_height)
            .max(0.0);

        true
    }

    fn enable(&mut self, state: bool) {
        self.enabled = state;
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Creates a chat history.
pub fn chat_history() -> ChatHistory {
    ChatHistory::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::support::point::Extent;
    use crate::view::View;

    #[test]
    fn wrap_markdown_keeps_every_line_within_max_width() {
        let mut canvas = Canvas::new(400, 400).unwrap();
        canvas.font_size(14.0);
        let text = "the quick brown fox jumps over the lazy dog again and again and again";

        let lines =
            ChatHistory::wrap_markdown(&mut canvas, text, 100.0, false).expect("non-empty text");

        assert!(
            lines.len() > 1,
            "expected wrapping to produce multiple lines"
        );
        for line in &lines {
            let width: f32 = line
                .runs
                .iter()
                .map(|run| match run {
                    LaidOutRun::Text(text_run) => {
                        canvas.font(markdown::run_font(text_run));
                        canvas.text_width(&text_run.text)
                    }
                    LaidOutRun::Math { layout, .. } => layout.width,
                })
                .sum();
            assert!(width <= 101.0, "line exceeds the 100px max width ({width})");
        }
    }

    #[test]
    fn wrap_markdown_forces_a_break_on_a_blank_line_even_under_the_width_limit() {
        // Real CommonMark semantics (a deliberate change from the old
        // plain-text `wrap_text`, which forced a break on *any* literal
        // `\n`): a single newline inside a paragraph is a soft break --
        // it collapses to a space, not a new display line -- only a
        // blank line actually starts a new paragraph.
        let mut canvas = Canvas::new(400, 400).unwrap();
        canvas.font_size(14.0);

        let lines = ChatHistory::wrap_markdown(&mut canvas, "line1\n\nline2", 1000.0, false)
            .expect("non-empty text");

        let rendered: Vec<String> = lines
            .iter()
            .map(|line| {
                line.runs
                    .iter()
                    .map(|r| match r {
                        LaidOutRun::Text(t) => t.text.as_str(),
                        LaidOutRun::Math { .. } => "",
                    })
                    .collect()
            })
            .collect();
        assert_eq!(rendered, vec!["line1".to_string(), "line2".to_string()]);
    }

    #[test]
    fn wrap_markdown_returns_none_for_empty_text() {
        let mut canvas = Canvas::new(400, 400).unwrap();
        assert!(ChatHistory::wrap_markdown(&mut canvas, "", 100.0, false).is_none());
    }

    #[test]
    fn push_message_grows_total_content_height() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        let view = View::new(Extent::new(300.0, 200.0));
        let canvas = std::cell::RefCell::new(Canvas::new(300, 200).unwrap());
        let bounds = Rect::new(0.0, 0.0, 300.0, 200.0);
        let ctx = Context::new(&view, &canvas, bounds);

        let (_, height_before) = history.layout_messages(&ctx);
        history.push_message(ChatSender::User, "hello");
        let (_, height_after) = history.layout_messages(&ctx);

        assert!(height_after > height_before);
    }

    #[test]
    fn user_bubbles_align_further_right_than_assistant_bubbles_for_the_same_text() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.push_message(ChatSender::User, "hi");
        history.push_message(ChatSender::Assistant, "hi");

        let view = View::new(Extent::new(300.0, 200.0));
        let canvas = std::cell::RefCell::new(Canvas::new(300, 200).unwrap());
        let bounds = Rect::new(0.0, 0.0, 300.0, 200.0);
        let ctx = Context::new(&view, &canvas, bounds);

        let (messages, _) = history.layout_messages(&ctx);

        assert_eq!(messages.len(), 2);
        assert!(
            messages[0].bubble.right > messages[1].bubble.right,
            "user bubble (right-aligned) should sit further right than the assistant bubble \
             (left-aligned) for identical text"
        );
    }

    #[test]
    fn handle_scroll_is_a_noop_when_content_already_fits() {
        let history = ChatHistory::new().width(300.0).height(400.0);
        history.push_message(ChatSender::User, "short");

        let view = View::new(Extent::new(300.0, 400.0));
        let canvas = std::cell::RefCell::new(Canvas::new(300, 400).unwrap());
        let bounds = Rect::new(0.0, 0.0, 300.0, 400.0);
        let ctx = Context::new(&view, &canvas, bounds);

        let handled = history.handle_scroll(&ctx, Point::new(0.0, -5.0), Point::zero());

        assert!(!handled);
        assert_eq!(*history.scroll_offset.read().unwrap(), 0.0);
    }

    #[test]
    fn streaming_append_grows_the_last_messages_response_in_place() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.start_streaming_message(ChatSender::Assistant);
        history.append_response("Hello");
        history.append_response(", world!");

        let messages = history.messages.read().unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].sender, ChatSender::Assistant);
        assert_eq!(messages[0].response, "Hello, world!");
        assert!(messages[0].thinking.is_empty());
    }

    #[test]
    fn streaming_append_thinking_and_response_target_separate_fields() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.start_streaming_message(ChatSender::Assistant);
        history.append_thinking("reasoning here");
        history.append_response("the answer");

        let messages = history.messages.read().unwrap();
        assert_eq!(messages[0].thinking, "reasoning here");
        assert_eq!(messages[0].response, "the answer");
    }

    #[test]
    fn append_before_any_streaming_message_started_is_a_harmless_noop() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.append_response("should go nowhere");
        assert!(history.messages.read().unwrap().is_empty());
    }

    #[test]
    fn a_message_with_thinking_text_lays_out_taller_than_one_with_only_a_response() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.push_message(ChatSender::Assistant, "just an answer");

        let view = View::new(Extent::new(300.0, 200.0));
        let canvas = std::cell::RefCell::new(Canvas::new(300, 200).unwrap());
        let bounds = Rect::new(0.0, 0.0, 300.0, 200.0);
        let ctx = Context::new(&view, &canvas, bounds);
        let (_, height_without_thinking) = history.layout_messages(&ctx);

        history.clear();
        history.start_streaming_message(ChatSender::Assistant);
        history.append_thinking("some reasoning about the problem");
        history.append_response("just an answer");
        let (messages, height_with_thinking) = history.layout_messages(&ctx);

        assert!(
            height_with_thinking > height_without_thinking,
            "a message with a thinking section should lay out taller"
        );
        assert!(!messages[0].thinking_lines.is_empty());
        assert!(!messages[0].response_lines.is_empty());
    }

    #[test]
    fn handle_scroll_clamps_into_a_valid_range_when_content_overflows() {
        let history = ChatHistory::new().width(200.0).height(80.0);
        for i in 0..20 {
            history.push_message(ChatSender::Assistant, format!("message number {i}"));
        }

        let view = View::new(Extent::new(200.0, 80.0));
        let canvas = std::cell::RefCell::new(Canvas::new(200, 80).unwrap());
        let bounds = Rect::new(0.0, 0.0, 200.0, 80.0);
        let ctx = Context::new(&view, &canvas, bounds);

        // Scroll far past the top -- should clamp to 0, not go negative.
        let handled = history.handle_scroll(&ctx, Point::new(0.0, 1000.0), Point::zero());
        assert!(handled);
        assert_eq!(*history.scroll_offset.read().unwrap(), 0.0);

        // Scroll far past the bottom -- should clamp to the max valid
        // offset, not run away unbounded.
        let handled = history.handle_scroll(&ctx, Point::new(0.0, -100000.0), Point::zero());
        assert!(handled);
        let (_, total_height) = history.layout_messages(&ctx);
        assert_eq!(*history.scroll_offset.read().unwrap(), total_height - 80.0);
    }

    #[test]
    fn a_second_layout_call_with_unchanged_text_reuses_the_cached_wrapped_lines() {
        let history = ChatHistory::new().width(300.0).height(200.0);
        history.push_message(ChatSender::Assistant, "$\\frac{1}{2}$ and some more text");

        let view = View::new(Extent::new(300.0, 200.0));
        let canvas = std::cell::RefCell::new(Canvas::new(300, 200).unwrap());
        let bounds = Rect::new(0.0, 0.0, 300.0, 200.0);
        let ctx = Context::new(&view, &canvas, bounds);

        let (first, _) = history.layout_messages(&ctx);
        let (second, _) = history.layout_messages(&ctx);

        let first_math = first[0].response_lines.iter().find_map(|line| {
            line.runs.iter().find_map(|r| match r {
                LaidOutRun::Math { layout, .. } => Some(layout.clone()),
                LaidOutRun::Text(_) => None,
            })
        });
        let second_math = second[0].response_lines.iter().find_map(|line| {
            line.runs.iter().find_map(|r| match r {
                LaidOutRun::Math { layout, .. } => Some(layout.clone()),
                LaidOutRun::Text(_) => None,
            })
        });

        let (Some(first_math), Some(second_math)) = (first_math, second_math) else {
            panic!("expected a math run in the response");
        };
        assert!(
            std::sync::Arc::ptr_eq(&first_math, &second_math),
            "expected the second layout_messages call to reuse the cached MathBox, not recompute it"
        );
    }
}