BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / channel_details.rs

channel_details.rs

0ff9db96 History
channel_details.rs 20.6 KiB Download Raw
1use chrono::{Local, Offset, Utc};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::button::{Button, ButtonVariants as _};
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use store::MessageRecord;
9use teams_core::FileKind;
10
11use super::{ChannelPane, ConversationView};
12use crate::app_state::Selection;
13use crate::channel_files::{SharedContent, SharedItem};
14use crate::find_in_chat::FIND_IN_CHANNEL;
15use crate::format;
16use crate::rows::reply_excerpt;
17use crate::theme;
18use crate::views::attachments::file_badge;
19use crate::views::avatar::person_avatar;
20use crate::views::scroll_edge::with_top_edge;
21
22pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
23pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
24pub const CHANNEL_DETAILS_PINNED_TAG: &str = "shell/islands/main/channel-details/pinned";
25pub const CHANNEL_DETAILS_SHARED_TAG: &str = "shell/islands/main/channel-details/shared";
26const CHANNEL_DETAILS_SCROLL_DIVIDER: &str = "shell/islands/main/channel-details/divider-scroll";
27const OPEN_LABEL: &str = "Open channel details";
28const CLOSE_LABEL: &str = "Close channel details";
29const OPEN_CHAT_LABEL: &str = "Open chat details";
30const CLOSE_CHAT_LABEL: &str = "Close chat details";
31const CHAT_DETAILS_TITLE: &str = "In this chat";
32const PINNED_TITLE: &str = "Pinned";
33const SHARED_TITLE: &str = "Shared";
34const SEE_ALL_SHARED_ARIA: &str = "See all shared files";
35const SEE_ALL_LABEL: &str = "See all";
36const SEE_ALL_ARIA: &str = "See all pinned posts";
37const BACK_LABEL: &str = "Back";
38const FALLBACK_PREVIEW: &str = "Pinned post";
39const PANE_WIDTH: f32 = 320.;
40const PANE_PADDING: f32 = 16.;
41const HEADER_HEIGHT: f32 = 48.;
42const BUTTON_SIZE: f32 = 32.;
43const ITEM_AVATAR: f32 = 24.;
44const COLLAPSED_PIN_COUNT: usize = 3;
45const SHARED_FILE_COUNT: usize = 3;
46
47pub(super) struct PinnedPostItem {
48 pub message_id: String,
49 pub author_id: Option<String>,
50 pub title: String,
51 pub byline: String,
52}
53
54/// Teams' info pane item: post subject or text, then "author, date".
55pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>) -> PinnedPostItem {
56 let Some(record) = record else {
57 return PinnedPostItem {
58 message_id: message_id.to_owned(),
59 author_id: None,
60 title: FALLBACK_PREVIEW.to_owned(),
61 byline: String::new(),
62 };
63 };
64 let today = Local::now().date_naive();
65 let date = format::list_time_label(record.created_at, today, app_base::format::Zone::Local);
66 let author = record.sender_name.clone().unwrap_or_default();
67 let byline = match (author.is_empty(), date.is_empty()) {
68 (false, false) => format!("{author}, {date}"),
69 (false, true) => author,
70 _ => date,
71 };
72 PinnedPostItem {
73 message_id: message_id.to_owned(),
74 author_id: record.sender_id.clone(),
75 title: record
76 .subject
77 .clone()
78 .filter(|subject| !subject.trim().is_empty())
79 .unwrap_or_else(|| reply_excerpt(record)),
80 byline,
81 }
82}
83
84pub(super) struct SharedFileRow {
85 pub message_id: String,
86 pub name: String,
87 pub kind: FileKind,
88 pub byline: String,
89}
90
91pub(super) fn shared_file_rows(items: &[SharedItem]) -> (Vec<SharedFileRow>, bool) {
92 let offset = Local::now().offset().fix();
93 let today = Utc::now().with_timezone(&offset).date_naive();
94 let mut files = items.iter().filter_map(|item| match &item.content {
95 SharedContent::File(card) => Some((item, card)),
96 SharedContent::Link(_) => None,
97 });
98 let rows = files
99 .by_ref()
100 .take(SHARED_FILE_COUNT)
101 .map(|(item, card)| {
102 let date = format::list_time_label(item.created_at, today, offset);
103 SharedFileRow {
104 message_id: item.message_id.clone(),
105 name: card.name.clone(),
106 kind: card.kind,
107 byline: [item.author.as_str(), date.as_str()]
108 .into_iter()
109 .filter(|part| !part.is_empty())
110 .collect::<Vec<_>>()
111 .join(", "),
112 }
113 })
114 .collect();
115 (rows, files.next().is_some())
116}
117
118pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
119 if expanded {
120 total
121 } else {
122 total.min(COLLAPSED_PIN_COUNT)
123 }
124}
125
126impl ConversationView {
127 fn details_channel_id(&self) -> Option<String> {
128 match &self.current.as_ref()?.selection {
129 Selection::Channel(channel_id) => Some(channel_id.clone()),
130 Selection::Chat(_) => None,
131 }
132 }
133
134 fn details_conversation_id(&self) -> Option<String> {
135 match &self.current.as_ref()?.selection {
136 Selection::Channel(channel_id) => Some(channel_id.clone()),
137 Selection::Chat(chat_id) if !self.draft_active && !self.pinned => Some(chat_id.clone()),
138 Selection::Chat(_) => None,
139 }
140 }
141
142 pub(super) fn details_labels(&self) -> (&'static str, &'static str) {
143 if self.details_channel_id().is_some() {
144 (OPEN_LABEL, CLOSE_LABEL)
145 } else {
146 (OPEN_CHAT_LABEL, CLOSE_CHAT_LABEL)
147 }
148 }
149
150 pub(super) fn channel_find_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
151 self.details_channel_id()?;
152 Some(
153 Button::new("channel-find")
154 .icon(IconName::Search)
155 .ghost()
156 .size(px(BUTTON_SIZE))
157 .rounded(px(8.))
158 .tooltip(FIND_IN_CHANNEL)
159 .on_click(cx.listener(|this, _, window, cx| this.open_find(window, cx)))
160 .into_any_element(),
161 )
162 }
163
164 pub(super) fn channel_details_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
165 self.details_conversation_id()?;
166 let open = self.channel_details_open;
167 let (open_label, close_label) = self.details_labels();
168 Some(
169 Button::new("channel-details-toggle")
170 .debug_selector(|| CHANNEL_DETAILS_BUTTON.into())
171 .icon(if open {
172 IconName::PanelRightClose
173 } else {
174 IconName::PanelRight
175 })
176 .ghost()
177 .size(px(BUTTON_SIZE))
178 .rounded(px(8.))
179 .tooltip(if open { close_label } else { open_label })
180 .on_click(cx.listener(|this, _, _, cx| this.toggle_details(cx)))
181 .into_any_element(),
182 )
183 }
184
185 pub(super) fn toggle_details(&mut self, cx: &mut Context<Self>) {
186 self.channel_details_open = !self.channel_details_open;
187 self.pinned_posts_expanded = false;
188 if self.channel_details_open {
189 self.find_panel = None;
190 self.find_subscription = None;
191 self.refresh_shared_items(cx);
192 }
193 cx.notify();
194 }
195
196 pub(super) fn render_channel_details(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
197 if !self.channel_details_open {
198 return None;
199 }
200 let channel_id = self.details_conversation_id()?;
201 let (_, close_label) = self.details_labels();
202 let is_chat = self.details_channel_id().is_none();
203 let state = self.app.read(cx);
204 let ids: Vec<String> = state
205 .pinned_messages(&channel_id)
206 .iter()
207 .map(|pin| pin.message_id.clone())
208 .collect();
209 let records = state
210 .store
211 .messages_by_id(&channel_id, &ids)
212 .unwrap_or_default();
213 let items: Vec<PinnedPostItem> = ids
214 .iter()
215 .map(|id| pinned_post_item(id, records.get(id)))
216 .collect();
217 let expanded = self.pinned_posts_expanded;
218 let shown = shown_pin_count(items.len(), expanded);
219 let has_more = items.len() > shown;
220 let title = if is_chat {
221 CHAT_DETAILS_TITLE.to_owned()
222 } else {
223 self.current
224 .as_ref()
225 .map(|current| current.title.clone())
226 .unwrap_or_default()
227 };
228 let directory = &state.directory;
229 let mut body = v_flex()
230 .w_full()
231 .px(px(PANE_PADDING))
232 .pb(px(PANE_PADDING))
233 .gap(px(4.));
234 if !items.is_empty() {
235 let mut section = v_flex()
236 .w_full()
237 .gap(px(4.))
238 .debug_selector(|| CHANNEL_DETAILS_PINNED_TAG.into());
239 if !expanded {
240 section = section.child(section_title(PINNED_TITLE));
241 }
242 for item in items.iter().take(shown) {
243 section = section.child(self.pinned_post_row(&channel_id, item, directory, cx));
244 }
245 if has_more {
246 section = section.child(
247 Button::new("channel-details-see-all-pins")
248 .ghost()
249 .label(SEE_ALL_LABEL)
250 .tooltip(SEE_ALL_ARIA)
251 .on_click(cx.listener(|this, _, _, cx| {
252 this.pinned_posts_expanded = true;
253 cx.notify();
254 })),
255 );
256 }
257 body = body.child(section);
258 }
259 let (shared_rows, more_shared) = shared_file_rows(&self.shared.items);
260 if !expanded && !shared_rows.is_empty() {
261 let mut section = v_flex()
262 .w_full()
263 .gap(px(4.))
264 .debug_selector(|| CHANNEL_DETAILS_SHARED_TAG.into())
265 .child(section_title(SHARED_TITLE));
266 for row in &shared_rows {
267 section = section.child(self.shared_file_row(&channel_id, row, cx));
268 }
269 if more_shared {
270 section = section.child(
271 Button::new("channel-details-see-all-shared")
272 .ghost()
273 .label(SEE_ALL_LABEL)
274 .tooltip(SEE_ALL_SHARED_ARIA)
275 .on_click(cx.listener(|this, _, _, cx| {
276 this.select_pane(ChannelPane::Shared, cx);
277 })),
278 );
279 }
280 body = body.child(section);
281 }
282 let header = if expanded {
283 h_flex()
284 .gap(px(8.))
285 .child(
286 Button::new("channel-details-back")
287 .icon(IconName::ChevronLeft)
288 .ghost()
289 .size(px(BUTTON_SIZE))
290 .rounded(px(8.))
291 .tooltip(BACK_LABEL)
292 .on_click(cx.listener(|this, _, _, cx| {
293 this.pinned_posts_expanded = false;
294 cx.notify();
295 })),
296 )
297 .child(header_title(PINNED_TITLE.to_owned()))
298 } else {
299 h_flex().child(header_title(title))
300 };
301 Some(
302 h_flex()
303 .h_full()
304 .flex_none()
305 .child(div().w(px(1.)).h_full().flex_none().bg(theme::border()))
306 .child(
307 v_flex()
308 .debug_selector(|| CHANNEL_DETAILS_TAG.into())
309 .w(px(PANE_WIDTH))
310 .h_full()
311 .bg(theme::surface())
312 .child(
313 h_flex()
314 .h(px(HEADER_HEIGHT))
315 .flex_none()
316 .px(px(PANE_PADDING))
317 .items_center()
318 .justify_between()
319 .child(header.flex_1().min_w_0().items_center())
320 .child(
321 Button::new("channel-details-close")
322 .icon(IconName::X)
323 .ghost()
324 .size(px(BUTTON_SIZE))
325 .rounded(px(8.))
326 .tooltip(close_label)
327 .on_click(cx.listener(|this, _, _, cx| {
328 this.channel_details_open = false;
329 this.pinned_posts_expanded = false;
330 cx.notify();
331 })),
332 ),
333 )
334 .child(with_top_edge(
335 div()
336 .id("channel-details-body")
337 .flex_1()
338 .min_h_0()
339 .overflow_y_scrollbar()
340 .track_scroll(&self.channel_details_scroll)
341 .child(body),
342 &self.channel_details_scroll,
343 CHANNEL_DETAILS_SCROLL_DIVIDER,
344 )),
345 )
346 .into_any_element(),
347 )
348 }
349
350 fn pinned_post_row(
351 &self,
352 channel_id: &str,
353 item: &PinnedPostItem,
354 directory: &crate::data::Directory,
355 cx: &Context<Self>,
356 ) -> AnyElement {
357 let (channel_id, message_id) = (channel_id.to_owned(), item.message_id.clone());
358 let author_name = item.byline.split(',').next().unwrap_or_default().to_owned();
359 h_flex()
360 .id(SharedString::from(format!(
361 "pinned-post-{}",
362 item.message_id
363 )))
364 .w_full()
365 .p(px(8.))
366 .gap(px(10.))
367 .items_start()
368 .rounded(px(8.))
369 .cursor_pointer()
370 .hover(|row| row.bg(theme::row_hover()))
371 .child(person_avatar(
372 directory,
373 item.author_id.as_deref(),
374 &author_name,
375 ITEM_AVATAR,
376 ))
377 .child(
378 v_flex()
379 .flex_1()
380 .min_w_0()
381 .gap(px(2.))
382 .child(
383 div()
384 .truncate()
385 .text_size(px(13.))
386 .text_color(theme::text())
387 .child(item.title.clone()),
388 )
389 .when(!item.byline.is_empty(), |column| {
390 column.child(
391 div()
392 .truncate()
393 .text_size(px(12.))
394 .text_color(theme::text_muted())
395 .child(item.byline.clone()),
396 )
397 }),
398 )
399 .on_click(cx.listener(move |this, _, _, cx| {
400 this.jump_to_message(&channel_id, &message_id, cx);
401 }))
402 .into_any_element()
403 }
404}
405
406impl ConversationView {
407 fn shared_file_row(
408 &self,
409 channel_id: &str,
410 row: &SharedFileRow,
411 cx: &Context<Self>,
412 ) -> AnyElement {
413 let (channel_id, message_id) = (channel_id.to_owned(), row.message_id.clone());
414 h_flex()
415 .id(SharedString::from(format!(
416 "shared-file-{}-{}",
417 row.message_id, row.name
418 )))
419 .w_full()
420 .p(px(8.))
421 .gap(px(10.))
422 .items_start()
423 .rounded(px(8.))
424 .cursor_pointer()
425 .hover(|item| item.bg(theme::row_hover()))
426 .child(file_badge(row.kind, ITEM_AVATAR))
427 .child(
428 v_flex()
429 .flex_1()
430 .min_w_0()
431 .gap(px(2.))
432 .child(
433 div()
434 .truncate()
435 .text_size(px(13.))
436 .text_color(theme::text())
437 .child(row.name.clone()),
438 )
439 .when(!row.byline.is_empty(), |column| {
440 column.child(
441 div()
442 .truncate()
443 .text_size(px(12.))
444 .text_color(theme::text_muted())
445 .child(row.byline.clone()),
446 )
447 }),
448 )
449 .on_click(cx.listener(move |this, _, _, cx| {
450 this.jump_to_message(&channel_id, &message_id, cx);
451 }))
452 .into_any_element()
453 }
454}
455
456fn section_title(text: &'static str) -> Div {
457 div()
458 .py(px(8.))
459 .text_size(px(14.))
460 .font_weight(FontWeight::SEMIBOLD)
461 .text_color(theme::text())
462 .child(text)
463}
464
465fn header_title(text: String) -> Div {
466 div()
467 .flex_1()
468 .min_w_0()
469 .truncate()
470 .text_size(px(15.))
471 .font_weight(FontWeight::SEMIBOLD)
472 .text_color(theme::text())
473 .child(text)
474}
475
476#[cfg(test)]
477mod tests {
478 use chrono::{TimeZone, Utc};
479 use store::MessageRecord;
480
481 use teams_core::{FileCard, FileKind};
482
483 use super::{FALLBACK_PREVIEW, pinned_post_item, shared_file_rows, shown_pin_count};
484 use crate::channel_files::{SharedContent, SharedItem};
485
486 fn record(subject: Option<&str>) -> MessageRecord {
487 MessageRecord {
488 conversation_id: "19:channel".into(),
489 message_id: "1".into(),
490 sender_id: Some("user-ada".into()),
491 sender_name: Some("Ada Lovelace".into()),
492 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
493 body_html: "<p>Release notes are up</p>".into(),
494 subject: subject.map(str::to_owned),
495 attachments_json: "[]".into(),
496 reactions_json: "[]".into(),
497 mentions_json: "[]".into(),
498 links_json: "[]".into(),
499 ..MessageRecord::default()
500 }
501 }
502
503 #[test]
504 fn the_item_prefers_the_subject_and_names_author_and_date() {
505 let item = pinned_post_item("1", Some(&record(Some("Release 4.2"))));
506 assert_eq!(item.title, "Release 4.2");
507 assert!(item.byline.starts_with("Ada Lovelace, "), "{}", item.byline);
508 assert_eq!(item.author_id.as_deref(), Some("user-ada"));
509 let plain = pinned_post_item("1", Some(&record(None)));
510 assert_eq!(plain.title, "Release notes are up");
511 }
512
513 #[test]
514 fn an_uncached_post_keeps_its_place_with_a_fallback() {
515 let item = pinned_post_item("9", None);
516 assert_eq!(item.message_id, "9");
517 assert_eq!(item.title, FALLBACK_PREVIEW);
518 assert!(item.byline.is_empty());
519 }
520
521 #[test]
522 fn three_pins_show_until_see_all() {
523 assert_eq!(shown_pin_count(5, false), 3);
524 assert_eq!(shown_pin_count(2, false), 2);
525 assert_eq!(shown_pin_count(5, true), 5);
526 }
527
528 fn shared(content: SharedContent, message_id: &str) -> SharedItem {
529 SharedItem {
530 content,
531 author: "Ada Lovelace".into(),
532 post_label: String::new(),
533 message_id: message_id.into(),
534 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
535 }
536 }
537
538 fn file(name: &str) -> SharedContent {
539 SharedContent::File(FileCard {
540 name: name.into(),
541 kind: FileKind::from_name(name),
542 content_type: None,
543 size: None,
544 open_url: format!("https://example.invalid/{name}"),
545 })
546 }
547
548 #[test]
549 fn shared_section_lists_the_newest_files_and_skips_links() {
550 let items = vec![
551 shared(SharedContent::Link("https://example.invalid".into()), "1"),
552 shared(file("plan.docx"), "2"),
553 shared(file("budget.xlsx"), "3"),
554 ];
555 let (rows, more) = shared_file_rows(&items);
556 let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
557 assert_eq!(names, ["plan.docx", "budget.xlsx"]);
558 assert!(!more);
559 assert_eq!(rows[0].message_id, "2");
560 assert!(
561 rows[0].byline.starts_with("Ada Lovelace, "),
562 "{}",
563 rows[0].byline
564 );
565 }
566
567 #[test]
568 fn shared_section_offers_see_all_after_three_files() {
569 let items: Vec<SharedItem> = (0..4)
570 .map(|index| shared(file(&format!("file-{index}.pdf")), &index.to_string()))
571 .collect();
572 let (rows, more) = shared_file_rows(&items);
573 assert_eq!(rows.len(), 3);
574 assert!(more);
575 }
576}