Skip to main content

chat/
chat.rs

1//! A chat window: messages in a growing list, newest at the bottom, and a text box. While the
2//! user is at the end, the list follows new messages; once they scroll back, it stays put,
3//! shows how many new ones arrived, and jumps to the end on a press. Enter sends, Shift+Enter
4//! starts a new line. A simulated friend replies to each message a moment later.
5//!   cargo run -p taut --example chat
6#![windows_subsystem = "windows"]
7use std::time::{Duration, Instant};
8use taut::{Align, Flow, Key, Length, Mods, Ui, Window};
9
10/// What the friend says, in turn.
11const ANSWERS: [&str; 5] = [
12    "Hello! Good to hear from you.",
13    "I was just about to write to you, in fact. How did the move go in the end, and is the new place as quiet as you hoped?",
14    "Ha, that sounds about right.",
15    "Shall we meet on Saturday?",
16    "Good. See you then!",
17];
18/// How long the friend takes to answer.
19const THINKING: Duration = Duration::from_millis(1200);
20
21/// One message, and who sent it.
22pub struct Message {
23    mine: bool,
24    text: String,
25}
26
27/// Everything the chat keeps.
28#[derive(Default)]
29pub struct Chat {
30    messages: Vec<Message>,
31    typed: String,
32    /// The list showed its end as it was last described; how many messages came since it
33    /// did not; and whether it is to go back to its end.
34    at_end: bool,
35    unread: usize,
36    to_end: bool,
37    /// What time it is, and when the friend will have an answer ready.
38    now: Duration,
39    answer_at: Option<Duration>,
40    answered: usize,
41}
42
43impl Chat {
44    fn add(&mut self, mine: bool, text: String) {
45        self.messages.push(Message { mine, text });
46        self.unread += !self.at_end as usize;
47    }
48}
49
50pub fn describe(app: &mut Chat, ui: &mut Ui) {
51    let t = ui.theme;
52    // The friend's answer, once it is ready; until then, the interface is woken for it.
53    match app.answer_at {
54        Some(at) if at <= app.now => {
55            app.add(false, ANSWERS[app.answered % ANSWERS.len()].into());
56            (app.answer_at, app.answered) = (None, app.answered + 1);
57        }
58        Some(at) => ui.wake_after(at - app.now),
59        None => {}
60    }
61
62    // The list, and what lies over it (the friend writing, the way back to the newest).
63    ui.column().grow().open();
64    ui.el().grow().flow(Flow::Stack).open();
65    // (A few stand at the bottom, as the newest always does.)
66    let list = ui.column().key("list").grow().scroll().align(Align::End, Align::Spread).open();
67    ui.stick_to_bottom(&list);
68    if std::mem::take(&mut app.to_end) {
69        ui.scroll_to(&list, [f32::NAN, f32::INFINITY]);
70    }
71    // Each message as high as its text comes out: only the ones in view are described.
72    let wide = ui.size().w;
73    for at in ui.variable_rows(app.messages.len(), 40.0) {
74        bubble(&app.messages[at], wide, ui);
75    }
76    ui.close();
77    ui.close();
78    app.at_end = ui.scroll_state(&list).at_end();
79    app.unread = if app.at_end { 0 } else { app.unread };
80    if app.messages.is_empty() {
81        ui.row().place(Align::Center).open();
82        ui.text("No messages yet. Say hello!", t.font, t.text_faint);
83        ui.close();
84    }
85    if app.answer_at.is_some() {
86        ui.row().place((Align::Start, Align::End)).pad((14.0, 4.0)).open();
87        ui.note("Sam is writing\u{2026}");
88        ui.close();
89    }
90    if !app.at_end {
91        ui.row().place((Align::Center, Align::End)).pad(6.0).gap(8.0).fill(t.raised).radius(t.radius).align(Align::Center, Align::Center).open();
92        if app.unread > 0 {
93            ui.note(&format!("{} new", app.unread));
94        }
95        app.to_end |= ui.button("Back to the newest").clicked;
96        ui.close();
97    }
98    ui.close();
99
100    // The box to type in: Enter sends what is in it, as the button does; Shift and Enter
101    // start a new line.
102    ui.row().pad(10.0).gap(8.0).fill(t.panel).open();
103    ui.enter_submits();
104    let typing = ui.text_area(&mut app.typed, "Write a message", (1, 4));
105    let send = ui.primary_button("Send").clicked || typing.focused && ui.key(Key::Enter, Mods::NONE);
106    ui.close();
107    ui.close();
108    if send && !app.typed.trim().is_empty() {
109        let text = std::mem::take(&mut app.typed);
110        app.add(true, text.trim().into());
111        // (What one sends, one sees.)
112        (app.to_end, app.answer_at) = (true, Some(app.now + THINKING));
113    }
114}
115
116/// One message, a row of the list: the person's own on the right in the colour that stands
117/// out, the friend's on the left; as wide as its text, up to three quarters of the window.
118fn bubble(message: &Message, wide: f32, ui: &mut Ui) {
119    let t = ui.theme;
120    let (side, fill, ink) = if message.mine { (Align::End, t.accent, t.on_accent) } else { (Align::Start, t.raised, t.text) };
121    ui.row().w(Length::Grow(1.0)).pad((12.0, 3.0)).align(side, Align::Start).open();
122    ui.column().max((wide * 0.75).max(120.0), f32::INFINITY).pad((10.0, 6.0)).fill(fill).radius(10.0).open();
123    ui.el().text(&message.text, t.font, ink).wrap().show();
124    ui.close();
125    ui.close();
126}
127
128fn main() {
129    let (mut app, started) = (Chat::default(), Instant::now());
130    let window = Window { title: "Chat", width: 420.0, height: 560.0, min_width: 280.0, min_height: 240.0, ..Default::default() };
131    taut::run(window, move |ui| {
132        app.now = started.elapsed();
133        describe(&mut app, ui);
134    });
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use taut::Role;
141    use taut::testing::Trial;
142
143    fn send(trial: &mut Trial<Chat>, text: &str) {
144        trial.fill("Write a message", text);
145        trial.key("Enter");
146    }
147
148    #[test]
149    fn the_list_stays_at_its_end_while_the_person_is_there() {
150        let mut trial = Trial::new(Chat::default(), describe);
151        trial.set_time(|chat, now| chat.now = now);
152        trial.resize(360.0, 400.0, 1.0);
153        assert!(trial.has(Role::Text, "No messages yet. Say hello!"));
154
155        // A message is sent with Enter; Shift and Enter start a new line in it first. The
156        // friend writes, and answers a moment later.
157        trial.fill("Write a message", "Hi Sam!");
158        trial.key("Shift+Enter");
159        trial.type_text("How are you?");
160        trial.key("Enter");
161        assert!(trial.has(Role::Text, "Hi Sam!\nHow are you?") && trial.has(Role::Text, "Sam is writing\u{2026}"));
162        assert_eq!(trial.find(Role::TextBox, "Write a message").value, "", "the box is empty at once");
163        trial.wait(Duration::from_secs(2));
164        assert!(trial.has(Role::Text, ANSWERS[0]) && !trial.has(Role::Text, "Sam is writing\u{2026}"));
165        trial.looks_like("tests/looks/chat.png");
166
167        // More than fit: the newest are in view, at the bottom, the first are gone off the top.
168        for number in 1..=12 {
169            send(&mut trial, &format!("Message {number}"));
170        }
171        let (last, typing) = (trial.find(Role::Text, "Message 12").rect, trial.find(Role::TextBox, "Write a message").rect);
172        assert!(last.bottom() <= typing.y && last.bottom() > typing.y - 60.0, "the newest is just over the box to type in: {last:?}");
173        assert!(!trial.has(Role::Text, "Hi Sam!\nHow are you?"));
174        trial.wait(Duration::from_secs(2));
175        assert!(trial.has(Role::Text, ANSWERS[1]), "and the answer that came is in view, at the end:\n{}", trial.dump());
176
177        // Back to read what came before: the list stays there as more comes, and says so.
178        let middle = trial.center_of(Role::Text, "Message 12");
179        trial.wheel(middle, 0.0, -10_000.0);
180        assert!(trial.has(Role::Text, "Hi Sam!\nHow are you?") && trial.has(Role::Button, "Back to the newest"));
181        trial.app.answer_at = Some(trial.app.now + THINKING); // (as if the friend wrote first)
182        trial.run();
183        trial.wait(Duration::from_secs(2));
184        assert!(trial.has(Role::Text, "Hi Sam!\nHow are you?") && trial.has(Role::Text, "1 new"));
185
186        // And back to the end at a press, or by sending.
187        trial.press(Role::Button, "Back to the newest");
188        assert!(trial.has(Role::Text, ANSWERS[2]) && !trial.has(Role::Text, "Hi Sam!\nHow are you?"));
189        assert!(!trial.has(Role::Button, "Back to the newest"));
190        let middle = trial.center_of(Role::Text, ANSWERS[2]);
191        trial.wheel(middle, 0.0, -10_000.0);
192        send(&mut trial, "Bye!");
193        assert!(trial.has(Role::Text, "Bye!") && trial.app.at_end);
194    }
195}