gpui-box-kit 0.1.0

GPUI Box Kit design-system components and interaction primitives
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! A conversation, over the one virtualized list this library has.
//!
//! # The list does not own the conversation
//!
//! Messages, their order, their authors, and their delivery are all the
//! caller's. This component renders what it is handed and reports what was
//! asked for: a failed message stays exactly where it is, with its text
//! intact, and a retry is a request rather than a resend.
//!
//! # Times are strings the host already wrote
//!
//! The time on a message is an [`EntryTime`], the same type
//! [`Timeline`](crate::display::timeline::Timeline) takes, for the same reason: turning
//! an instant into words is calendar, time-zone and locale work, and whoever
//! owns the clock owns the wording. A message whose time nobody knows says so
//! rather than being floated to an end that would claim when it happened.
//!
//! # One message, one slot
//!
//! Virtualization here is [`List`], which is `uniform_list`, so every row is
//! the same height. That is the whole reason a conversation of ten thousand
//! messages costs the same as one of ten, and the price is that a message
//! occupies a slot rather than growing to fit: [`MessageList::body_lines`]
//! decides how tall the slot is, and a body longer than that says how many
//! lines it left out instead of being quietly cut off.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use gpui::{
    AnyElement, App, Global, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window,
    div, prelude::FluentBuilder, px,
};
use gpui_kit_semantics::{NodeSpec, Role, Semantic};
use gpui_kit_theme::{ActiveTheme, ControlSize, Radius, Space, Surface, Theme, TypeScale};
use web_time::Instant;

use crate::content::markdown::{Markdown, MarkdownEvent};
use crate::controls::button::Button;
use crate::data::list::{List, ListItem, scroll_to_row};
use crate::display::avatar::Avatar;
use crate::display::badge::Tone;
use crate::display::status::StatusDot;
use crate::display::timeline::EntryTime;
use crate::foundation::{Ident, Sizable, StyledExt};
use crate::motion::keyed;
use crate::strings::{ActiveStrings, StringKey, Strings};

/// What a host said about a message's journey.
///
/// Five states, five renderings. Collapsing sent, delivered, and read into one
/// tick tells the reader less than the host knows, and folding a failure into
/// any of them tells them something untrue.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum DeliveryState {
    /// Handed over, not yet acknowledged.
    Sending,
    /// The host accepted it.
    #[default]
    Sent,
    /// It reached the other side.
    Delivered,
    /// The other side opened it.
    Read,
    /// It did not arrive, and here is why, in the host's own words.
    Failed { reason: SharedString },
}

impl DeliveryState {
    /// The name a node publishes, so a test asserts the state rather than the
    /// colour it was drawn in.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Sending => "sending",
            Self::Sent => "sent",
            Self::Delivered => "delivered",
            Self::Read => "read",
            Self::Failed { .. } => "failed",
        }
    }

    fn label(&self, strings: &Strings) -> SharedString {
        match self {
            Self::Sending => strings.text(StringKey::MessageSending),
            Self::Sent => strings.text(StringKey::MessageSent),
            Self::Delivered => strings.text(StringKey::MessageDelivered),
            Self::Read => strings.text(StringKey::MessageRead),
            Self::Failed { reason } => reason.clone(),
        }
    }

    fn tone(&self) -> Tone {
        match self {
            Self::Sending => Tone::Neutral,
            Self::Sent => Tone::Info,
            Self::Delivered => Tone::Accent,
            Self::Read => Tone::Success,
            Self::Failed { .. } => Tone::Danger,
        }
    }

    pub fn failed(&self) -> bool {
        matches!(self, Self::Failed { .. })
    }
}

/// What a message says.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageBody {
    /// Shown exactly as it is, with no markup read into it.
    Text(SharedString),
    /// Rendered through [`Markdown`], with its rules about HTML, links, and
    /// images.
    Markdown(SharedString),
}

impl MessageBody {
    /// The text as the caller wrote it, markup and all.
    pub fn source(&self) -> &SharedString {
        match self {
            Self::Text(text) | Self::Markdown(text) => text,
        }
    }
}

impl From<&'static str> for MessageBody {
    fn from(value: &'static str) -> Self {
        Self::Text(SharedString::new_static(value))
    }
}

impl From<String> for MessageBody {
    fn from(value: String) -> Self {
        Self::Text(SharedString::from(value))
    }
}

/// Something carried alongside a message. The list names it and fetches
/// nothing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
    id: SharedString,
    name: SharedString,
    detail: Option<SharedString>,
}

impl Attachment {
    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            detail: None,
        }
    }

    /// A size, a kind, or whatever else the host already knows about it.
    pub fn detail(mut self, detail: impl Into<SharedString>) -> Self {
        self.detail = Some(detail.into());
        self
    }
}

/// A reaction and how many people left it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reaction {
    key: SharedString,
    label: SharedString,
    count: usize,
}

impl Reaction {
    pub fn new(key: impl Into<SharedString>, label: impl Into<SharedString>, count: usize) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            count,
        }
    }
}

/// One turn in a conversation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    id: SharedString,
    author: Option<SharedString>,
    time: EntryTime,
    body: MessageBody,
    delivery: DeliveryState,
    streaming: bool,
    attachments: Vec<Attachment>,
    reactions: Vec<Reaction>,
}

impl Message {
    /// `id` is the message's own identity, which every node it publishes is
    /// derived from, so an assertion survives the conversation growing above
    /// it.
    pub fn new(id: impl Into<SharedString>, body: impl Into<MessageBody>) -> Self {
        Self {
            id: id.into(),
            author: None,
            time: EntryTime::Unknown,
            body: body.into(),
            delivery: DeliveryState::default(),
            streaming: false,
            attachments: Vec::new(),
            reactions: Vec::new(),
        }
    }

    pub fn markdown(id: impl Into<SharedString>, source: impl Into<SharedString>) -> Self {
        Self::new(id, MessageBody::Markdown(source.into()))
    }

    pub fn author(mut self, author: impl Into<SharedString>) -> Self {
        self.author = Some(author.into());
        self
    }

    /// The time, in the words the host chose.
    pub fn time(mut self, time: impl Into<EntryTime>) -> Self {
        self.time = time.into();
        self
    }

    pub fn delivery(mut self, delivery: DeliveryState) -> Self {
        self.delivery = delivery;
        self
    }

    pub fn failed(self, reason: impl Into<SharedString>) -> Self {
        self.delivery(DeliveryState::Failed {
            reason: reason.into(),
        })
    }

    /// Marks the message as still arriving. The body keeps whatever has
    /// arrived so far.
    pub fn streaming(mut self, streaming: bool) -> Self {
        self.streaming = streaming;
        self
    }

    pub fn attachment(mut self, attachment: Attachment) -> Self {
        self.attachments.push(attachment);
        self
    }

    pub fn reaction(mut self, reaction: Reaction) -> Self {
        self.reactions.push(reaction);
        self
    }

    pub fn id(&self) -> &SharedString {
        &self.id
    }
}

type RetryHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
type MarkdownHandler = Rc<dyn Fn(SharedString, &MarkdownEvent, &mut Window, &mut App)>;

/// A conversation.
#[derive(IntoElement)]
pub struct MessageList {
    ident: Ident,
    messages: Vec<Message>,
    visible_rows: Option<usize>,
    body_lines: usize,
    group_consecutive: bool,
    on_retry: Option<RetryHandler>,
    on_markdown: Option<MarkdownHandler>,
}

impl std::fmt::Debug for MessageList {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("MessageList")
            .field("ident", &self.ident)
            .field("messages", &self.messages.len())
            .field("visible_rows", &self.visible_rows)
            .field("group_consecutive", &self.group_consecutive)
            .finish()
    }
}

impl MessageList {
    pub fn new(ident: impl Into<Ident>, messages: impl IntoIterator<Item = Message>) -> Self {
        Self {
            ident: ident.into(),
            messages: messages.into_iter().collect(),
            visible_rows: None,
            body_lines: 3,
            group_consecutive: false,
            on_retry: None,
            on_markdown: None,
        }
    }

    /// Bounds the viewport to `rows` messages, which is what lets the list
    /// skip the ones it does not show.
    pub fn visible_rows(mut self, rows: usize) -> Self {
        self.visible_rows = Some(rows);
        self
    }

    /// How many lines of body each message's slot holds.
    pub fn body_lines(mut self, lines: usize) -> Self {
        self.body_lines = lines.max(1);
        self
    }

    /// Whether consecutive messages from one author are drawn as one turn.
    ///
    /// Declared, not inferred, for the same reason
    /// [`Toolbar::overflow_after`](crate::layout::Toolbar::overflow_after) is:
    /// whether two messages a minute apart are one turn or two is a product
    /// judgement about the conversation, and this component knows nothing
    /// about the conversation.
    pub fn group_consecutive(mut self, group: bool) -> Self {
        self.group_consecutive = group;
        self
    }

    /// Reports that a failed message should be tried again. Nothing is resent
    /// and nothing is removed.
    pub fn on_retry(
        mut self,
        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_retry = Some(Rc::new(handler));
        self
    }

    /// Forwards what a Markdown body reported, stamped with the message it
    /// came from.
    pub fn on_markdown(
        mut self,
        handler: impl Fn(SharedString, &MarkdownEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_markdown = Some(Rc::new(handler));
        self
    }

    /// The height of one slot: a header line, `body_lines` of body, and a
    /// footer line, inside the row's own padding.
    fn row_height(&self, theme: &Theme) -> f32 {
        theme.space(Space::Sm) * 2.0
            + theme.typography.caption.line_height
            + theme.space(Space::Xs) * 2.0
            + theme.typography.body.line_height * self.body_lines as f32
            + theme.control.get(ControlSize::Sm).height
    }
}

impl RenderOnce for MessageList {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.theme().clone();
        let ident = self.ident.clone();
        let count = self.messages.len();
        let row_height = self.row_height(&theme);
        let body_lines = self.body_lines;
        let group = self.group_consecutive;
        let on_retry = self.on_retry.clone();
        let on_markdown = self.on_markdown.clone();

        let follow = self.follow(count, cx);
        if follow.stick {
            scroll_to_row(&ident, count.saturating_sub(1), cx);
        }
        let pending = self.pending(&follow, &theme, cx);

        let messages = Rc::new(self.messages);
        let seen = follow.cell.clone();
        let list_ident = ident.clone();
        let rows = List::new(ident.clone(), count, move |index, window, cx| {
            if let Some(highest) = seen.borrow_mut().current.as_mut() {
                *highest = (*highest).max(index);
            } else {
                seen.borrow_mut().current = Some(index);
            }
            let Some(message) = messages.get(index) else {
                return ListItem::new("unknown", div());
            };
            let continues = group
                && index > 0
                && messages
                    .get(index - 1)
                    .is_some_and(|previous| previous.author == message.author);
            ListItem::new(
                message.id.clone(),
                row(
                    &list_ident,
                    message,
                    continues,
                    body_lines,
                    on_retry.as_ref(),
                    on_markdown.as_ref(),
                    window,
                    cx,
                ),
            )
            .text(shown_author(message.author.as_ref()))
        })
        .row_height(row_height)
        .when_some(self.visible_rows, List::visible_rows);

        div()
            .column()
            .w_full()
            .relative()
            .child(rows)
            .children(pending)
    }
}

/// What the list knows about where the reader is and what has arrived.
#[derive(Debug, Default)]
struct Following {
    /// Whether this identity has rendered before. Nothing is "new" on the
    /// frame a conversation first appears.
    started: bool,
    /// How many messages there were last time.
    count: usize,
    /// The highest index rendered in the frame being built.
    current: Option<usize>,
    /// The highest index rendered in the previous frame, which is where the
    /// reader was.
    previous: Option<usize>,
    /// The highest index the reader has ever had on screen.
    ever: Option<usize>,
    /// How many messages arrived while the reader was somewhere else.
    arrived: usize,
}

/// What one frame decided about following.
struct Follow {
    cell: Rc<RefCell<Following>>,
    /// Whether this frame should bring the newest message into view.
    stick: bool,
    /// How many messages sit below the viewport that the reader has not seen.
    below: usize,
    /// How many of those arrived after the conversation was first drawn.
    arrived: usize,
}

impl std::fmt::Debug for Follow {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Follow")
            .field("stick", &self.stick)
            .field("below", &self.below)
            .field("arrived", &self.arrived)
            .finish()
    }
}

impl MessageList {
    /// Decides, once per frame, whether the newest message is followed.
    ///
    /// Following is conditional on purpose: dragging the reader back down
    /// while they are reading something further up takes the conversation away
    /// from them. When it does not follow it says how many messages it did not
    /// follow, which is the same rule
    /// [`ScrollArea`](crate::layout::ScrollArea) keeps — content continuing
    /// past the view is published rather than left to be noticed.
    fn follow(&self, count: usize, cx: &mut App) -> Follow {
        let cell = keyed::slot::<Following>(&self.ident.child("following").semantic_id(), cx);
        let mut following = cell.borrow_mut();
        following.previous = following.current.take();
        if let Some(previous) = following.previous {
            following.ever = Some(following.ever.map_or(previous, |ever| ever.max(previous)));
        }

        // Before the first frame has drawn a row, where the reader is has to
        // come from the viewport the caller asked for: a list opens at its
        // top.
        let reach = |highest: Option<usize>| match highest {
            Some(highest) => highest + 1,
            None => self.visible_rows.unwrap_or(count),
        };
        let at_bottom = reach(following.previous) >= following.count.max(1);

        let mut stick = false;
        if !following.started {
            following.started = true;
        } else if count > following.count {
            if at_bottom {
                stick = true;
            } else {
                following.arrived += count - following.count;
            }
        }
        following.count = count;

        let mut below = count.saturating_sub(reach(following.ever));
        if below == 0 {
            following.arrived = 0;
        }
        let arrived = following.arrived.min(below);
        // A frame that is following the newest message is not behind it, even
        // though the row it is scrolling to has not been drawn yet.
        if stick {
            below = 0;
        }
        drop(following);

        Follow {
            cell,
            stick,
            below,
            arrived,
        }
    }

    /// The affordance naming what is below the view, when anything is.
    fn pending(&self, follow: &Follow, theme: &Theme, cx: &mut App) -> Option<AnyElement> {
        if follow.below == 0 {
            return None;
        }
        // Messages that arrived while the reader was away are a different fact
        // from messages that have simply always been further down, so they are
        // worded differently rather than counted together.
        let counted = if follow.arrived > 0 {
            follow.arrived
        } else {
            follow.below
        };
        let strings = cx.strings();
        let label = match (follow.arrived, counted) {
            (0, 1) => strings.text(StringKey::MessageMoreOne),
            (0, more) => strings.format(StringKey::MessageMoreMany, &[&more.to_string()]),
            (_, 1) => strings.text(StringKey::MessageNewOne),
            (_, new) => strings.format(StringKey::MessageNewMany, &[&new.to_string()]),
        };
        let ident = self.ident.child("pending");
        let list = self.ident.clone();
        let last = self.messages.len().saturating_sub(1);
        let cell = follow.cell.clone();

        Some(
            div()
                .absolute()
                .bottom(px(theme.space(Space::Sm)))
                .right(px(theme.space(Space::Sm)))
                .child(
                    Button::new(ident.child("follow"))
                        .label(label.clone())
                        .secondary()
                        .control_size(ControlSize::Sm)
                        .on_click(move |window, cx| {
                            cell.borrow_mut().arrived = 0;
                            scroll_to_row(&list, last, cx);
                            window.refresh();
                        }),
                )
                .semantic_in(
                    cx,
                    NodeSpec::new(ident.semantic_id(), Role::Status)
                        .parent(self.ident.semantic_id())
                        .text(label)
                        .value(counted.to_string()),
                )
                .into_any_element(),
        )
    }
}

/// When the indicator for a streaming message started, keyed by message.
#[derive(Debug, Default)]
struct Streams(RefCell<HashMap<SharedString, Instant>>);

impl Global for Streams {}

/// When the streaming indicator on `message` in `list` began.
///
/// Keyed by the message's identity and nothing else, so text arriving into a
/// message that is already streaming does not restart the indicator: a
/// conversation whose "still writing" mark flickered on every token would be
/// reporting the token, not the stream. Answers `None` once the message stops
/// streaming.
pub fn streaming_since(list: &Ident, message: &str, cx: &App) -> Option<Instant> {
    cx.try_global::<Streams>()
        .and_then(|streams| streams.0.borrow().get(&stream_key(list, message)).copied())
}

fn stream_key(list: &Ident, message: &str) -> SharedString {
    list.child(message).child("streaming").semantic_id()
}

/// The instant this message's stream began, started on first sight.
fn stream_began(list: &Ident, message: &str, streaming: bool, cx: &mut App) -> Option<Instant> {
    if !cx.has_global::<Streams>() {
        cx.set_global(Streams::default());
    }
    let key = stream_key(list, message);
    let streams = cx.global::<Streams>();
    let mut clocks = streams.0.borrow_mut();
    if !streaming {
        clocks.remove(&key);
        return None;
    }
    let now = cx.background_executor().now();
    Some(*clocks.entry(key).or_insert(now))
}

fn shown_author(author: Option<&SharedString>) -> SharedString {
    // An author nobody named is named `unknown`, because a blank byline reads
    // as a message with no author rather than one whose author was not
    // recorded.
    match author {
        Some(author) if !author.trim().is_empty() => author.clone(),
        _ => SharedString::new_static("unknown"),
    }
}

#[allow(clippy::too_many_arguments)]
fn row(
    list: &Ident,
    message: &Message,
    continues: bool,
    body_lines: usize,
    on_retry: Option<&RetryHandler>,
    on_markdown: Option<&MarkdownHandler>,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    let theme = cx.theme().clone();
    let ident = list.child(message.id.as_ref());
    let author = shown_author(message.author.as_ref());
    let began = stream_began(list, message.id.as_ref(), message.streaming, cx);

    let header = div()
        .row()
        .w_full()
        .gap_token(&theme, Space::Sm)
        .type_scale(&theme, TypeScale::Caption)
        .h(px(theme.typography.caption.line_height))
        // A continued turn keeps the space its byline would occupy, because
        // the slot is one height and a hole where a name was is not a saving.
        .when(!continues, |element| {
            element
                .child(Avatar::new(author.clone()).size(theme.typography.caption.line_height))
                .child(
                    div()
                        .text_color(theme.colors.text)
                        .child(author.clone())
                        .semantic_in(
                            cx,
                            NodeSpec::new(ident.child("author").semantic_id(), Role::Text)
                                .parent(ident.semantic_id())
                                .text(author.clone()),
                        ),
                )
        })
        .child(
            div()
                .text_color(if message.time == EntryTime::Unknown {
                    theme.colors.warning
                } else {
                    theme.colors.text_faint
                })
                .child(message.time.shown(cx))
                .semantic_in(
                    cx,
                    NodeSpec::new(ident.child("time").semantic_id(), Role::Text)
                        .parent(ident.semantic_id())
                        .text(message.time.shown(cx))
                        .value(match &message.time {
                            EntryTime::At(time) => time.clone(),
                            EntryTime::Unknown => SharedString::new_static("time unknown"),
                        }),
                ),
        )
        .children(began.map(|_| streaming_mark(&ident, &theme, cx)));

    let body = body_element(&ident, message, body_lines, on_markdown, &theme, cx);

    let mut footer = div()
        .row()
        .w_full()
        .gap_token(&theme, Space::Sm)
        .h(px(theme.control.get(ControlSize::Sm).height))
        .child(delivery_mark(&ident, &message.delivery, &theme, cx));

    for attachment in &message.attachments {
        footer = footer.child(attachment_chip(&ident, attachment, &theme, cx));
    }
    for reaction in &message.reactions {
        footer = footer.child(reaction_chip(&ident, reaction, &theme, cx));
    }

    // A failed message keeps everything it had and gains one thing: a way to
    // ask for it to be tried again. It is never removed, and nothing here
    // retries it.
    if let (DeliveryState::Failed { .. }, Some(handler)) = (&message.delivery, on_retry) {
        let id = message.id.clone();
        let handler = Rc::clone(handler);
        footer = footer.child(
            Button::new(ident.child("retry"))
                .label(cx.strings().text(StringKey::TryAgain))
                .secondary()
                .control_size(ControlSize::Xs)
                .on_click(move |window, cx| handler(id.clone(), window, cx)),
        );
    }

    let _ = window;
    div()
        .column()
        .w_full()
        .gap_token(&theme, Space::Xs)
        .py_token(&theme, Space::Sm)
        .child(header)
        .child(body)
        .child(footer)
        .into_any_element()
}

fn body_element(
    ident: &Ident,
    message: &Message,
    body_lines: usize,
    on_markdown: Option<&MarkdownHandler>,
    theme: &Theme,
    cx: &mut App,
) -> AnyElement {
    let height = theme.typography.body.line_height * body_lines as f32;
    match &message.body {
        MessageBody::Markdown(source) => {
            let mut markdown =
                Markdown::new(ident.child("body"), source.clone()).max_lines(body_lines);
            if let Some(handler) = on_markdown {
                let handler = Rc::clone(handler);
                let id = message.id.clone();
                markdown = markdown
                    .on_event(move |event, window, cx| handler(id.clone(), event, window, cx));
            }
            div()
                .w_full()
                .h(px(height))
                .overflow_hidden()
                .child(markdown)
                .into_any_element()
        }
        MessageBody::Text(text) => {
            let lines: Vec<&str> = text.lines().collect();
            let hidden = lines.len().saturating_sub(body_lines);
            let shown = lines
                .iter()
                .take(body_lines)
                .copied()
                .collect::<Vec<_>>()
                .join("\n");
            div()
                .column()
                .w_full()
                .h(px(height))
                .overflow_hidden()
                .type_scale(theme, TypeScale::Body)
                .text_color(theme.colors.text)
                .child(SharedString::from(shown))
                .children((hidden > 0).then(|| {
                    let label = if hidden == 1 {
                        cx.strings().text(StringKey::MessageShowMoreOne)
                    } else {
                        cx.strings()
                            .format(StringKey::MessageShowMoreMany, &[&hidden.to_string()])
                    };
                    div()
                        .type_scale(theme, TypeScale::Caption)
                        .text_color(theme.colors.text_faint)
                        .child(label.clone())
                        .semantic_in(
                            cx,
                            NodeSpec::new(ident.child("truncated").semantic_id(), Role::Status)
                                .parent(ident.semantic_id())
                                .text(label)
                                .value(hidden.to_string()),
                        )
                }))
                .into_any_element()
        }
    }
}

fn streaming_mark(ident: &Ident, theme: &Theme, cx: &mut App) -> AnyElement {
    let label = cx.strings().text(StringKey::MessageStreaming);
    div()
        .row()
        .gap(px(4.0))
        .text_color(theme.colors.accent)
        // The mark already published `busy`; a still dot meant a reader
        // watching the screen had to take the word for it.
        .child(StatusDot::new(Tone::Accent).busy(ident.child("streaming.mark")))
        .child(label.clone())
        .semantic_in(
            cx,
            NodeSpec::new(ident.child("streaming").semantic_id(), Role::Status)
                .parent(ident.semantic_id())
                .text(label)
                .value("streaming")
                .busy(true),
        )
        .into_any_element()
}

fn delivery_mark(ident: &Ident, state: &DeliveryState, theme: &Theme, cx: &mut App) -> AnyElement {
    let label = state.label(cx.strings());
    let tone = state.tone();
    div()
        .row()
        .gap(px(4.0))
        .min_w_0()
        .type_scale(theme, TypeScale::Caption)
        .text_color(tone.color(theme))
        .child(StatusDot::new(tone))
        .child(div().min_w_0().child(label.clone()))
        .semantic_in(
            cx,
            NodeSpec::new(ident.child("delivery").semantic_id(), Role::Status)
                .parent(ident.semantic_id())
                .text(label)
                .value(state.name())
                .invalid(state.failed())
                .busy(matches!(state, DeliveryState::Sending)),
        )
        .into_any_element()
}

fn attachment_chip(
    ident: &Ident,
    attachment: &Attachment,
    theme: &Theme,
    cx: &mut App,
) -> AnyElement {
    let text = match &attachment.detail {
        Some(detail) => SharedString::from(format!("{}{detail}", attachment.name)),
        None => attachment.name.clone(),
    };
    div()
        .px_token(theme, Space::Xs)
        .radius(theme, Radius::Small)
        .surface(theme, Surface::Raised)
        .type_scale(theme, TypeScale::Caption)
        .text_color(theme.colors.text_muted)
        .child(text.clone())
        .semantic_in(
            cx,
            NodeSpec::new(
                ident
                    .child("attachment")
                    .child(attachment.id.as_ref())
                    .semantic_id(),
                Role::Text,
            )
            .parent(ident.semantic_id())
            .text(text),
        )
        .into_any_element()
}

fn reaction_chip(ident: &Ident, reaction: &Reaction, theme: &Theme, cx: &mut App) -> AnyElement {
    let text = SharedString::from(format!("{} {}", reaction.label, reaction.count));
    div()
        .px_token(theme, Space::Xs)
        .radius(theme, Radius::Pill)
        .bg(theme.colors.raised)
        .type_scale(theme, TypeScale::Caption)
        .text_color(theme.colors.text_muted)
        .child(text.clone())
        .semantic_in(
            cx,
            NodeSpec::new(
                ident
                    .child("reaction")
                    .child(reaction.key.as_ref())
                    .semantic_id(),
                Role::Status,
            )
            .parent(ident.semantic_id())
            .text(text)
            .value(reaction.count.to_string()),
        )
        .into_any_element()
}

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

    #[test]
    fn every_delivery_state_has_its_own_name() {
        let states = [
            DeliveryState::Sending,
            DeliveryState::Sent,
            DeliveryState::Delivered,
            DeliveryState::Read,
            DeliveryState::Failed {
                reason: "The host refused it.".into(),
            },
        ];
        let mut names: Vec<&str> = states.iter().map(DeliveryState::name).collect();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), states.len());
    }

    #[test]
    fn a_failure_states_the_hosts_reason_rather_than_a_word_of_its_own() {
        let state = DeliveryState::Failed {
            reason: "The workspace is read only.".into(),
        };
        // A host's own reason is passed through untouched, so it needs no
        // catalogue to read it back.
        // A host's own reason is passed through untouched, so an empty
        // catalogue is enough to read it back.
        assert_eq!(
            state.label(&Strings::new()).as_ref(),
            "The workspace is read only."
        );
        assert!(state.failed());
    }

    #[test]
    fn an_unnamed_author_is_named_unknown() {
        assert_eq!(shown_author(None).as_ref(), "unknown");
        assert_eq!(shown_author(Some(&"  ".into())).as_ref(), "unknown");
        assert_eq!(shown_author(Some(&"Ada".into())).as_ref(), "Ada");
    }
}