feat(app): loading states while a chat syncs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -60,7 +60,7 @@ It signs you in through a real Teams web page and lets that page make the API ca
60
60
61
61
| Step | What happens |
62
62
|---|---|
63
| Start | The UI renders from the SQLite cache right away |
63
| Start | The UI renders from the SQLite cache right away. A chat still syncing shows a progress line in its header and skeleton bubbles |
64
64
| Sync | `core` fetches chats and channels from Graph with delta queries, pins and folders from the chat service |
65
65
| Live | `chatsvc` keeps the Trouter WebSocket open. An event only says "something changed", the content is then fetched fresh |
66
66
| Write | Sends, edits and reactions go out through Graph or the chat service, then the cache updates |
@@ -60,7 +60,7 @@ It signs you in through a real Teams web page and lets that page make the API ca60
60
61
| Step | What happens |61
| Step | What happens |62
|---|---|62
|---|---|63
| Start | The UI renders from the SQLite cache right away |63
| Start | The UI renders from the SQLite cache right away. A chat still syncing shows a progress line in its header and skeleton bubbles |64
| Sync | `core` fetches chats and channels from Graph with delta queries, pins and folders from the chat service |64
| Sync | `core` fetches chats and channels from Graph with delta queries, pins and folders from the chat service |65
| Live | `chatsvc` keeps the Trouter WebSocket open. An event only says "something changed", the content is then fetched fresh |65
| Live | `chatsvc` keeps the Trouter WebSocket open. An event only says "something changed", the content is then fetched fresh |66
| Write | Sends, edits and reactions go out through Graph or the chat service, then the cache updates |66
| Write | Sends, edits and reactions go out through Graph or the chat service, then the cache updates |@@ -40,6 +40,7 @@ pub enum AppEvent {
40
40
pub struct Mode {
41
41
pub demo: bool,
42
42
pub read_only: bool,
43
pub demo_sync: Option<std::time::Duration>,
43
44
}
44
45
45
46
pub struct AppState {
@@ -40,6 +40,7 @@ pub enum AppEvent {40
pub struct Mode {40
pub struct Mode {41
pub demo: bool,41
pub demo: bool,42
pub read_only: bool,42
pub read_only: bool,43
pub demo_sync: Option<std::time::Duration>,43
}44
}44
45
45
pub struct AppState {46
pub struct AppState {@@ -23,6 +23,7 @@ mod views;
23
23
24
24
use std::path::PathBuf;
25
25
use std::sync::Arc;
26
use std::time::Duration;
26
27
27
28
use directories::ProjectDirs;
28
29
use gpui_kit::component::TitleBar;
@@ -52,6 +53,7 @@ struct Arguments {
52
53
composer_text: Option<String>,
53
54
reply_to_last: bool,
54
55
channels_tab: bool,
56
demo_sync: Option<Duration>,
55
57
}
56
58
57
59
fn parse_arguments() -> Arguments {
@@ -68,6 +70,12 @@ fn parse_arguments() -> Arguments {
68
70
"--type" => arguments.composer_text = input.next(),
69
71
"--reply-last" => arguments.reply_to_last = true,
70
72
"--channels-tab" => arguments.channels_tab = true,
73
"--demo-sync" => {
74
arguments.demo_sync = input
75
.next()
76
.and_then(|value| value.parse().ok())
77
.map(Duration::from_secs_f32)
78
}
71
79
"--database" => arguments.database = input.next().map(PathBuf::from),
72
80
"--endpoint" => arguments.endpoint = input.next(),
73
81
"--open" => {
@@ -112,6 +120,7 @@ fn main() {
112
120
let mode = Mode {
113
121
demo: arguments.demo,
114
122
read_only: arguments.read_only,
123
demo_sync: arguments.demo_sync,
115
124
};
116
125
let store = if arguments.demo {
117
126
let store = Store::open_in_memory().expect("in-memory store");
@@ -23,6 +23,7 @@ mod views;23
23
24
use std::path::PathBuf;24
use std::path::PathBuf;25
use std::sync::Arc;25
use std::sync::Arc;26
use std::time::Duration;26
27
27
use directories::ProjectDirs;28
use directories::ProjectDirs;28
use gpui_kit::component::TitleBar;29
use gpui_kit::component::TitleBar;@@ -52,6 +53,7 @@ struct Arguments {52
composer_text: Option<String>,53
composer_text: Option<String>,53
reply_to_last: bool,54
reply_to_last: bool,54
channels_tab: bool,55
channels_tab: bool,56
demo_sync: Option<Duration>,55
}57
}56
58
57
fn parse_arguments() -> Arguments {59
fn parse_arguments() -> Arguments {@@ -68,6 +70,12 @@ fn parse_arguments() -> Arguments {68
"--type" => arguments.composer_text = input.next(),70
"--type" => arguments.composer_text = input.next(),69
"--reply-last" => arguments.reply_to_last = true,71
"--reply-last" => arguments.reply_to_last = true,70
"--channels-tab" => arguments.channels_tab = true,72
"--channels-tab" => arguments.channels_tab = true,73
"--demo-sync" => {74
arguments.demo_sync = input75
.next()76
.and_then(|value| value.parse().ok())77
.map(Duration::from_secs_f32)78
}71
"--database" => arguments.database = input.next().map(PathBuf::from),79
"--database" => arguments.database = input.next().map(PathBuf::from),72
"--endpoint" => arguments.endpoint = input.next(),80
"--endpoint" => arguments.endpoint = input.next(),73
"--open" => {81
"--open" => {@@ -112,6 +120,7 @@ fn main() {112
let mode = Mode {120
let mode = Mode {113
demo: arguments.demo,121
demo: arguments.demo,114
read_only: arguments.read_only,122
read_only: arguments.read_only,123
demo_sync: arguments.demo_sync,115
};124
};116
let store = if arguments.demo {125
let store = if arguments.demo {117
let store = Store::open_in_memory().expect("in-memory store");126
let store = Store::open_in_memory().expect("in-memory store");@@ -72,6 +72,15 @@ pub fn bubble_corners(own: bool, series: Series) -> Corners {
72
72
}
73
73
}
74
74
75
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
76
pub enum Receipt {
77
#[default]
78
Hidden,
79
Pending,
80
Sent,
81
Read,
82
}
83
75
84
#[derive(Debug, Clone, PartialEq, Eq)]
76
85
pub enum Delivery {
77
86
Delivered,
@@ -103,7 +112,7 @@ pub struct MessageRow {
103
112
pub is_reply: bool,
104
113
pub delivery: Delivery,
105
114
pub own: bool,
106
pub read: bool,
115
pub receipt: Receipt,
107
116
}
108
117
109
118
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -118,9 +127,63 @@ pub const START_KEY: &str = "conversation-start";
118
127
pub enum Row {
119
128
LoadOlder,
120
129
Start(StartInfo),
130
Skeleton(Skeleton),
121
131
Message(Box<MessageRow>),
122
132
}
123
133
134
#[derive(Debug, Clone, Copy, PartialEq)]
135
pub struct Skeleton {
136
pub key: &'static str,
137
pub own: bool,
138
pub width_ratio: f32,
139
pub lines: u8,
140
}
141
142
const SKELETON_TRAILING: Skeleton = Skeleton {
143
key: "skeleton-trailing",
144
own: false,
145
width_ratio: 0.32,
146
lines: 1,
147
};
148
149
const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
150
Skeleton {
151
key: "skeleton-0",
152
own: false,
153
width_ratio: 0.42,
154
lines: 1,
155
},
156
Skeleton {
157
key: "skeleton-1",
158
own: true,
159
width_ratio: 0.3,
160
lines: 1,
161
},
162
Skeleton {
163
key: "skeleton-2",
164
own: true,
165
width_ratio: 0.48,
166
lines: 2,
167
},
168
Skeleton {
169
key: "skeleton-3",
170
own: false,
171
width_ratio: 0.26,
172
lines: 1,
173
},
174
];
175
176
pub fn placeholder_rows() -> Vec<Row> {
177
SKELETON_PLACEHOLDERS
178
.into_iter()
179
.map(Row::Skeleton)
180
.collect()
181
}
182
183
pub fn trailing_skeleton() -> Row {
184
Row::Skeleton(SKELETON_TRAILING)
185
}
186
124
187
fn sender_key(row: &MessageRow) -> &str {
125
188
row.sender_id.as_deref().unwrap_or(&row.author)
126
189
}
@@ -165,6 +228,7 @@ impl Row {
165
228
match self {
166
229
Row::LoadOlder => LOAD_OLDER_KEY,
167
230
Row::Start(_) => START_KEY,
231
Row::Skeleton(skeleton) => skeleton.key,
168
232
Row::Message(message) => &message.key,
169
233
}
170
234
}
@@ -293,7 +357,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
293
357
open_thread: None,
294
358
is_reply: record.reply_to_id.is_some(),
295
359
delivery: Delivery::Delivered,
296
read: false,
360
receipt: Receipt::Hidden,
297
361
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
298
362
}
299
363
}
@@ -543,7 +607,7 @@ mod tests {
543
607
.iter()
544
608
.map(|row| match row {
545
609
Row::Message(message) => message.day_header.clone(),
546
Row::LoadOlder | Row::Start(_) => None,
610
Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
547
611
})
548
612
.collect();
549
613
assert_eq!(
@@ -635,7 +699,7 @@ mod tests {
635
699
rows.iter()
636
700
.filter_map(|row| match row {
637
701
Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
638
Row::LoadOlder | Row::Start(_) => None,
702
Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
639
703
})
640
704
.collect()
641
705
}
@@ -72,6 +72,15 @@ pub fn bubble_corners(own: bool, series: Series) -> Corners {72
}72
}73
}73
}74
74
75
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]76
pub enum Receipt {77
#[default]78
Hidden,79
Pending,80
Sent,81
Read,82
}83
75
#[derive(Debug, Clone, PartialEq, Eq)]84
#[derive(Debug, Clone, PartialEq, Eq)]76
pub enum Delivery {85
pub enum Delivery {77
Delivered,86
Delivered,@@ -103,7 +112,7 @@ pub struct MessageRow {103
pub is_reply: bool,112
pub is_reply: bool,104
pub delivery: Delivery,113
pub delivery: Delivery,105
pub own: bool,114
pub own: bool,106
pub read: bool,115
pub receipt: Receipt,107
}116
}108
117
109
#[derive(Debug, Clone, PartialEq, Eq)]118
#[derive(Debug, Clone, PartialEq, Eq)]@@ -118,9 +127,63 @@ pub const START_KEY: &str = "conversation-start";118
pub enum Row {127
pub enum Row {119
LoadOlder,128
LoadOlder,120
Start(StartInfo),129
Start(StartInfo),130
Skeleton(Skeleton),121
Message(Box<MessageRow>),131
Message(Box<MessageRow>),122
}132
}123
133
134
#[derive(Debug, Clone, Copy, PartialEq)]135
pub struct Skeleton {136
pub key: &'static str,137
pub own: bool,138
pub width_ratio: f32,139
pub lines: u8,140
}141
142
const SKELETON_TRAILING: Skeleton = Skeleton {143
key: "skeleton-trailing",144
own: false,145
width_ratio: 0.32,146
lines: 1,147
};148
149
const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [150
Skeleton {151
key: "skeleton-0",152
own: false,153
width_ratio: 0.42,154
lines: 1,155
},156
Skeleton {157
key: "skeleton-1",158
own: true,159
width_ratio: 0.3,160
lines: 1,161
},162
Skeleton {163
key: "skeleton-2",164
own: true,165
width_ratio: 0.48,166
lines: 2,167
},168
Skeleton {169
key: "skeleton-3",170
own: false,171
width_ratio: 0.26,172
lines: 1,173
},174
];175
176
pub fn placeholder_rows() -> Vec<Row> {177
SKELETON_PLACEHOLDERS178
.into_iter()179
.map(Row::Skeleton)180
.collect()181
}182
183
pub fn trailing_skeleton() -> Row {184
Row::Skeleton(SKELETON_TRAILING)185
}186
124
fn sender_key(row: &MessageRow) -> &str {187
fn sender_key(row: &MessageRow) -> &str {125
row.sender_id.as_deref().unwrap_or(&row.author)188
row.sender_id.as_deref().unwrap_or(&row.author)126
}189
}@@ -165,6 +228,7 @@ impl Row {165
match self {228
match self {166
Row::LoadOlder => LOAD_OLDER_KEY,229
Row::LoadOlder => LOAD_OLDER_KEY,167
Row::Start(_) => START_KEY,230
Row::Start(_) => START_KEY,231
Row::Skeleton(skeleton) => skeleton.key,168
Row::Message(message) => &message.key,232
Row::Message(message) => &message.key,169
}233
}170
}234
}@@ -293,7 +357,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {293
open_thread: None,357
open_thread: None,294
is_reply: record.reply_to_id.is_some(),358
is_reply: record.reply_to_id.is_some(),295
delivery: Delivery::Delivered,359
delivery: Delivery::Delivered,296
read: false,360
receipt: Receipt::Hidden,297
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,361
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,298
}362
}299
}363
}@@ -543,7 +607,7 @@ mod tests {543
.iter()607
.iter()544
.map(|row| match row {608
.map(|row| match row {545
Row::Message(message) => message.day_header.clone(),609
Row::Message(message) => message.day_header.clone(),546
Row::LoadOlder | Row::Start(_) => None,610
Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,547
})611
})548
.collect();612
.collect();549
assert_eq!(613
assert_eq!(@@ -635,7 +699,7 @@ mod tests {635
rows.iter()699
rows.iter()636
.filter_map(|row| match row {700
.filter_map(|row| match row {637
Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),701
Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),638
Row::LoadOlder | Row::Start(_) => None,702
Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,639
})703
})640
.collect()704
.collect()641
}705
}@@ -1,9 +1,9 @@
1
1
use std::cell::RefCell;
2
2
use std::collections::HashMap;
3
3
use std::rc::Rc;
4
use std::time::Duration;
4
use std::time::{Duration, Instant};
5
5
6
use chrono::{Local, Offset, Utc};
6
use chrono::{DateTime, Local, Offset, Utc};
7
7
use gpui_kit::assets::IconName;
8
8
use gpui_kit::component::{
9
9
button::{Button, ButtonVariants as _},
@@ -18,15 +18,16 @@ use teams_core::ImageRef;
18
18
19
19
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
20
20
use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};
21
use super::message_row::{RowActions, render_message_row};
21
use super::message_row::{RowActions, render_message_row, render_skeleton_row};
22
22
use super::widgets::icon;
23
23
use crate::app_state::{AppEvent, AppState, Selection, selection_title};
24
24
use crate::data::{is_one_on_one, others};
25
25
use crate::render::Block;
26
26
use crate::render::blocks::Inline;
27
27
use crate::rows::{
28
Delivery, MessageRow, Row, RowContext, Series, StartInfo, assign_series, changed_indices,
29
diff_keys, flat_rows, reply_excerpt, thread_list_rows, thread_rows,
28
Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,
29
changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows,
30
thread_rows, trailing_skeleton,
30
31
};
31
32
use crate::runtime;
32
33
use crate::sidebar_model::{AvatarSpec, Face};
@@ -41,6 +42,12 @@ const MAX_NOTICE_CHARS: usize = 140;
41
42
const JUMP_SCAN_LIMIT: usize = 5000;
42
43
const JUMP_CONTEXT_MESSAGES: usize = 12;
43
44
const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
45
const PROGRESS_DELAY: Duration = Duration::from_millis(400);
46
const SKELETON_DELAY: Duration = Duration::from_millis(1000);
47
const SLOW_AFTER: Duration = Duration::from_secs(8);
48
const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
49
const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
50
const PROGRESS_BAR_WIDTH: f32 = 0.35;
44
51
45
52
actions!(teams, [ReplyToHovered]);
46
53
@@ -51,6 +58,24 @@ enum ViewMode {
51
58
Thread(String),
52
59
}
53
60
61
#[derive(Default)]
62
struct SyncProgress {
63
messages: bool,
64
receipts: bool,
65
empty_cache: bool,
66
newest_cached: Option<DateTime<Utc>>,
67
shown_at: Option<Instant>,
68
trailing_skeleton: bool,
69
slow: bool,
70
failed: bool,
71
}
72
73
impl SyncProgress {
74
fn running(&self) -> bool {
75
self.messages || self.receipts
76
}
77
}
78
54
79
struct Current {
55
80
selection: Selection,
56
81
title: String,
@@ -62,6 +87,7 @@ struct Current {
62
87
older_blocked: bool,
63
88
fetched: bool,
64
89
first_unread: Option<String>,
90
sync: SyncProgress,
65
91
}
66
92
67
93
pub struct ConversationView {
@@ -76,6 +102,7 @@ pub struct ConversationView {
76
102
hovered_message: Option<String>,
77
103
highlighted_message: Option<String>,
78
104
notice: Option<String>,
105
sync_generation: u64,
79
106
_subscriptions: Vec<Subscription>,
80
107
}
81
108
@@ -110,6 +137,7 @@ impl ConversationView {
110
137
hovered_message: None,
111
138
highlighted_message: None,
112
139
notice: None,
140
sync_generation: 0,
113
141
_subscriptions: subscriptions,
114
142
};
115
143
if let Some(selection) = view.app.read(cx).selection.clone() {
@@ -155,7 +183,14 @@ impl ConversationView {
155
183
}
156
184
AppEvent::Images(keys) => self.remeasure_images(keys, cx),
157
185
AppEvent::Jump => self.apply_pending_jump(cx),
158
AppEvent::Status => self.start_fetch(cx),
186
AppEvent::Status => {
187
if let Some(current) = self.current.as_mut()
188
&& current.sync.failed
189
{
190
current.fetched = false;
191
}
192
self.start_fetch(cx)
193
}
159
194
AppEvent::Directory => cx.notify(),
160
195
AppEvent::Sidebar => {
161
196
if let Some(current) = self.current.as_mut() {
@@ -202,7 +237,9 @@ impl ConversationView {
202
237
older_blocked: false,
203
238
fetched: false,
204
239
first_unread,
240
sync: SyncProgress::default(),
205
241
});
242
self.sync_generation += 1;
206
243
self.pending.clear();
207
244
self.notice = None;
208
245
self.rebuild(true, cx);
@@ -465,7 +502,15 @@ impl ConversationView {
465
502
current.loaded_limit = limit;
466
503
current.loaded_count = records.len();
467
504
let has_older = sync_has_more && !current.older_blocked && can_load_older;
505
let placeholders = current.sync.messages
506
&& records.is_empty()
507
&& !matches!(current.mode, ViewMode::Thread(_));
508
let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat;
468
509
let mut rows = match ¤t.mode {
510
_ if placeholders => {
511
current.has_older = false;
512
placeholder_rows()
513
}
469
514
ViewMode::Flat => {
470
515
current.has_older = has_older;
471
516
let mut rows = flat_rows(&records, &context, has_older);
@@ -483,16 +528,21 @@ impl ConversationView {
483
528
thread_rows(&records, root_id, &context)
484
529
}
485
530
};
531
if trailing && !placeholders {
532
rows.push(trailing_skeleton());
533
}
486
534
rows.extend(
487
535
self.pending
488
536
.iter()
489
537
.cloned()
490
538
.map(|row| Row::Message(Box::new(row))),
491
539
);
492
let read_ids = self.read_message_ids(&records, cx);
540
let receipts = self.receipts(&records, cx);
493
541
for row in rows.iter_mut() {
494
if let Row::Message(message) = row {
495
message.read = read_ids.contains(&message.key);
542
if let Row::Message(message) = row
543
&& message.own
544
{
545
message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
496
546
}
497
547
}
498
548
if let Some(unread_id) = &first_unread {
@@ -553,9 +603,11 @@ impl ConversationView {
553
603
}
554
604
555
605
fn start_fetch(&mut self, cx: &mut Context<Self>) {
556
let Some(engine) = self.app.read(cx).engine.clone() else {
606
let state = self.app.read(cx);
607
let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
608
if engine.is_none() && demo_sync.is_none() {
557
609
return;
558
};
610
}
559
611
let Some(current) = self.current.as_mut() else {
560
612
return;
561
613
};
@@ -563,47 +615,249 @@ impl ConversationView {
563
615
return;
564
616
}
565
617
current.fetched = true;
618
let is_chat = matches!(current.selection, Selection::Chat(_));
619
let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
620
Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
621
Some(message.created_at)
622
}
623
_ => None,
624
});
625
let current = self.current.as_mut().expect("checked above");
626
if current.sync.failed {
627
self.notice = None;
628
}
629
current.sync = SyncProgress {
630
messages: true,
631
receipts: is_chat,
632
empty_cache: newest_cached.is_none(),
633
newest_cached,
634
..SyncProgress::default()
635
};
636
self.sync_generation += 1;
637
let generation = self.sync_generation;
566
638
let conversation_id = current.selection.conversation_id().to_owned();
567
let receiver = runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
568
cx.spawn(async move |this, cx| {
569
if let Ok(Err(error)) = receiver.await {
570
this.update(cx, |this, cx| {
571
this.notice = Some(format!("Could not refresh: {}", short_error(&error)));
572
cx.notify();
639
match (engine, demo_sync) {
640
(Some(engine), _) => {
641
let receiver =
642
runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
643
cx.spawn(async move |this, cx| {
644
let result = receiver.await;
645
this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
646
.ok();
573
647
})
574
.ok();
648
.detach();
575
649
}
650
(None, Some(delay)) => self.simulate_sync(generation, delay, cx),
651
(None, None) => {}
652
}
653
self.schedule_progress(generation, cx);
654
self.rebuild(false, cx);
655
self.mark_read(cx);
656
self.refresh_receipts(generation, cx);
657
}
658
659
fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
660
cx.spawn(async move |this, cx| {
661
cx.background_executor().timer(delay).await;
662
this.update(cx, |this, cx| {
663
if let Some(sync) = this.sync_of(generation) {
664
sync.receipts = false;
665
}
666
this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
667
})
668
.ok();
576
669
})
577
670
.detach();
578
self.mark_read(cx);
579
self.refresh_receipts(cx);
580
671
}
581
672
582
fn read_message_ids(
583
&self,
584
records: &[MessageRecord],
585
cx: &App,
586
) -> std::collections::HashSet<String> {
673
fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
674
if generation != self.sync_generation {
675
return None;
676
}
677
self.current.as_mut().map(|current| &mut current.sync)
678
}
679
680
fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
681
cx.spawn(async move |this, cx| {
682
let stages = [
683
(PROGRESS_DELAY, Duration::ZERO),
684
(SKELETON_DELAY, PROGRESS_DELAY),
685
(SLOW_AFTER, SKELETON_DELAY),
686
];
687
for (stage, (at, previous)) in stages.into_iter().enumerate() {
688
cx.background_executor().timer(at - previous).await;
689
let running = this
690
.update(cx, |this, cx| this.advance_progress(generation, stage, cx))
691
.unwrap_or(false);
692
if !running {
693
return;
694
}
695
}
696
})
697
.detach();
698
}
699
700
fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
701
let Some(sync) = self.sync_of(generation) else {
702
return false;
703
};
704
if !sync.running() {
705
return false;
706
}
707
match stage {
708
0 => sync.shown_at = Some(Instant::now()),
709
1 if sync.messages => {
710
sync.trailing_skeleton = true;
711
self.rebuild(false, cx);
712
}
713
1 => {}
714
_ => sync.slow = true,
715
}
716
cx.notify();
717
true
718
}
719
720
fn finish_fetch(
721
&mut self,
722
generation: u64,
723
result: Result<
724
teams_core::Result<teams_core::Delta>,
725
tokio::sync::oneshot::error::RecvError,
726
>,
727
cx: &mut Context<Self>,
728
) {
729
let Some(sync) = self.sync_of(generation) else {
730
return;
731
};
732
sync.messages = false;
733
sync.trailing_skeleton = false;
734
let newest_cached = sync.newest_cached;
735
match result {
736
Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
737
Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
738
Err(error) => self.fail_sync(generation, short_error(&error)),
739
}
740
self.rebuild(false, cx);
741
self.settle_progress(generation, cx);
742
}
743
744
fn fail_sync(&mut self, generation: u64, error: String) {
745
if let Some(sync) = self.sync_of(generation) {
746
sync.failed = true;
747
sync.receipts = false;
748
}
749
self.notice = Some(format!("Could not refresh: {error}"));
750
}
751
752
fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
753
let Some(newest_cached) = newest_cached else {
754
return;
755
};
756
let Some(my_user_id) = self.row_context(cx).my_user_id else {
757
return;
758
};
759
let store = self.app.read(cx).store.clone();
760
let Some(current) = self.current.as_mut() else {
761
return;
762
};
763
if current.first_unread.is_some() || current.mode != ViewMode::Flat {
764
return;
765
}
766
let limit = current
767
.loaded_limit
768
.max(current.loaded_count + GROWTH_HEADROOM);
769
current.first_unread = store
770
.messages(current.selection.conversation_id(), None, limit)
771
.unwrap_or_default()
772
.into_iter()
773
.find(|record| {
774
record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
775
})
776
.map(|record| record.message_id);
777
}
778
779
fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
780
let Some(sync) = self.sync_of(generation) else {
781
return;
782
};
783
if sync.running() {
784
return;
785
}
786
let remaining = sync
787
.shown_at
788
.map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
789
.unwrap_or_default();
790
if remaining.is_zero() {
791
sync.shown_at = None;
792
sync.slow = false;
793
cx.notify();
794
return;
795
}
796
cx.spawn(async move |this, cx| {
797
cx.background_executor().timer(remaining).await;
798
this.update(cx, |this, cx| {
799
if let Some(sync) = this.sync_of(generation) {
800
sync.shown_at = None;
801
sync.slow = false;
802
cx.notify();
803
}
804
})
805
.ok();
806
})
807
.detach();
808
}
809
810
fn retry_fetch(&mut self, cx: &mut Context<Self>) {
811
if let Some(current) = self.current.as_mut() {
812
current.fetched = false;
813
}
814
self.start_fetch(cx);
815
}
816
817
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
587
818
let state = self.app.read(cx);
819
let receipts_syncing = self
820
.current
821
.as_ref()
822
.is_some_and(|current| current.sync.receipts);
588
823
if state.mode.demo {
589
return crate::demo::read_message_ids(records);
824
let read_ids = crate::demo::read_message_ids(records);
825
return records
826
.iter()
827
.map(|record| {
828
let receipt = if receipts_syncing {
829
Receipt::Pending
830
} else if read_ids.contains(&record.message_id) {
831
Receipt::Read
832
} else {
833
Receipt::Sent
834
};
835
(record.message_id.clone(), receipt)
836
})
837
.collect();
590
838
}
591
839
let Some(engine) = state.engine.as_ref() else {
592
return Default::default();
840
return HashMap::new();
841
};
842
let unknown = if receipts_syncing {
843
Receipt::Pending
844
} else {
845
Receipt::Hidden
593
846
};
594
847
records
595
848
.iter()
596
.filter(|record| {
597
matches!(
598
engine.receipt_state_for(record),
599
teams_core::ReceiptState::Read { .. }
600
)
849
.map(|record| {
850
let receipt = match engine.receipt_state_for(record) {
851
teams_core::ReceiptState::Read { .. } => Receipt::Read,
852
teams_core::ReceiptState::Sent => Receipt::Sent,
853
teams_core::ReceiptState::Unknown => unknown,
854
};
855
(record.message_id.clone(), receipt)
601
856
})
602
.map(|record| record.message_id.clone())
603
857
.collect()
604
858
}
605
859
606
fn refresh_receipts(&mut self, cx: &mut Context<Self>) {
860
fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
607
861
let state = self.app.read(cx);
608
862
let (Some(engine), Some(Selection::Chat(chat_id))) = (
609
863
state.engine.clone(),
@@ -611,9 +865,20 @@ impl ConversationView {
611
865
) else {
612
866
return;
613
867
};
614
drop(runtime::spawn(async move {
615
engine.refresh_receipts(&chat_id).await
616
}));
868
let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
869
cx.spawn(async move |this, cx| {
870
receiver.await.ok();
871
this.update(cx, |this, cx| {
872
let Some(sync) = this.sync_of(generation) else {
873
return;
874
};
875
sync.receipts = false;
876
this.rebuild(false, cx);
877
this.settle_progress(generation, cx);
878
})
879
.ok();
880
})
881
.detach();
617
882
}
618
883
619
884
fn mark_read(&mut self, cx: &mut Context<Self>) {
@@ -762,7 +1027,7 @@ impl ConversationView {
762
1027
open_thread: None,
763
1028
is_reply: false,
764
1029
delivery: Delivery::Sending,
765
read: false,
1030
receipt: Receipt::Hidden,
766
1031
own: true,
767
1032
});
768
1033
self.notice = None;
@@ -929,7 +1194,24 @@ impl ConversationView {
929
1194
if let Some(note) = channel_note {
930
1195
subline = note.to_owned();
931
1196
}
1197
let sync = ¤t.sync;
1198
if sync.failed {
1199
subline = "Not up to date".to_owned();
1200
} else if sync.shown_at.is_some() {
1201
subline = if sync.slow {
1202
"Taking longer than usual ..."
1203
} else if sync.empty_cache {
1204
"Loading messages ..."
1205
} else {
1206
"Updating ..."
1207
}
1208
.to_owned();
1209
}
932
1210
header
1211
.relative()
1212
.when(sync.shown_at.is_some(), |header| {
1213
header.child(progress_bar())
1214
})
933
1215
.children(lead)
934
1216
.child(
935
1217
v_flex()
@@ -1066,6 +1348,7 @@ impl Render for ConversationView {
1066
1348
cx,
1067
1349
)
1068
1350
}
1351
Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
1069
1352
Some(Row::LoadOlder) => {
1070
1353
let view = view.clone();
1071
1354
cx.defer(move |cx| {
@@ -1121,13 +1404,24 @@ impl Render for ConversationView {
1121
1404
root = root.child(self.render_header(current, cx));
1122
1405
if let Some(notice) = &self.notice {
1123
1406
root = root.child(
1124
div()
1407
h_flex()
1125
1408
.px_4()
1126
1409
.py_1()
1410
.gap(px(8.))
1411
.items_center()
1127
1412
.text_xs()
1128
1413
.bg(theme::amber().opacity(0.15))
1129
1414
.text_color(theme::amber())
1130
.child(notice.clone()),
1415
.child(div().flex_1().min_w_0().child(notice.clone()))
1416
.when(current.sync.failed, |bar| {
1417
bar.child(
1418
Button::new("retry-fetch")
1419
.ghost()
1420
.compact()
1421
.label("Retry")
1422
.on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
1423
)
1424
}),
1131
1425
);
1132
1426
}
1133
1427
let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();
@@ -1149,3 +1443,33 @@ impl Render for ConversationView {
1149
1443
.into_any_element()
1150
1444
}
1151
1445
}
1446
1447
fn progress_bar() -> impl IntoElement {
1448
div()
1449
.absolute()
1450
.left_0()
1451
.right_0()
1452
.bottom(px(-1.))
1453
.h(px(2.))
1454
.overflow_hidden()
1455
.bg(theme::border())
1456
.child(
1457
div()
1458
.absolute()
1459
.top_0()
1460
.h_full()
1461
.w(relative(PROGRESS_BAR_WIDTH))
1462
.bg(theme::own_read())
1463
.with_animation(
1464
"sync-progress",
1465
Animation::new(PROGRESS_BAR_PERIOD).repeat(),
1466
|bar, delta| {
1467
let travel = 1. + PROGRESS_BAR_WIDTH;
1468
// The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
1469
bar.left(relative(
1470
(delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
1471
))
1472
},
1473
),
1474
)
1475
}
@@ -1,9 +1,9 @@1
use std::cell::RefCell;1
use std::cell::RefCell;2
use std::collections::HashMap;2
use std::collections::HashMap;3
use std::rc::Rc;3
use std::rc::Rc;4
use std::time::Duration;4
use std::time::{Duration, Instant};5
5
6
use chrono::{Local, Offset, Utc};6
use chrono::{DateTime, Local, Offset, Utc};7
use gpui_kit::assets::IconName;7
use gpui_kit::assets::IconName;8
use gpui_kit::component::{8
use gpui_kit::component::{9
button::{Button, ButtonVariants as _},9
button::{Button, ButtonVariants as _},@@ -18,15 +18,16 @@ use teams_core::ImageRef;18
18
19
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};19
use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};20
use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};20
use super::composer::{Composer, ComposerEvent, Outgoing, ReplyPreview};21
use super::message_row::{RowActions, render_message_row};21
use super::message_row::{RowActions, render_message_row, render_skeleton_row};22
use super::widgets::icon;22
use super::widgets::icon;23
use crate::app_state::{AppEvent, AppState, Selection, selection_title};23
use crate::app_state::{AppEvent, AppState, Selection, selection_title};24
use crate::data::{is_one_on_one, others};24
use crate::data::{is_one_on_one, others};25
use crate::render::Block;25
use crate::render::Block;26
use crate::render::blocks::Inline;26
use crate::render::blocks::Inline;27
use crate::rows::{27
use crate::rows::{28
Delivery, MessageRow, Row, RowContext, Series, StartInfo, assign_series, changed_indices,28
Delivery, MessageRow, Receipt, Row, RowContext, Series, StartInfo, assign_series,29
diff_keys, flat_rows, reply_excerpt, thread_list_rows, thread_rows,29
changed_indices, diff_keys, flat_rows, placeholder_rows, reply_excerpt, thread_list_rows,30
thread_rows, trailing_skeleton,30
};31
};31
use crate::runtime;32
use crate::runtime;32
use crate::sidebar_model::{AvatarSpec, Face};33
use crate::sidebar_model::{AvatarSpec, Face};@@ -41,6 +42,12 @@ const MAX_NOTICE_CHARS: usize = 140;41
const JUMP_SCAN_LIMIT: usize = 5000;42
const JUMP_SCAN_LIMIT: usize = 5000;42
const JUMP_CONTEXT_MESSAGES: usize = 12;43
const JUMP_CONTEXT_MESSAGES: usize = 12;43
const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);44
const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);45
const PROGRESS_DELAY: Duration = Duration::from_millis(400);46
const SKELETON_DELAY: Duration = Duration::from_millis(1000);47
const SLOW_AFTER: Duration = Duration::from_secs(8);48
const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);49
const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);50
const PROGRESS_BAR_WIDTH: f32 = 0.35;44
51
45
actions!(teams, [ReplyToHovered]);52
actions!(teams, [ReplyToHovered]);46
53
@@ -51,6 +58,24 @@ enum ViewMode {51
Thread(String),58
Thread(String),52
}59
}53
60
61
#[derive(Default)]62
struct SyncProgress {63
messages: bool,64
receipts: bool,65
empty_cache: bool,66
newest_cached: Option<DateTime<Utc>>,67
shown_at: Option<Instant>,68
trailing_skeleton: bool,69
slow: bool,70
failed: bool,71
}72
73
impl SyncProgress {74
fn running(&self) -> bool {75
self.messages || self.receipts76
}77
}78
54
struct Current {79
struct Current {55
selection: Selection,80
selection: Selection,56
title: String,81
title: String,@@ -62,6 +87,7 @@ struct Current {62
older_blocked: bool,87
older_blocked: bool,63
fetched: bool,88
fetched: bool,64
first_unread: Option<String>,89
first_unread: Option<String>,90
sync: SyncProgress,65
}91
}66
92
67
pub struct ConversationView {93
pub struct ConversationView {@@ -76,6 +102,7 @@ pub struct ConversationView {76
hovered_message: Option<String>,102
hovered_message: Option<String>,77
highlighted_message: Option<String>,103
highlighted_message: Option<String>,78
notice: Option<String>,104
notice: Option<String>,105
sync_generation: u64,79
_subscriptions: Vec<Subscription>,106
_subscriptions: Vec<Subscription>,80
}107
}81
108
@@ -110,6 +137,7 @@ impl ConversationView {110
hovered_message: None,137
hovered_message: None,111
highlighted_message: None,138
highlighted_message: None,112
notice: None,139
notice: None,140
sync_generation: 0,113
_subscriptions: subscriptions,141
_subscriptions: subscriptions,114
};142
};115
if let Some(selection) = view.app.read(cx).selection.clone() {143
if let Some(selection) = view.app.read(cx).selection.clone() {@@ -155,7 +183,14 @@ impl ConversationView {155
}183
}156
AppEvent::Images(keys) => self.remeasure_images(keys, cx),184
AppEvent::Images(keys) => self.remeasure_images(keys, cx),157
AppEvent::Jump => self.apply_pending_jump(cx),185
AppEvent::Jump => self.apply_pending_jump(cx),158
AppEvent::Status => self.start_fetch(cx),186
AppEvent::Status => {187
if let Some(current) = self.current.as_mut()188
&& current.sync.failed189
{190
current.fetched = false;191
}192
self.start_fetch(cx)193
}159
AppEvent::Directory => cx.notify(),194
AppEvent::Directory => cx.notify(),160
AppEvent::Sidebar => {195
AppEvent::Sidebar => {161
if let Some(current) = self.current.as_mut() {196
if let Some(current) = self.current.as_mut() {@@ -202,7 +237,9 @@ impl ConversationView {202
older_blocked: false,237
older_blocked: false,203
fetched: false,238
fetched: false,204
first_unread,239
first_unread,240
sync: SyncProgress::default(),205
});241
});242
self.sync_generation += 1;206
self.pending.clear();243
self.pending.clear();207
self.notice = None;244
self.notice = None;208
self.rebuild(true, cx);245
self.rebuild(true, cx);@@ -465,7 +502,15 @@ impl ConversationView {465
current.loaded_limit = limit;502
current.loaded_limit = limit;466
current.loaded_count = records.len();503
current.loaded_count = records.len();467
let has_older = sync_has_more && !current.older_blocked && can_load_older;504
let has_older = sync_has_more && !current.older_blocked && can_load_older;505
let placeholders = current.sync.messages506
&& records.is_empty()507
&& !matches!(current.mode, ViewMode::Thread(_));508
let trailing = current.sync.trailing_skeleton && current.mode == ViewMode::Flat;468
let mut rows = match ¤t.mode {509
let mut rows = match ¤t.mode {510
_ if placeholders => {511
current.has_older = false;512
placeholder_rows()513
}469
ViewMode::Flat => {514
ViewMode::Flat => {470
current.has_older = has_older;515
current.has_older = has_older;471
let mut rows = flat_rows(&records, &context, has_older);516
let mut rows = flat_rows(&records, &context, has_older);@@ -483,16 +528,21 @@ impl ConversationView {483
thread_rows(&records, root_id, &context)528
thread_rows(&records, root_id, &context)484
}529
}485
};530
};531
if trailing && !placeholders {532
rows.push(trailing_skeleton());533
}486
rows.extend(534
rows.extend(487
self.pending535
self.pending488
.iter()536
.iter()489
.cloned()537
.cloned()490
.map(|row| Row::Message(Box::new(row))),538
.map(|row| Row::Message(Box::new(row))),491
);539
);492
let read_ids = self.read_message_ids(&records, cx);540
let receipts = self.receipts(&records, cx);493
for row in rows.iter_mut() {541
for row in rows.iter_mut() {494
if let Row::Message(message) = row {542
if let Row::Message(message) = row495
message.read = read_ids.contains(&message.key);543
&& message.own544
{545
message.receipt = receipts.get(&message.key).copied().unwrap_or_default();496
}546
}497
}547
}498
if let Some(unread_id) = &first_unread {548
if let Some(unread_id) = &first_unread {@@ -553,9 +603,11 @@ impl ConversationView {553
}603
}554
604
555
fn start_fetch(&mut self, cx: &mut Context<Self>) {605
fn start_fetch(&mut self, cx: &mut Context<Self>) {556
let Some(engine) = self.app.read(cx).engine.clone() else {606
let state = self.app.read(cx);607
let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);608
if engine.is_none() && demo_sync.is_none() {557
return;609
return;558
};610
}559
let Some(current) = self.current.as_mut() else {611
let Some(current) = self.current.as_mut() else {560
return;612
return;561
};613
};@@ -563,47 +615,249 @@ impl ConversationView {563
return;615
return;564
}616
}565
current.fetched = true;617
current.fetched = true;618
let is_chat = matches!(current.selection, Selection::Chat(_));619
let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {620
Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {621
Some(message.created_at)622
}623
_ => None,624
});625
let current = self.current.as_mut().expect("checked above");626
if current.sync.failed {627
self.notice = None;628
}629
current.sync = SyncProgress {630
messages: true,631
receipts: is_chat,632
empty_cache: newest_cached.is_none(),633
newest_cached,634
..SyncProgress::default()635
};636
self.sync_generation += 1;637
let generation = self.sync_generation;566
let conversation_id = current.selection.conversation_id().to_owned();638
let conversation_id = current.selection.conversation_id().to_owned();567
let receiver = runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });639
match (engine, demo_sync) {568
cx.spawn(async move |this, cx| {640
(Some(engine), _) => {569
if let Ok(Err(error)) = receiver.await {641
let receiver =570
this.update(cx, |this, cx| {642
runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });571
this.notice = Some(format!("Could not refresh: {}", short_error(&error)));643
cx.spawn(async move |this, cx| {572
cx.notify();644
let result = receiver.await;645
this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))646
.ok();573
})647
})574
.ok();648
.detach();575
}649
}650
(None, Some(delay)) => self.simulate_sync(generation, delay, cx),651
(None, None) => {}652
}653
self.schedule_progress(generation, cx);654
self.rebuild(false, cx);655
self.mark_read(cx);656
self.refresh_receipts(generation, cx);657
}658
659
fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {660
cx.spawn(async move |this, cx| {661
cx.background_executor().timer(delay).await;662
this.update(cx, |this, cx| {663
if let Some(sync) = this.sync_of(generation) {664
sync.receipts = false;665
}666
this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)667
})668
.ok();576
})669
})577
.detach();670
.detach();578
self.mark_read(cx);579
self.refresh_receipts(cx);580
}671
}581
672
582
fn read_message_ids(673
fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {583
&self,674
if generation != self.sync_generation {584
records: &[MessageRecord],675
return None;585
cx: &App,676
}586
) -> std::collections::HashSet<String> {677
self.current.as_mut().map(|current| &mut current.sync)678
}679
680
fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {681
cx.spawn(async move |this, cx| {682
let stages = [683
(PROGRESS_DELAY, Duration::ZERO),684
(SKELETON_DELAY, PROGRESS_DELAY),685
(SLOW_AFTER, SKELETON_DELAY),686
];687
for (stage, (at, previous)) in stages.into_iter().enumerate() {688
cx.background_executor().timer(at - previous).await;689
let running = this690
.update(cx, |this, cx| this.advance_progress(generation, stage, cx))691
.unwrap_or(false);692
if !running {693
return;694
}695
}696
})697
.detach();698
}699
700
fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {701
let Some(sync) = self.sync_of(generation) else {702
return false;703
};704
if !sync.running() {705
return false;706
}707
match stage {708
0 => sync.shown_at = Some(Instant::now()),709
1 if sync.messages => {710
sync.trailing_skeleton = true;711
self.rebuild(false, cx);712
}713
1 => {}714
_ => sync.slow = true,715
}716
cx.notify();717
true718
}719
720
fn finish_fetch(721
&mut self,722
generation: u64,723
result: Result<724
teams_core::Result<teams_core::Delta>,725
tokio::sync::oneshot::error::RecvError,726
>,727
cx: &mut Context<Self>,728
) {729
let Some(sync) = self.sync_of(generation) else {730
return;731
};732
sync.messages = false;733
sync.trailing_skeleton = false;734
let newest_cached = sync.newest_cached;735
match result {736
Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),737
Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),738
Err(error) => self.fail_sync(generation, short_error(&error)),739
}740
self.rebuild(false, cx);741
self.settle_progress(generation, cx);742
}743
744
fn fail_sync(&mut self, generation: u64, error: String) {745
if let Some(sync) = self.sync_of(generation) {746
sync.failed = true;747
sync.receipts = false;748
}749
self.notice = Some(format!("Could not refresh: {error}"));750
}751
752
fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {753
let Some(newest_cached) = newest_cached else {754
return;755
};756
let Some(my_user_id) = self.row_context(cx).my_user_id else {757
return;758
};759
let store = self.app.read(cx).store.clone();760
let Some(current) = self.current.as_mut() else {761
return;762
};763
if current.first_unread.is_some() || current.mode != ViewMode::Flat {764
return;765
}766
let limit = current767
.loaded_limit768
.max(current.loaded_count + GROWTH_HEADROOM);769
current.first_unread = store770
.messages(current.selection.conversation_id(), None, limit)771
.unwrap_or_default()772
.into_iter()773
.find(|record| {774
record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)775
})776
.map(|record| record.message_id);777
}778
779
fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {780
let Some(sync) = self.sync_of(generation) else {781
return;782
};783
if sync.running() {784
return;785
}786
let remaining = sync787
.shown_at788
.map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))789
.unwrap_or_default();790
if remaining.is_zero() {791
sync.shown_at = None;792
sync.slow = false;793
cx.notify();794
return;795
}796
cx.spawn(async move |this, cx| {797
cx.background_executor().timer(remaining).await;798
this.update(cx, |this, cx| {799
if let Some(sync) = this.sync_of(generation) {800
sync.shown_at = None;801
sync.slow = false;802
cx.notify();803
}804
})805
.ok();806
})807
.detach();808
}809
810
fn retry_fetch(&mut self, cx: &mut Context<Self>) {811
if let Some(current) = self.current.as_mut() {812
current.fetched = false;813
}814
self.start_fetch(cx);815
}816
817
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {587
let state = self.app.read(cx);818
let state = self.app.read(cx);819
let receipts_syncing = self820
.current821
.as_ref()822
.is_some_and(|current| current.sync.receipts);588
if state.mode.demo {823
if state.mode.demo {589
return crate::demo::read_message_ids(records);824
let read_ids = crate::demo::read_message_ids(records);825
return records826
.iter()827
.map(|record| {828
let receipt = if receipts_syncing {829
Receipt::Pending830
} else if read_ids.contains(&record.message_id) {831
Receipt::Read832
} else {833
Receipt::Sent834
};835
(record.message_id.clone(), receipt)836
})837
.collect();590
}838
}591
let Some(engine) = state.engine.as_ref() else {839
let Some(engine) = state.engine.as_ref() else {592
return Default::default();840
return HashMap::new();841
};842
let unknown = if receipts_syncing {843
Receipt::Pending844
} else {845
Receipt::Hidden593
};846
};594
records847
records595
.iter()848
.iter()596
.filter(|record| {849
.map(|record| {597
matches!(850
let receipt = match engine.receipt_state_for(record) {598
engine.receipt_state_for(record),851
teams_core::ReceiptState::Read { .. } => Receipt::Read,599
teams_core::ReceiptState::Read { .. }852
teams_core::ReceiptState::Sent => Receipt::Sent,600
)853
teams_core::ReceiptState::Unknown => unknown,854
};855
(record.message_id.clone(), receipt)601
})856
})602
.map(|record| record.message_id.clone())603
.collect()857
.collect()604
}858
}605
859
606
fn refresh_receipts(&mut self, cx: &mut Context<Self>) {860
fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {607
let state = self.app.read(cx);861
let state = self.app.read(cx);608
let (Some(engine), Some(Selection::Chat(chat_id))) = (862
let (Some(engine), Some(Selection::Chat(chat_id))) = (609
state.engine.clone(),863
state.engine.clone(),@@ -611,9 +865,20 @@ impl ConversationView {611
) else {865
) else {612
return;866
return;613
};867
};614
drop(runtime::spawn(async move {868
let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });615
engine.refresh_receipts(&chat_id).await869
cx.spawn(async move |this, cx| {616
}));870
receiver.await.ok();871
this.update(cx, |this, cx| {872
let Some(sync) = this.sync_of(generation) else {873
return;874
};875
sync.receipts = false;876
this.rebuild(false, cx);877
this.settle_progress(generation, cx);878
})879
.ok();880
})881
.detach();617
}882
}618
883
619
fn mark_read(&mut self, cx: &mut Context<Self>) {884
fn mark_read(&mut self, cx: &mut Context<Self>) {@@ -762,7 +1027,7 @@ impl ConversationView {762
open_thread: None,1027
open_thread: None,763
is_reply: false,1028
is_reply: false,764
delivery: Delivery::Sending,1029
delivery: Delivery::Sending,765
read: false,1030
receipt: Receipt::Hidden,766
own: true,1031
own: true,767
});1032
});768
self.notice = None;1033
self.notice = None;@@ -929,7 +1194,24 @@ impl ConversationView {929
if let Some(note) = channel_note {1194
if let Some(note) = channel_note {930
subline = note.to_owned();1195
subline = note.to_owned();931
}1196
}1197
let sync = ¤t.sync;1198
if sync.failed {1199
subline = "Not up to date".to_owned();1200
} else if sync.shown_at.is_some() {1201
subline = if sync.slow {1202
"Taking longer than usual ..."1203
} else if sync.empty_cache {1204
"Loading messages ..."1205
} else {1206
"Updating ..."1207
}1208
.to_owned();1209
}932
header1210
header1211
.relative()1212
.when(sync.shown_at.is_some(), |header| {1213
header.child(progress_bar())1214
})933
.children(lead)1215
.children(lead)934
.child(1216
.child(935
v_flex()1217
v_flex()@@ -1066,6 +1348,7 @@ impl Render for ConversationView {1066
cx,1348
cx,1067
)1349
)1068
}1350
}1351
Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),1069
Some(Row::LoadOlder) => {1352
Some(Row::LoadOlder) => {1070
let view = view.clone();1353
let view = view.clone();1071
cx.defer(move |cx| {1354
cx.defer(move |cx| {@@ -1121,13 +1404,24 @@ impl Render for ConversationView {1121
root = root.child(self.render_header(current, cx));1404
root = root.child(self.render_header(current, cx));1122
if let Some(notice) = &self.notice {1405
if let Some(notice) = &self.notice {1123
root = root.child(1406
root = root.child(1124
div()1407
h_flex()1125
.px_4()1408
.px_4()1126
.py_1()1409
.py_1()1410
.gap(px(8.))1411
.items_center()1127
.text_xs()1412
.text_xs()1128
.bg(theme::amber().opacity(0.15))1413
.bg(theme::amber().opacity(0.15))1129
.text_color(theme::amber())1414
.text_color(theme::amber())1130
.child(notice.clone()),1415
.child(div().flex_1().min_w_0().child(notice.clone()))1416
.when(current.sync.failed, |bar| {1417
bar.child(1418
Button::new("retry-fetch")1419
.ghost()1420
.compact()1421
.label("Retry")1422
.on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),1423
)1424
}),1131
);1425
);1132
}1426
}1133
let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();1427
let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();@@ -1149,3 +1443,33 @@ impl Render for ConversationView {1149
.into_any_element()1443
.into_any_element()1150
}1444
}1151
}1445
}1446
1447
fn progress_bar() -> impl IntoElement {1448
div()1449
.absolute()1450
.left_0()1451
.right_0()1452
.bottom(px(-1.))1453
.h(px(2.))1454
.overflow_hidden()1455
.bg(theme::border())1456
.child(1457
div()1458
.absolute()1459
.top_0()1460
.h_full()1461
.w(relative(PROGRESS_BAR_WIDTH))1462
.bg(theme::own_read())1463
.with_animation(1464
"sync-progress",1465
Animation::new(PROGRESS_BAR_PERIOD).repeat(),1466
|bar, delta| {1467
let travel = 1. + PROGRESS_BAR_WIDTH;1468
// The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).1469
bar.left(relative(1470
(delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,1471
))1472
},1473
),1474
)1475
}@@ -2,13 +2,14 @@ use gpui_kit::assets::IconName;
2
2
use gpui_kit::component::{h_flex, v_flex};
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
use std::time::Duration;
5
6
6
7
use super::attachments::attachments_view;
7
8
use super::avatar::{member_stack, person_avatar};
8
9
use super::widgets::{icon, symbol};
9
10
use crate::data::Directory;
10
11
use crate::render::{Block, render_blocks};
11
use crate::rows::{Delivery, MessageRow, ReactionChip, bubble_corners};
12
use crate::rows::{Delivery, MessageRow, ReactionChip, Receipt, Skeleton, bubble_corners};
12
13
use crate::sidebar_model::DELETED_PREVIEW;
13
14
use crate::theme;
14
15
@@ -26,6 +27,8 @@ const CARD_GAP: f32 = 12.;
26
27
const META_SIZE: f32 = 11.;
27
28
const META_CHECK_SIZE: f32 = 15.;
28
29
const FIGURE_SPACE_WIDTH: f32 = 7.4;
30
const PULSE_PERIOD: Duration = Duration::from_millis(1600);
31
const SKELETON_LINE_HEIGHT: f32 = 20.;
29
32
30
33
pub struct RowActions {
31
34
pub open_thread: RowAction,
@@ -188,13 +191,78 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {
188
191
.text_color(tint)
189
192
.when(row.edited, |meta| meta.child("Edited"))
190
193
.child(row.time.clone())
191
.when(own && row.delivery == Delivery::Delivered, |meta| {
192
if row.read {
193
meta.child(symbol("done_all", META_CHECK_SIZE, theme::own_read()))
194
} else {
195
meta.child(symbol("done", META_CHECK_SIZE, tint))
196
}
194
.when(
195
own && row.delivery == Delivery::Delivered,
196
|meta| match row.receipt {
197
Receipt::Hidden => meta,
198
Receipt::Pending => meta.child(receipt_slot(tint)),
199
Receipt::Sent => meta.child(symbol("done", META_CHECK_SIZE, tint)),
200
Receipt::Read => meta.child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),
201
},
202
)
203
}
204
205
fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> AnimationElement<E> {
206
element.with_animation(
207
id,
208
Animation::new(PULSE_PERIOD)
209
.repeat_synced()
210
.with_easing(pulsating_between(0.35, 1.)),
211
|element, opacity| element.opacity(opacity),
212
)
213
}
214
215
fn receipt_slot(tint: Hsla) -> Div {
216
h_flex()
217
.size(px(META_CHECK_SIZE))
218
.flex_none()
219
.items_center()
220
.justify_center()
221
.child(pulse(
222
"receipt-slot",
223
div()
224
.w(px(13.))
225
.h(px(4.))
226
.rounded(px(2.))
227
.bg(tint.opacity(0.5)),
228
))
229
}
230
231
pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {
232
let corners = bubble_corners(skeleton.own, Default::default());
233
let height = 14. + SKELETON_LINE_HEIGHT * f32::from(skeleton.lines);
234
let shape = div()
235
.w(relative(skeleton.width_ratio))
236
.h(px(height))
237
.rounded_tl(px(corners.top_left))
238
.rounded_tr(px(corners.top_right))
239
.rounded_br(px(corners.bottom_right))
240
.rounded_bl(px(corners.bottom_left))
241
.bg(if skeleton.own {
242
theme::bubble_own().opacity(0.55)
243
} else {
244
theme::bubble_other()
245
});
246
let line = h_flex()
247
.w_full()
248
.when(skeleton.own, |line| line.justify_end())
249
.when(!skeleton.own, |line| {
250
line.gap(px(AVATAR_GAP)).child(
251
div()
252
.size(px(AVATAR_SIZE))
253
.flex_none()
254
.rounded_full()
255
.bg(theme::bubble_other()),
256
)
197
257
})
258
.child(shape);
259
div()
260
.id(ElementId::Name(format!("row-{index}").into()))
261
.w_full()
262
.px(px(24.))
263
.pt(px(SERIES_START_GAP))
264
.child(pulse("skeleton", line))
265
.into_any_element()
198
266
}
199
267
200
268
fn meta_room(row: &MessageRow, own: bool) -> usize {
@@ -409,17 +477,13 @@ fn others_row(
409
477
.items_start();
410
478
if first {
411
479
column = column.child(
412
h_flex()
413
.gap(px(8.))
414
.items_baseline()
415
.pl(px(2.))
416
.child(
417
div()
418
.text_size(px(12.))
419
.font_weight(FontWeight::SEMIBOLD)
420
.text_color(theme::text_soft())
421
.child(row.author.clone()),
422
)
480
h_flex().gap(px(8.)).items_baseline().pl(px(2.)).child(
481
div()
482
.text_size(px(12.))
483
.font_weight(FontWeight::SEMIBOLD)
484
.text_color(theme::text_soft())
485
.child(row.author.clone()),
486
),
423
487
);
424
488
}
425
489
column = column.child(bubble(row, index, false, directory, cx));
@@ -2,13 +2,14 @@ use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
use std::time::Duration;5
6
6
use super::attachments::attachments_view;7
use super::attachments::attachments_view;7
use super::avatar::{member_stack, person_avatar};8
use super::avatar::{member_stack, person_avatar};8
use super::widgets::{icon, symbol};9
use super::widgets::{icon, symbol};9
use crate::data::Directory;10
use crate::data::Directory;10
use crate::render::{Block, render_blocks};11
use crate::render::{Block, render_blocks};11
use crate::rows::{Delivery, MessageRow, ReactionChip, bubble_corners};12
use crate::rows::{Delivery, MessageRow, ReactionChip, Receipt, Skeleton, bubble_corners};12
use crate::sidebar_model::DELETED_PREVIEW;13
use crate::sidebar_model::DELETED_PREVIEW;13
use crate::theme;14
use crate::theme;14
15
@@ -26,6 +27,8 @@ const CARD_GAP: f32 = 12.;26
const META_SIZE: f32 = 11.;27
const META_SIZE: f32 = 11.;27
const META_CHECK_SIZE: f32 = 15.;28
const META_CHECK_SIZE: f32 = 15.;28
const FIGURE_SPACE_WIDTH: f32 = 7.4;29
const FIGURE_SPACE_WIDTH: f32 = 7.4;30
const PULSE_PERIOD: Duration = Duration::from_millis(1600);31
const SKELETON_LINE_HEIGHT: f32 = 20.;29
32
30
pub struct RowActions {33
pub struct RowActions {31
pub open_thread: RowAction,34
pub open_thread: RowAction,@@ -188,13 +191,78 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {188
.text_color(tint)191
.text_color(tint)189
.when(row.edited, |meta| meta.child("Edited"))192
.when(row.edited, |meta| meta.child("Edited"))190
.child(row.time.clone())193
.child(row.time.clone())191
.when(own && row.delivery == Delivery::Delivered, |meta| {194
.when(192
if row.read {195
own && row.delivery == Delivery::Delivered,193
meta.child(symbol("done_all", META_CHECK_SIZE, theme::own_read()))196
|meta| match row.receipt {194
} else {197
Receipt::Hidden => meta,195
meta.child(symbol("done", META_CHECK_SIZE, tint))198
Receipt::Pending => meta.child(receipt_slot(tint)),196
}199
Receipt::Sent => meta.child(symbol("done", META_CHECK_SIZE, tint)),200
Receipt::Read => meta.child(symbol("done_all", META_CHECK_SIZE, theme::own_read())),201
},202
)203
}204
205
fn pulse<E: IntoElement + Styled + 'static>(id: &'static str, element: E) -> AnimationElement<E> {206
element.with_animation(207
id,208
Animation::new(PULSE_PERIOD)209
.repeat_synced()210
.with_easing(pulsating_between(0.35, 1.)),211
|element, opacity| element.opacity(opacity),212
)213
}214
215
fn receipt_slot(tint: Hsla) -> Div {216
h_flex()217
.size(px(META_CHECK_SIZE))218
.flex_none()219
.items_center()220
.justify_center()221
.child(pulse(222
"receipt-slot",223
div()224
.w(px(13.))225
.h(px(4.))226
.rounded(px(2.))227
.bg(tint.opacity(0.5)),228
))229
}230
231
pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {232
let corners = bubble_corners(skeleton.own, Default::default());233
let height = 14. + SKELETON_LINE_HEIGHT * f32::from(skeleton.lines);234
let shape = div()235
.w(relative(skeleton.width_ratio))236
.h(px(height))237
.rounded_tl(px(corners.top_left))238
.rounded_tr(px(corners.top_right))239
.rounded_br(px(corners.bottom_right))240
.rounded_bl(px(corners.bottom_left))241
.bg(if skeleton.own {242
theme::bubble_own().opacity(0.55)243
} else {244
theme::bubble_other()245
});246
let line = h_flex()247
.w_full()248
.when(skeleton.own, |line| line.justify_end())249
.when(!skeleton.own, |line| {250
line.gap(px(AVATAR_GAP)).child(251
div()252
.size(px(AVATAR_SIZE))253
.flex_none()254
.rounded_full()255
.bg(theme::bubble_other()),256
)197
})257
})258
.child(shape);259
div()260
.id(ElementId::Name(format!("row-{index}").into()))261
.w_full()262
.px(px(24.))263
.pt(px(SERIES_START_GAP))264
.child(pulse("skeleton", line))265
.into_any_element()198
}266
}199
267
200
fn meta_room(row: &MessageRow, own: bool) -> usize {268
fn meta_room(row: &MessageRow, own: bool) -> usize {@@ -409,17 +477,13 @@ fn others_row(409
.items_start();477
.items_start();410
if first {478
if first {411
column = column.child(479
column = column.child(412
h_flex()480
h_flex().gap(px(8.)).items_baseline().pl(px(2.)).child(413
.gap(px(8.))481
div()414
.items_baseline()482
.text_size(px(12.))415
.pl(px(2.))483
.font_weight(FontWeight::SEMIBOLD)416
.child(484
.text_color(theme::text_soft())417
div()485
.child(row.author.clone()),418
.text_size(px(12.))486
),419
.font_weight(FontWeight::SEMIBOLD)420
.text_color(theme::text_soft())421
.child(row.author.clone()),422
)423
);487
);424
}488
}425
column = column.child(bubble(row, index, false, directory, cx));489
column = column.child(bubble(row, index, false, directory, cx));@@ -162,6 +162,7 @@ mod tests {
162
162
let mode = Mode {
163
163
demo: true,
164
164
read_only: false,
165
demo_sync: None,
165
166
};
166
167
assert_eq!(
167
168
connection_text(&ConnectionState::NoBrowser, mode).0,
@@ -162,6 +162,7 @@ mod tests {162
let mode = Mode {162
let mode = Mode {163
demo: true,163
demo: true,164
read_only: false,164
read_only: false,165
demo_sync: None,165
};166
};166
assert_eq!(167
assert_eq!(167
connection_text(&ConnectionState::NoBrowser, mode).0,168
connection_text(&ConnectionState::NoBrowser, mode).0,