BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into fix/menu-alignment

# Conflicts:
#	crates/app/src/layout_guard.rs

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
ed12e82e9288ee33a3903073ba6e0ac7eea6489c
14 files changed +2056 −10
crates/app-state/src/chat_filter.rs added +376 −0
@@ -0,0 +1,376 @@
1 use std::collections::HashSet;
2
3 use store::ChatRecord;
4
5 use crate::activity::{Entry, Kind};
6 use crate::app_state::chat_title;
7 use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8
9 pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
10 pub const NO_MATCHES: &str = "We didn't find any matches.";
11 pub const CLEAR_FILTERS: &str = "Clear filters";
12 pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
13 pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
14 pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
15 pub const MORE_FILTERS: &str = "More filters";
16 pub const FEWER_FILTERS: &str = "Fewer filters";
17 const MEETING_KIND: &str = "meeting";
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20 pub enum ChatFilterPill {
21 Unread,
22 Mentions,
23 Chats,
24 Meetings,
25 Muted,
26 }
27
28 impl ChatFilterPill {
29 pub const PRIMARY: [ChatFilterPill; 3] = [
30 ChatFilterPill::Unread,
31 ChatFilterPill::Mentions,
32 ChatFilterPill::Chats,
33 ];
34 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Meetings, ChatFilterPill::Muted];
35
36 pub fn label(self) -> &'static str {
37 match self {
38 ChatFilterPill::Unread => "Unread",
39 ChatFilterPill::Mentions => "@Mentions",
40 ChatFilterPill::Chats => "Chats",
41 ChatFilterPill::Meetings => "Meeting chats",
42 ChatFilterPill::Muted => "Muted",
43 }
44 }
45
46 fn is_category(self) -> bool {
47 matches!(self, ChatFilterPill::Chats | ChatFilterPill::Meetings)
48 }
49
50 fn excludes(self) -> Option<ChatFilterPill> {
51 match self {
52 ChatFilterPill::Mentions => Some(ChatFilterPill::Muted),
53 ChatFilterPill::Muted => Some(ChatFilterPill::Mentions),
54 ChatFilterPill::Chats => Some(ChatFilterPill::Meetings),
55 ChatFilterPill::Meetings => Some(ChatFilterPill::Chats),
56 ChatFilterPill::Unread => None,
57 }
58 }
59
60 fn admits(self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
61 let meeting = chat.kind.eq_ignore_ascii_case(MEETING_KIND);
62 match self {
63 ChatFilterPill::Unread => chat.unread,
64 ChatFilterPill::Mentions => mentioned.contains(&chat.id),
65 ChatFilterPill::Chats => !meeting,
66 ChatFilterPill::Meetings => meeting,
67 ChatFilterPill::Muted => chat.muted,
68 }
69 }
70 }
71
72 #[derive(Debug, Clone, Default, PartialEq, Eq)]
73 pub struct ChatFilter {
74 pub text: String,
75 pub pills: Vec<ChatFilterPill>,
76 }
77
78 impl ChatFilter {
79 pub fn is_active(&self) -> bool {
80 !self.text.trim().is_empty() || !self.pills.is_empty()
81 }
82
83 pub fn has(&self, pill: ChatFilterPill) -> bool {
84 self.pills.contains(&pill)
85 }
86
87 pub fn is_disabled(&self, pill: ChatFilterPill) -> bool {
88 !self.has(pill)
89 && self
90 .pills
91 .iter()
92 .any(|active| active.excludes() == Some(pill))
93 }
94
95 pub fn toggle(&mut self, pill: ChatFilterPill) -> bool {
96 if self.has(pill) {
97 self.pills.retain(|active| *active != pill);
98 return true;
99 }
100 if self.is_disabled(pill) {
101 return false;
102 }
103 self.pills.push(pill);
104 true
105 }
106
107 pub fn clear(&mut self) {
108 self.text.clear();
109 self.pills.clear();
110 }
111
112 pub fn admits(&self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
113 if !name_matches(&self.text, &chat_title(chat)) {
114 return false;
115 }
116 let states_hold = self
117 .pills
118 .iter()
119 .filter(|pill| !pill.is_category())
120 .all(|pill| pill.admits(chat, mentioned));
121 let mut categories = self
122 .pills
123 .iter()
124 .filter(|pill| pill.is_category())
125 .peekable();
126 let category_holds =
127 categories.peek().is_none() || categories.any(|pill| pill.admits(chat, mentioned));
128 states_hold && category_holds
129 }
130 }
131
132 pub fn mentioned_conversations<'a>(entries: impl Iterator<Item = &'a Entry>) -> HashSet<String> {
133 entries
134 .filter(|entry| entry.kind == Kind::Mention)
135 .map(|entry| entry.conversation_id.clone())
136 .collect()
137 }
138
139 fn words(text: &str) -> Vec<String> {
140 text.to_lowercase()
141 .split(|character: char| character.is_whitespace() || character == ',')
142 .filter(|word| !word.is_empty())
143 .map(str::to_owned)
144 .collect()
145 }
146
147 pub fn name_matches(query: &str, title: &str) -> bool {
148 let query = query.trim().to_lowercase();
149 if query.is_empty() {
150 return true;
151 }
152 let title_lower = title.to_lowercase();
153 if title_lower.contains(&query) {
154 return true;
155 }
156 let title_words = words(&title_lower);
157 words(&query).iter().all(|word| {
158 title_words
159 .iter()
160 .any(|title_word| title_word.starts_with(word.as_str()))
161 })
162 }
163
164 pub fn filtered_sections(
165 input: &SectionInput<'_>,
166 filter: &ChatFilter,
167 mentioned: &HashSet<String>,
168 selected_id: Option<&str>,
169 ) -> Vec<Section> {
170 let chats: Vec<ChatRecord> = input
171 .chats
172 .iter()
173 .filter(|chat| Some(chat.id.as_str()) == selected_id || filter.admits(chat, mentioned))
174 .cloned()
175 .collect();
176 let every_list: HashSet<String> = input
177 .directory
178 .folders
179 .iter()
180 .map(|folder| folder.id.clone())
181 .chain([MUTED_ID.to_owned(), OTHERS_ID.to_owned()])
182 .collect();
183 let unpaged = SectionInput {
184 chats: &chats,
185 expanded_lists: &every_list,
186 ..*input
187 };
188 build_sections(&unpaged)
189 .into_iter()
190 .filter(|section| !section.items.is_empty())
191 .map(|section| Section {
192 hidden_count: 0,
193 list_expanded: false,
194 show_empty_hint: false,
195 ..section
196 })
197 .collect()
198 }
199
200 pub fn has_no_matches(sections: &[Section], selected_id: Option<&str>) -> bool {
201 sections
202 .iter()
203 .flat_map(|section| &section.items)
204 .all(|item| Some(item.id.as_str()) == selected_id)
205 }
206
207 #[cfg(test)]
208 mod tests {
209 use chrono::{FixedOffset, TimeZone, Utc};
210
211 use super::*;
212 use crate::data::{Directory, FolderInfo, FolderKind};
213 use crate::typing::TypingState;
214 use teams_core::ChatSection;
215
216 fn chat(id: &str, title: &str, kind: &str) -> ChatRecord {
217 ChatRecord {
218 id: id.into(),
219 kind: kind.into(),
220 title: title.into(),
221 ..Default::default()
222 }
223 }
224
225 fn admitted(filter: &ChatFilter, chats: &[ChatRecord], mentioned: &[&str]) -> Vec<String> {
226 let mentioned: HashSet<String> = mentioned.iter().map(|id| (*id).to_owned()).collect();
227 chats
228 .iter()
229 .filter(|chat| filter.admits(chat, &mentioned))
230 .map(|chat| chat.id.clone())
231 .collect()
232 }
233
234 #[test]
235 fn name_filter_matches_a_substring_or_every_word_prefix_like_teams() {
236 assert!(name_matches("", "Anything"));
237 assert!(name_matches("lind", "Mara Lindqvist"));
238 assert!(name_matches("ma li", "Mara Lindqvist"));
239 assert!(name_matches("LI, MA", "Mara Lindqvist"));
240 assert!(!name_matches("ma xo", "Mara Lindqvist"));
241 }
242
243 #[test]
244 fn state_pills_must_all_hold_and_category_pills_need_one() {
245 let chats = [
246 ChatRecord {
247 unread: true,
248 ..chat("unread", "Unread chat", "group")
249 },
250 ChatRecord {
251 unread: true,
252 ..chat("meeting", "Standup", "meeting")
253 },
254 ChatRecord {
255 muted: true,
256 ..chat("muted", "Muted chat", "group")
257 },
258 chat("plain", "Plain chat", "oneOnOne"),
259 ];
260 let mut filter = ChatFilter::default();
261 assert_eq!(admitted(&filter, &chats, &[]).len(), 4);
262 filter.toggle(ChatFilterPill::Unread);
263 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "meeting"]);
264 filter.toggle(ChatFilterPill::Meetings);
265 assert_eq!(admitted(&filter, &chats, &[]), ["meeting"]);
266 filter.toggle(ChatFilterPill::Unread);
267 filter.toggle(ChatFilterPill::Meetings);
268 filter.toggle(ChatFilterPill::Chats);
269 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "muted", "plain"]);
270 filter.toggle(ChatFilterPill::Mentions);
271 assert_eq!(admitted(&filter, &chats, &["plain"]), ["plain"]);
272 }
273
274 #[test]
275 fn exclusive_pills_disable_each_other() {
276 let mut filter = ChatFilter::default();
277 assert!(filter.toggle(ChatFilterPill::Chats));
278 assert!(filter.is_disabled(ChatFilterPill::Meetings));
279 assert!(!filter.toggle(ChatFilterPill::Meetings));
280 assert!(filter.toggle(ChatFilterPill::Muted));
281 assert!(filter.is_disabled(ChatFilterPill::Mentions));
282 assert!(!filter.is_disabled(ChatFilterPill::Unread));
283 assert!(filter.toggle(ChatFilterPill::Chats));
284 assert!(!filter.is_disabled(ChatFilterPill::Meetings));
285 filter.text = "x".into();
286 assert!(filter.is_active());
287 filter.clear();
288 assert!(!filter.is_active());
289 }
290
291 #[test]
292 fn text_combines_with_pills() {
293 let chats = [
294 ChatRecord {
295 unread: true,
296 ..chat("a", "Release crew", "group")
297 },
298 chat("b", "Release notes", "group"),
299 ];
300 let filter = ChatFilter {
301 text: "rel".into(),
302 pills: vec![ChatFilterPill::Unread],
303 };
304 assert_eq!(admitted(&filter, &chats, &[]), ["a"]);
305 }
306
307 static NO_TYPING: std::sync::LazyLock<TypingState> =
308 std::sync::LazyLock::new(TypingState::default);
309
310 #[test]
311 fn filtered_sections_keep_sections_drop_empty_ones_and_unpage_muted() {
312 let mut chats = vec![
313 chat("fav", "Favorite release", "group"),
314 chat("other", "Other release", "group"),
315 chat("quiet", "Quiet", "group"),
316 ];
317 chats.extend((0..7).map(|index| ChatRecord {
318 muted: true,
319 ..chat(
320 &format!("m{index}"),
321 &format!("Muted release {index}"),
322 "group",
323 )
324 }));
325 let mut directory = Directory {
326 folders: vec![
327 FolderInfo {
328 id: "favorites".into(),
329 name: "Favorites".into(),
330 kind: FolderKind::Favorites,
331 expanded: None,
332 conversation_ids: vec!["fav".into()],
333 },
334 FolderInfo {
335 id: "empty".into(),
336 name: "Empty".into(),
337 kind: FolderKind::UserCreated,
338 expanded: None,
339 conversation_ids: Vec::new(),
340 },
341 ],
342 ..Default::default()
343 };
344 directory.section_settings.set(ChatSection::Muted, true);
345 let collapsed = HashSet::new();
346 let expanded = HashSet::new();
347 let input = SectionInput {
348 chats: &chats,
349 directory: &directory,
350 collapsed: &collapsed,
351 expanded_lists: &expanded,
352 typing: &NO_TYPING,
353 now: Utc.with_ymd_and_hms(2026, 10, 17, 12, 0, 0).unwrap(),
354 offset: FixedOffset::east_opt(0).unwrap(),
355 };
356 let filter = ChatFilter {
357 text: "release".into(),
358 pills: Vec::new(),
359 };
360 let sections = filtered_sections(&input, &filter, &HashSet::new(), None);
361 let names: Vec<(&str, usize)> = sections
362 .iter()
363 .map(|section| (section.id.as_str(), section.items.len()))
364 .collect();
365 assert_eq!(names, [("favorites", 1), (OTHERS_ID, 1), (MUTED_ID, 7)]);
366 assert!(sections.iter().all(|section| section.hidden_count == 0
367 && !section.list_expanded
368 && !section.show_empty_hint));
369 let with_selection = filtered_sections(&input, &filter, &HashSet::new(), Some("quiet"));
370 assert!(
371 with_selection
372 .iter()
373 .any(|section| section.items.iter().any(|item| item.id == "quiet"))
374 );
375 }
376 }
@@ -0,0 +1,376 @@
1use std::collections::HashSet;
2
3use store::ChatRecord;
4
5use crate::activity::{Entry, Kind};
6use crate::app_state::chat_title;
7use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8
9pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
10pub const NO_MATCHES: &str = "We didn't find any matches.";
11pub const CLEAR_FILTERS: &str = "Clear filters";
12pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
13pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
14pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
15pub const MORE_FILTERS: &str = "More filters";
16pub const FEWER_FILTERS: &str = "Fewer filters";
17const MEETING_KIND: &str = "meeting";
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum ChatFilterPill {
21 Unread,
22 Mentions,
23 Chats,
24 Meetings,
25 Muted,
26}
27
28impl ChatFilterPill {
29 pub const PRIMARY: [ChatFilterPill; 3] = [
30 ChatFilterPill::Unread,
31 ChatFilterPill::Mentions,
32 ChatFilterPill::Chats,
33 ];
34 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Meetings, ChatFilterPill::Muted];
35
36 pub fn label(self) -> &'static str {
37 match self {
38 ChatFilterPill::Unread => "Unread",
39 ChatFilterPill::Mentions => "@Mentions",
40 ChatFilterPill::Chats => "Chats",
41 ChatFilterPill::Meetings => "Meeting chats",
42 ChatFilterPill::Muted => "Muted",
43 }
44 }
45
46 fn is_category(self) -> bool {
47 matches!(self, ChatFilterPill::Chats | ChatFilterPill::Meetings)
48 }
49
50 fn excludes(self) -> Option<ChatFilterPill> {
51 match self {
52 ChatFilterPill::Mentions => Some(ChatFilterPill::Muted),
53 ChatFilterPill::Muted => Some(ChatFilterPill::Mentions),
54 ChatFilterPill::Chats => Some(ChatFilterPill::Meetings),
55 ChatFilterPill::Meetings => Some(ChatFilterPill::Chats),
56 ChatFilterPill::Unread => None,
57 }
58 }
59
60 fn admits(self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
61 let meeting = chat.kind.eq_ignore_ascii_case(MEETING_KIND);
62 match self {
63 ChatFilterPill::Unread => chat.unread,
64 ChatFilterPill::Mentions => mentioned.contains(&chat.id),
65 ChatFilterPill::Chats => !meeting,
66 ChatFilterPill::Meetings => meeting,
67 ChatFilterPill::Muted => chat.muted,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Default, PartialEq, Eq)]
73pub struct ChatFilter {
74 pub text: String,
75 pub pills: Vec<ChatFilterPill>,
76}
77
78impl ChatFilter {
79 pub fn is_active(&self) -> bool {
80 !self.text.trim().is_empty() || !self.pills.is_empty()
81 }
82
83 pub fn has(&self, pill: ChatFilterPill) -> bool {
84 self.pills.contains(&pill)
85 }
86
87 pub fn is_disabled(&self, pill: ChatFilterPill) -> bool {
88 !self.has(pill)
89 && self
90 .pills
91 .iter()
92 .any(|active| active.excludes() == Some(pill))
93 }
94
95 pub fn toggle(&mut self, pill: ChatFilterPill) -> bool {
96 if self.has(pill) {
97 self.pills.retain(|active| *active != pill);
98 return true;
99 }
100 if self.is_disabled(pill) {
101 return false;
102 }
103 self.pills.push(pill);
104 true
105 }
106
107 pub fn clear(&mut self) {
108 self.text.clear();
109 self.pills.clear();
110 }
111
112 pub fn admits(&self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
113 if !name_matches(&self.text, &chat_title(chat)) {
114 return false;
115 }
116 let states_hold = self
117 .pills
118 .iter()
119 .filter(|pill| !pill.is_category())
120 .all(|pill| pill.admits(chat, mentioned));
121 let mut categories = self
122 .pills
123 .iter()
124 .filter(|pill| pill.is_category())
125 .peekable();
126 let category_holds =
127 categories.peek().is_none() || categories.any(|pill| pill.admits(chat, mentioned));
128 states_hold && category_holds
129 }
130}
131
132pub fn mentioned_conversations<'a>(entries: impl Iterator<Item = &'a Entry>) -> HashSet<String> {
133 entries
134 .filter(|entry| entry.kind == Kind::Mention)
135 .map(|entry| entry.conversation_id.clone())
136 .collect()
137}
138
139fn words(text: &str) -> Vec<String> {
140 text.to_lowercase()
141 .split(|character: char| character.is_whitespace() || character == ',')
142 .filter(|word| !word.is_empty())
143 .map(str::to_owned)
144 .collect()
145}
146
147pub fn name_matches(query: &str, title: &str) -> bool {
148 let query = query.trim().to_lowercase();
149 if query.is_empty() {
150 return true;
151 }
152 let title_lower = title.to_lowercase();
153 if title_lower.contains(&query) {
154 return true;
155 }
156 let title_words = words(&title_lower);
157 words(&query).iter().all(|word| {
158 title_words
159 .iter()
160 .any(|title_word| title_word.starts_with(word.as_str()))
161 })
162}
163
164pub fn filtered_sections(
165 input: &SectionInput<'_>,
166 filter: &ChatFilter,
167 mentioned: &HashSet<String>,
168 selected_id: Option<&str>,
169) -> Vec<Section> {
170 let chats: Vec<ChatRecord> = input
171 .chats
172 .iter()
173 .filter(|chat| Some(chat.id.as_str()) == selected_id || filter.admits(chat, mentioned))
174 .cloned()
175 .collect();
176 let every_list: HashSet<String> = input
177 .directory
178 .folders
179 .iter()
180 .map(|folder| folder.id.clone())
181 .chain([MUTED_ID.to_owned(), OTHERS_ID.to_owned()])
182 .collect();
183 let unpaged = SectionInput {
184 chats: &chats,
185 expanded_lists: &every_list,
186 ..*input
187 };
188 build_sections(&unpaged)
189 .into_iter()
190 .filter(|section| !section.items.is_empty())
191 .map(|section| Section {
192 hidden_count: 0,
193 list_expanded: false,
194 show_empty_hint: false,
195 ..section
196 })
197 .collect()
198}
199
200pub fn has_no_matches(sections: &[Section], selected_id: Option<&str>) -> bool {
201 sections
202 .iter()
203 .flat_map(|section| &section.items)
204 .all(|item| Some(item.id.as_str()) == selected_id)
205}
206
207#[cfg(test)]
208mod tests {
209 use chrono::{FixedOffset, TimeZone, Utc};
210
211 use super::*;
212 use crate::data::{Directory, FolderInfo, FolderKind};
213 use crate::typing::TypingState;
214 use teams_core::ChatSection;
215
216 fn chat(id: &str, title: &str, kind: &str) -> ChatRecord {
217 ChatRecord {
218 id: id.into(),
219 kind: kind.into(),
220 title: title.into(),
221 ..Default::default()
222 }
223 }
224
225 fn admitted(filter: &ChatFilter, chats: &[ChatRecord], mentioned: &[&str]) -> Vec<String> {
226 let mentioned: HashSet<String> = mentioned.iter().map(|id| (*id).to_owned()).collect();
227 chats
228 .iter()
229 .filter(|chat| filter.admits(chat, &mentioned))
230 .map(|chat| chat.id.clone())
231 .collect()
232 }
233
234 #[test]
235 fn name_filter_matches_a_substring_or_every_word_prefix_like_teams() {
236 assert!(name_matches("", "Anything"));
237 assert!(name_matches("lind", "Mara Lindqvist"));
238 assert!(name_matches("ma li", "Mara Lindqvist"));
239 assert!(name_matches("LI, MA", "Mara Lindqvist"));
240 assert!(!name_matches("ma xo", "Mara Lindqvist"));
241 }
242
243 #[test]
244 fn state_pills_must_all_hold_and_category_pills_need_one() {
245 let chats = [
246 ChatRecord {
247 unread: true,
248 ..chat("unread", "Unread chat", "group")
249 },
250 ChatRecord {
251 unread: true,
252 ..chat("meeting", "Standup", "meeting")
253 },
254 ChatRecord {
255 muted: true,
256 ..chat("muted", "Muted chat", "group")
257 },
258 chat("plain", "Plain chat", "oneOnOne"),
259 ];
260 let mut filter = ChatFilter::default();
261 assert_eq!(admitted(&filter, &chats, &[]).len(), 4);
262 filter.toggle(ChatFilterPill::Unread);
263 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "meeting"]);
264 filter.toggle(ChatFilterPill::Meetings);
265 assert_eq!(admitted(&filter, &chats, &[]), ["meeting"]);
266 filter.toggle(ChatFilterPill::Unread);
267 filter.toggle(ChatFilterPill::Meetings);
268 filter.toggle(ChatFilterPill::Chats);
269 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "muted", "plain"]);
270 filter.toggle(ChatFilterPill::Mentions);
271 assert_eq!(admitted(&filter, &chats, &["plain"]), ["plain"]);
272 }
273
274 #[test]
275 fn exclusive_pills_disable_each_other() {
276 let mut filter = ChatFilter::default();
277 assert!(filter.toggle(ChatFilterPill::Chats));
278 assert!(filter.is_disabled(ChatFilterPill::Meetings));
279 assert!(!filter.toggle(ChatFilterPill::Meetings));
280 assert!(filter.toggle(ChatFilterPill::Muted));
281 assert!(filter.is_disabled(ChatFilterPill::Mentions));
282 assert!(!filter.is_disabled(ChatFilterPill::Unread));
283 assert!(filter.toggle(ChatFilterPill::Chats));
284 assert!(!filter.is_disabled(ChatFilterPill::Meetings));
285 filter.text = "x".into();
286 assert!(filter.is_active());
287 filter.clear();
288 assert!(!filter.is_active());
289 }
290
291 #[test]
292 fn text_combines_with_pills() {
293 let chats = [
294 ChatRecord {
295 unread: true,
296 ..chat("a", "Release crew", "group")
297 },
298 chat("b", "Release notes", "group"),
299 ];
300 let filter = ChatFilter {
301 text: "rel".into(),
302 pills: vec![ChatFilterPill::Unread],
303 };
304 assert_eq!(admitted(&filter, &chats, &[]), ["a"]);
305 }
306
307 static NO_TYPING: std::sync::LazyLock<TypingState> =
308 std::sync::LazyLock::new(TypingState::default);
309
310 #[test]
311 fn filtered_sections_keep_sections_drop_empty_ones_and_unpage_muted() {
312 let mut chats = vec![
313 chat("fav", "Favorite release", "group"),
314 chat("other", "Other release", "group"),
315 chat("quiet", "Quiet", "group"),
316 ];
317 chats.extend((0..7).map(|index| ChatRecord {
318 muted: true,
319 ..chat(
320 &format!("m{index}"),
321 &format!("Muted release {index}"),
322 "group",
323 )
324 }));
325 let mut directory = Directory {
326 folders: vec![
327 FolderInfo {
328 id: "favorites".into(),
329 name: "Favorites".into(),
330 kind: FolderKind::Favorites,
331 expanded: None,
332 conversation_ids: vec!["fav".into()],
333 },
334 FolderInfo {
335 id: "empty".into(),
336 name: "Empty".into(),
337 kind: FolderKind::UserCreated,
338 expanded: None,
339 conversation_ids: Vec::new(),
340 },
341 ],
342 ..Default::default()
343 };
344 directory.section_settings.set(ChatSection::Muted, true);
345 let collapsed = HashSet::new();
346 let expanded = HashSet::new();
347 let input = SectionInput {
348 chats: &chats,
349 directory: &directory,
350 collapsed: &collapsed,
351 expanded_lists: &expanded,
352 typing: &NO_TYPING,
353 now: Utc.with_ymd_and_hms(2026, 10, 17, 12, 0, 0).unwrap(),
354 offset: FixedOffset::east_opt(0).unwrap(),
355 };
356 let filter = ChatFilter {
357 text: "release".into(),
358 pills: Vec::new(),
359 };
360 let sections = filtered_sections(&input, &filter, &HashSet::new(), None);
361 let names: Vec<(&str, usize)> = sections
362 .iter()
363 .map(|section| (section.id.as_str(), section.items.len()))
364 .collect();
365 assert_eq!(names, [("favorites", 1), (OTHERS_ID, 1), (MUTED_ID, 7)]);
366 assert!(sections.iter().all(|section| section.hidden_count == 0
367 && !section.list_expanded
368 && !section.show_empty_hint));
369 let with_selection = filtered_sections(&input, &filter, &HashSet::new(), Some("quiet"));
370 assert!(
371 with_selection
372 .iter()
373 .any(|section| section.items.iter().any(|item| item.id == "quiet"))
374 );
375 }
376}
crates/app-state/src/demo.rs +10 −0
@@ -754,6 +754,16 @@ pub fn activity_entries() -> Vec<Entry> {
754 754 false,
755 755 ),
756 756 reaction,
757 entry(
758 "demo-chat-allhands",
759 Kind::Mention,
760 "demo-allhands-policy",
761 vec![actor(LEA_ID, "Lea Schneider")],
762 "@Dana please read the new vacation policy before Friday.",
763 1,
764 at(0, 9, 0),
765 false,
766 ),
757 767 entry(
758 768 "demo-chat-customer-3",
759 769 Kind::Messages,
@@ -754,6 +754,16 @@ pub fn activity_entries() -> Vec<Entry> {
754 false,
754 false,
755 ),
755 ),
756 reaction,
756 reaction,
757 entry(
758 "demo-chat-allhands",
759 Kind::Mention,
760 "demo-allhands-policy",
761 vec![actor(LEA_ID, "Lea Schneider")],
762 "@Dana please read the new vacation policy before Friday.",
763 1,
764 at(0, 9, 0),
765 false,
766 ),
757 entry(
767 entry(
758 "demo-chat-customer-3",
768 "demo-chat-customer-3",
759 Kind::Messages,
769 Kind::Messages,
crates/app-state/src/find_in_chat.rs added +439 −0
@@ -0,0 +1,439 @@
1 use std::collections::HashSet;
2 use std::ops::Range;
3
4 use chatsvc::substrate_search::{MessageFilter, SearchMessage, split_highlights};
5 use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc};
6 use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, SearchHit};
7
8 pub const FIND_IN_CHAT: &str = "Find in chat";
9 pub const FIND_IN_CHANNEL: &str = "Find in channel";
10 pub const EMPTY_HINT: &str = "Find messages and links shared in this chat.";
11 pub const NO_RESULTS_CHAT: &str = "We couldn't find any results in this chat";
12 pub const NO_RESULTS_CHANNEL: &str = "We couldn't find any results in this channel";
13 pub const LOAD_ERROR: &str = "Something went wrong while loading the results.";
14 pub const LOADING: &str = "Fetching Data...";
15 pub const FROM_LABEL: &str = "From";
16 pub const DATE_LABEL: &str = "Date";
17 pub const HAS_ATTACHMENT_LABEL: &str = "Has attachment";
18 pub const MENTIONS_LABEL: &str = "@Mentions";
19 pub const THIS_MONTH: &str = "This month";
20 pub const LAST_MONTH: &str = "Last month";
21 const ORG_PREFIX: &str = "8:orgid:";
22
23 pub fn no_results_with_filters(search_term: &str) -> String {
24 format!("We couldn't find any results for '{search_term}' with the applied filters.")
25 }
26
27 #[derive(Debug, Clone, PartialEq, Eq)]
28 pub struct FindHit {
29 pub message_id: String,
30 pub sent_at: DateTime<Utc>,
31 pub sender_name: String,
32 pub sender_id: Option<String>,
33 pub text: String,
34 pub highlights: Vec<Range<usize>>,
35 pub mentions_me: bool,
36 pub has_attachment: bool,
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 pub enum DateRange {
41 Today,
42 Yesterday,
43 ThisWeek,
44 ThisMonth,
45 }
46
47 impl DateRange {
48 pub const ALL: [DateRange; 4] = [
49 DateRange::Today,
50 DateRange::Yesterday,
51 DateRange::ThisWeek,
52 DateRange::ThisMonth,
53 ];
54
55 pub fn label(self) -> &'static str {
56 match self {
57 DateRange::Today => "Today",
58 DateRange::Yesterday => "Yesterday",
59 DateRange::ThisWeek => "This week",
60 DateRange::ThisMonth => "This month",
61 }
62 }
63
64 pub fn contains(self, date: NaiveDate, today: NaiveDate) -> bool {
65 match self {
66 DateRange::Today => date == today,
67 DateRange::Yesterday => Some(date) == today.pred_opt(),
68 DateRange::ThisWeek => {
69 let week_start =
70 today - Duration::days(i64::from(today.weekday().num_days_from_monday()));
71 date >= week_start && date <= today
72 }
73 DateRange::ThisMonth => date.year() == today.year() && date.month() == today.month(),
74 }
75 }
76 }
77
78 #[derive(Debug, Clone, PartialEq, Eq)]
79 pub struct Sender {
80 pub user_id: String,
81 pub name: String,
82 }
83
84 #[derive(Debug, Clone, Default, PartialEq, Eq)]
85 pub struct FindFilters {
86 pub from: Option<Sender>,
87 pub date: Option<DateRange>,
88 pub has_attachment: bool,
89 pub mentions_me: bool,
90 }
91
92 impl FindFilters {
93 pub fn is_active(&self) -> bool {
94 self.from.is_some() || self.date.is_some() || self.has_attachment || self.mentions_me
95 }
96
97 pub fn admits(&self, hit: &FindHit, today: NaiveDate, offset: FixedOffset) -> bool {
98 let from_holds = self.from.as_ref().is_none_or(|sender| {
99 hit.sender_id
100 .as_deref()
101 .is_some_and(|sender_id| same_user(sender_id, &sender.user_id))
102 });
103 let date_holds = self.date.is_none_or(|range| {
104 range.contains(hit.sent_at.with_timezone(&offset).date_naive(), today)
105 });
106 from_holds
107 && date_holds
108 && (!self.has_attachment || hit.has_attachment)
109 && (!self.mentions_me || hit.mentions_me)
110 }
111
112 pub fn server_filters(&self, thread_id: &str) -> Vec<MessageFilter> {
113 let mut filters = vec![MessageFilter::InChat {
114 thread_id: thread_id.to_owned(),
115 }];
116 if let Some(sender) = &self.from {
117 filters.push(MessageFilter::FromSender {
118 mri: user_mri(&sender.user_id),
119 });
120 }
121 if self.has_attachment {
122 filters.push(MessageFilter::HasAttachment);
123 }
124 if self.mentions_me {
125 filters.push(MessageFilter::MentionsMe);
126 }
127 filters
128 }
129 }
130
131 fn bare_user_id(user_id: &str) -> String {
132 user_id
133 .strip_prefix(ORG_PREFIX)
134 .unwrap_or(user_id)
135 .to_ascii_lowercase()
136 }
137
138 pub fn same_user(first: &str, second: &str) -> bool {
139 bare_user_id(first) == bare_user_id(second)
140 }
141
142 pub fn user_mri(user_id: &str) -> String {
143 if user_id.contains(':') {
144 user_id.to_owned()
145 } else {
146 format!("{ORG_PREFIX}{user_id}")
147 }
148 }
149
150 fn parse_local_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
151 let mut text = String::with_capacity(snippet.len());
152 let mut highlights = Vec::new();
153 let mut start = None;
154 for character in snippet.chars() {
155 match character {
156 HIGHLIGHT_START => start = Some(text.len()),
157 HIGHLIGHT_END => {
158 if let Some(begin) = start.take() {
159 highlights.push(begin..text.len());
160 }
161 }
162 _ => text.push(character),
163 }
164 }
165 (text, highlights)
166 }
167
168 pub fn from_local(hit: &SearchHit, record: Option<&MessageRecord>, my_id: Option<&str>) -> FindHit {
169 let (text, highlights) = parse_local_snippet(&hit.snippet);
170 FindHit {
171 message_id: hit.message_id.clone(),
172 sent_at: hit.created_at,
173 sender_name: hit.sender_name.clone().unwrap_or_default(),
174 sender_id: record.and_then(|record| record.sender_id.clone()),
175 text,
176 highlights,
177 mentions_me: record.is_some_and(|record| mentions_user(record, my_id)),
178 has_attachment: record.is_some_and(has_attachment),
179 }
180 }
181
182 pub fn from_record(record: &MessageRecord, my_id: Option<&str>) -> FindHit {
183 FindHit {
184 message_id: record.message_id.clone(),
185 sent_at: record.created_at,
186 sender_name: record.sender_name.clone().unwrap_or_default(),
187 sender_id: record.sender_id.clone(),
188 text: teams_core::preview_text(&record.body_html).unwrap_or_default(),
189 highlights: Vec::new(),
190 mentions_me: mentions_user(record, my_id),
191 has_attachment: has_attachment(record),
192 }
193 }
194
195 pub fn from_server(message: &SearchMessage) -> Option<FindHit> {
196 let sent_at = message.sent_at?;
197 let highlighted = split_highlights(
198 message
199 .highlighted_summary
200 .as_deref()
201 .unwrap_or(&message.preview),
202 );
203 Some(FindHit {
204 message_id: message.message_id.clone(),
205 sent_at,
206 sender_name: message.sender_name.clone().unwrap_or_default(),
207 sender_id: message.sender_mri.clone(),
208 text: highlighted.text,
209 highlights: highlighted.hits,
210 mentions_me: message.is_mentioned,
211 has_attachment: message.has_attachments,
212 })
213 }
214
215 fn mentions_user(record: &MessageRecord, my_id: Option<&str>) -> bool {
216 let Some(my_id) = my_id else {
217 return false;
218 };
219 teams_core::mentions(record).iter().any(|mention| {
220 mention
221 .user_id
222 .as_deref()
223 .is_some_and(|user_id| same_user(user_id, my_id))
224 })
225 }
226
227 fn has_attachment(record: &MessageRecord) -> bool {
228 !teams_core::files(record).is_empty() || !teams_core::images(record).is_empty()
229 }
230
231 pub fn merge(local: Vec<FindHit>, server: Vec<FindHit>) -> Vec<FindHit> {
232 let mut seen = HashSet::new();
233 let mut hits: Vec<FindHit> = local
234 .into_iter()
235 .chain(server)
236 .filter(|hit| seen.insert(hit.message_id.clone()))
237 .collect();
238 hits.sort_by(|first, second| {
239 second
240 .sent_at
241 .cmp(&first.sent_at)
242 .then_with(|| second.message_id.cmp(&first.message_id))
243 });
244 hits
245 }
246
247 pub fn month_label(date: NaiveDate, today: NaiveDate) -> String {
248 let months = |date: NaiveDate| date.year() * 12 + date.month0() as i32;
249 match months(today) - months(date) {
250 0 => THIS_MONTH.to_owned(),
251 1 => LAST_MONTH.to_owned(),
252 _ => date.format("%B %Y").to_string(),
253 }
254 }
255
256 #[derive(Debug, Clone, PartialEq, Eq)]
257 pub struct MonthGroup {
258 pub label: String,
259 pub hits: Vec<FindHit>,
260 }
261
262 pub fn group_by_month(hits: &[FindHit], today: NaiveDate, offset: FixedOffset) -> Vec<MonthGroup> {
263 let mut groups: Vec<MonthGroup> = Vec::new();
264 for hit in hits {
265 let label = month_label(hit.sent_at.with_timezone(&offset).date_naive(), today);
266 match groups.last_mut() {
267 Some(group) if group.label == label => group.hits.push(hit.clone()),
268 _ => groups.push(MonthGroup {
269 label,
270 hits: vec![hit.clone()],
271 }),
272 }
273 }
274 groups
275 }
276
277 pub fn step_index(current: Option<usize>, count: usize, backwards: bool) -> Option<usize> {
278 if count == 0 {
279 return None;
280 }
281 Some(match (current, backwards) {
282 (None, false) => 0,
283 (None, true) => count - 1,
284 (Some(index), false) => (index + 1) % count,
285 (Some(index), true) => (index + count - 1) % count,
286 })
287 }
288
289 #[cfg(test)]
290 mod tests {
291 use chrono::TimeZone;
292
293 use super::*;
294
295 fn utc() -> FixedOffset {
296 FixedOffset::east_opt(0).unwrap()
297 }
298
299 fn hit(message_id: &str, day: u32, month: u32) -> FindHit {
300 FindHit {
301 message_id: message_id.into(),
302 sent_at: Utc.with_ymd_and_hms(2026, month, day, 10, 0, 0).unwrap(),
303 sender_name: "Lea".into(),
304 sender_id: Some("8:orgid:ABC".into()),
305 text: message_id.into(),
306 highlights: Vec::new(),
307 mentions_me: false,
308 has_attachment: false,
309 }
310 }
311
312 fn today() -> NaiveDate {
313 NaiveDate::from_ymd_opt(2026, 10, 17).unwrap()
314 }
315
316 #[test]
317 fn merge_dedupes_by_message_id_and_sorts_newest_first() {
318 let local = vec![hit("a", 1, 10), hit("b", 5, 10)];
319 let mut server_copy = hit("a", 1, 10);
320 server_copy.text = "server".into();
321 let server = vec![server_copy, hit("c", 3, 10)];
322 let merged = merge(local, server);
323 let ids: Vec<&str> = merged.iter().map(|hit| hit.message_id.as_str()).collect();
324 assert_eq!(ids, ["b", "c", "a"]);
325 assert_eq!(merged[2].text, "a");
326 }
327
328 #[test]
329 fn groups_follow_teams_month_labels() {
330 let hits = vec![
331 hit("a", 16, 10),
332 hit("b", 2, 10),
333 hit("c", 30, 9),
334 hit("d", 1, 7),
335 ];
336 let groups = group_by_month(&hits, today(), utc());
337 let labels: Vec<(&str, usize)> = groups
338 .iter()
339 .map(|group| (group.label.as_str(), group.hits.len()))
340 .collect();
341 assert_eq!(labels, [(THIS_MONTH, 2), (LAST_MONTH, 1), ("July 2026", 1)]);
342 assert_eq!(
343 month_label(NaiveDate::from_ymd_opt(2025, 10, 3).unwrap(), today()),
344 "October 2025"
345 );
346 }
347
348 #[test]
349 fn date_ranges_use_the_local_calendar() {
350 let saturday = today();
351 let day = |day: u32| NaiveDate::from_ymd_opt(2026, 10, day).unwrap();
352 assert!(DateRange::Today.contains(day(17), saturday));
353 assert!(DateRange::Yesterday.contains(day(16), saturday));
354 assert!(!DateRange::Yesterday.contains(day(17), saturday));
355 assert!(DateRange::ThisWeek.contains(day(12), saturday));
356 assert!(!DateRange::ThisWeek.contains(day(11), saturday));
357 assert!(DateRange::ThisMonth.contains(day(1), saturday));
358 assert!(
359 !DateRange::ThisMonth.contains(NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(), saturday)
360 );
361 }
362
363 #[test]
364 fn filters_admit_matching_hits_only() {
365 let mut matching = hit("a", 17, 10);
366 matching.has_attachment = true;
367 matching.mentions_me = true;
368 let plain = hit("b", 1, 10);
369 let filters = FindFilters {
370 from: Some(Sender {
371 user_id: "abc".into(),
372 name: "Lea".into(),
373 }),
374 date: Some(DateRange::Today),
375 has_attachment: true,
376 mentions_me: true,
377 };
378 assert!(filters.admits(&matching, today(), utc()));
379 assert!(!filters.admits(&plain, today(), utc()));
380 assert!(FindFilters::default().admits(&plain, today(), utc()));
381 let other_sender = FindFilters {
382 from: Some(Sender {
383 user_id: "8:orgid:other".into(),
384 name: "Other".into(),
385 }),
386 ..Default::default()
387 };
388 assert!(!other_sender.admits(&matching, today(), utc()));
389 }
390
391 #[test]
392 fn server_filters_scope_to_the_chat_and_map_chips() {
393 let filters = FindFilters {
394 from: Some(Sender {
395 user_id: "abc".into(),
396 name: "Lea".into(),
397 }),
398 date: Some(DateRange::Today),
399 has_attachment: true,
400 mentions_me: true,
401 };
402 assert_eq!(
403 filters.server_filters("19:chat@thread.v2"),
404 [
405 MessageFilter::InChat {
406 thread_id: "19:chat@thread.v2".into()
407 },
408 MessageFilter::FromSender {
409 mri: "8:orgid:abc".into()
410 },
411 MessageFilter::HasAttachment,
412 MessageFilter::MentionsMe,
413 ]
414 );
415 }
416
417 #[test]
418 fn local_snippet_markers_become_highlight_ranges() {
419 let search_hit = SearchHit {
420 conversation_id: "c".into(),
421 message_id: "m".into(),
422 sender_name: Some("Lea".into()),
423 created_at: Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap(),
424 snippet: format!("access is {HIGHLIGHT_START}ready{HIGHLIGHT_END} now"),
425 };
426 let found = from_local(&search_hit, None, None);
427 assert_eq!(found.text, "access is ready now");
428 assert_eq!(&found.text[found.highlights[0].clone()], "ready");
429 }
430
431 #[test]
432 fn stepping_wraps_in_both_directions() {
433 assert_eq!(step_index(None, 0, false), None);
434 assert_eq!(step_index(None, 3, false), Some(0));
435 assert_eq!(step_index(None, 3, true), Some(2));
436 assert_eq!(step_index(Some(2), 3, false), Some(0));
437 assert_eq!(step_index(Some(0), 3, true), Some(2));
438 }
439 }
@@ -0,0 +1,439 @@
1use std::collections::HashSet;
2use std::ops::Range;
3
4use chatsvc::substrate_search::{MessageFilter, SearchMessage, split_highlights};
5use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc};
6use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, SearchHit};
7
8pub const FIND_IN_CHAT: &str = "Find in chat";
9pub const FIND_IN_CHANNEL: &str = "Find in channel";
10pub const EMPTY_HINT: &str = "Find messages and links shared in this chat.";
11pub const NO_RESULTS_CHAT: &str = "We couldn't find any results in this chat";
12pub const NO_RESULTS_CHANNEL: &str = "We couldn't find any results in this channel";
13pub const LOAD_ERROR: &str = "Something went wrong while loading the results.";
14pub const LOADING: &str = "Fetching Data...";
15pub const FROM_LABEL: &str = "From";
16pub const DATE_LABEL: &str = "Date";
17pub const HAS_ATTACHMENT_LABEL: &str = "Has attachment";
18pub const MENTIONS_LABEL: &str = "@Mentions";
19pub const THIS_MONTH: &str = "This month";
20pub const LAST_MONTH: &str = "Last month";
21const ORG_PREFIX: &str = "8:orgid:";
22
23pub fn no_results_with_filters(search_term: &str) -> String {
24 format!("We couldn't find any results for '{search_term}' with the applied filters.")
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct FindHit {
29 pub message_id: String,
30 pub sent_at: DateTime<Utc>,
31 pub sender_name: String,
32 pub sender_id: Option<String>,
33 pub text: String,
34 pub highlights: Vec<Range<usize>>,
35 pub mentions_me: bool,
36 pub has_attachment: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum DateRange {
41 Today,
42 Yesterday,
43 ThisWeek,
44 ThisMonth,
45}
46
47impl DateRange {
48 pub const ALL: [DateRange; 4] = [
49 DateRange::Today,
50 DateRange::Yesterday,
51 DateRange::ThisWeek,
52 DateRange::ThisMonth,
53 ];
54
55 pub fn label(self) -> &'static str {
56 match self {
57 DateRange::Today => "Today",
58 DateRange::Yesterday => "Yesterday",
59 DateRange::ThisWeek => "This week",
60 DateRange::ThisMonth => "This month",
61 }
62 }
63
64 pub fn contains(self, date: NaiveDate, today: NaiveDate) -> bool {
65 match self {
66 DateRange::Today => date == today,
67 DateRange::Yesterday => Some(date) == today.pred_opt(),
68 DateRange::ThisWeek => {
69 let week_start =
70 today - Duration::days(i64::from(today.weekday().num_days_from_monday()));
71 date >= week_start && date <= today
72 }
73 DateRange::ThisMonth => date.year() == today.year() && date.month() == today.month(),
74 }
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Sender {
80 pub user_id: String,
81 pub name: String,
82}
83
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct FindFilters {
86 pub from: Option<Sender>,
87 pub date: Option<DateRange>,
88 pub has_attachment: bool,
89 pub mentions_me: bool,
90}
91
92impl FindFilters {
93 pub fn is_active(&self) -> bool {
94 self.from.is_some() || self.date.is_some() || self.has_attachment || self.mentions_me
95 }
96
97 pub fn admits(&self, hit: &FindHit, today: NaiveDate, offset: FixedOffset) -> bool {
98 let from_holds = self.from.as_ref().is_none_or(|sender| {
99 hit.sender_id
100 .as_deref()
101 .is_some_and(|sender_id| same_user(sender_id, &sender.user_id))
102 });
103 let date_holds = self.date.is_none_or(|range| {
104 range.contains(hit.sent_at.with_timezone(&offset).date_naive(), today)
105 });
106 from_holds
107 && date_holds
108 && (!self.has_attachment || hit.has_attachment)
109 && (!self.mentions_me || hit.mentions_me)
110 }
111
112 pub fn server_filters(&self, thread_id: &str) -> Vec<MessageFilter> {
113 let mut filters = vec![MessageFilter::InChat {
114 thread_id: thread_id.to_owned(),
115 }];
116 if let Some(sender) = &self.from {
117 filters.push(MessageFilter::FromSender {
118 mri: user_mri(&sender.user_id),
119 });
120 }
121 if self.has_attachment {
122 filters.push(MessageFilter::HasAttachment);
123 }
124 if self.mentions_me {
125 filters.push(MessageFilter::MentionsMe);
126 }
127 filters
128 }
129}
130
131fn bare_user_id(user_id: &str) -> String {
132 user_id
133 .strip_prefix(ORG_PREFIX)
134 .unwrap_or(user_id)
135 .to_ascii_lowercase()
136}
137
138pub fn same_user(first: &str, second: &str) -> bool {
139 bare_user_id(first) == bare_user_id(second)
140}
141
142pub fn user_mri(user_id: &str) -> String {
143 if user_id.contains(':') {
144 user_id.to_owned()
145 } else {
146 format!("{ORG_PREFIX}{user_id}")
147 }
148}
149
150fn parse_local_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
151 let mut text = String::with_capacity(snippet.len());
152 let mut highlights = Vec::new();
153 let mut start = None;
154 for character in snippet.chars() {
155 match character {
156 HIGHLIGHT_START => start = Some(text.len()),
157 HIGHLIGHT_END => {
158 if let Some(begin) = start.take() {
159 highlights.push(begin..text.len());
160 }
161 }
162 _ => text.push(character),
163 }
164 }
165 (text, highlights)
166}
167
168pub fn from_local(hit: &SearchHit, record: Option<&MessageRecord>, my_id: Option<&str>) -> FindHit {
169 let (text, highlights) = parse_local_snippet(&hit.snippet);
170 FindHit {
171 message_id: hit.message_id.clone(),
172 sent_at: hit.created_at,
173 sender_name: hit.sender_name.clone().unwrap_or_default(),
174 sender_id: record.and_then(|record| record.sender_id.clone()),
175 text,
176 highlights,
177 mentions_me: record.is_some_and(|record| mentions_user(record, my_id)),
178 has_attachment: record.is_some_and(has_attachment),
179 }
180}
181
182pub fn from_record(record: &MessageRecord, my_id: Option<&str>) -> FindHit {
183 FindHit {
184 message_id: record.message_id.clone(),
185 sent_at: record.created_at,
186 sender_name: record.sender_name.clone().unwrap_or_default(),
187 sender_id: record.sender_id.clone(),
188 text: teams_core::preview_text(&record.body_html).unwrap_or_default(),
189 highlights: Vec::new(),
190 mentions_me: mentions_user(record, my_id),
191 has_attachment: has_attachment(record),
192 }
193}
194
195pub fn from_server(message: &SearchMessage) -> Option<FindHit> {
196 let sent_at = message.sent_at?;
197 let highlighted = split_highlights(
198 message
199 .highlighted_summary
200 .as_deref()
201 .unwrap_or(&message.preview),
202 );
203 Some(FindHit {
204 message_id: message.message_id.clone(),
205 sent_at,
206 sender_name: message.sender_name.clone().unwrap_or_default(),
207 sender_id: message.sender_mri.clone(),
208 text: highlighted.text,
209 highlights: highlighted.hits,
210 mentions_me: message.is_mentioned,
211 has_attachment: message.has_attachments,
212 })
213}
214
215fn mentions_user(record: &MessageRecord, my_id: Option<&str>) -> bool {
216 let Some(my_id) = my_id else {
217 return false;
218 };
219 teams_core::mentions(record).iter().any(|mention| {
220 mention
221 .user_id
222 .as_deref()
223 .is_some_and(|user_id| same_user(user_id, my_id))
224 })
225}
226
227fn has_attachment(record: &MessageRecord) -> bool {
228 !teams_core::files(record).is_empty() || !teams_core::images(record).is_empty()
229}
230
231pub fn merge(local: Vec<FindHit>, server: Vec<FindHit>) -> Vec<FindHit> {
232 let mut seen = HashSet::new();
233 let mut hits: Vec<FindHit> = local
234 .into_iter()
235 .chain(server)
236 .filter(|hit| seen.insert(hit.message_id.clone()))
237 .collect();
238 hits.sort_by(|first, second| {
239 second
240 .sent_at
241 .cmp(&first.sent_at)
242 .then_with(|| second.message_id.cmp(&first.message_id))
243 });
244 hits
245}
246
247pub fn month_label(date: NaiveDate, today: NaiveDate) -> String {
248 let months = |date: NaiveDate| date.year() * 12 + date.month0() as i32;
249 match months(today) - months(date) {
250 0 => THIS_MONTH.to_owned(),
251 1 => LAST_MONTH.to_owned(),
252 _ => date.format("%B %Y").to_string(),
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct MonthGroup {
258 pub label: String,
259 pub hits: Vec<FindHit>,
260}
261
262pub fn group_by_month(hits: &[FindHit], today: NaiveDate, offset: FixedOffset) -> Vec<MonthGroup> {
263 let mut groups: Vec<MonthGroup> = Vec::new();
264 for hit in hits {
265 let label = month_label(hit.sent_at.with_timezone(&offset).date_naive(), today);
266 match groups.last_mut() {
267 Some(group) if group.label == label => group.hits.push(hit.clone()),
268 _ => groups.push(MonthGroup {
269 label,
270 hits: vec![hit.clone()],
271 }),
272 }
273 }
274 groups
275}
276
277pub fn step_index(current: Option<usize>, count: usize, backwards: bool) -> Option<usize> {
278 if count == 0 {
279 return None;
280 }
281 Some(match (current, backwards) {
282 (None, false) => 0,
283 (None, true) => count - 1,
284 (Some(index), false) => (index + 1) % count,
285 (Some(index), true) => (index + count - 1) % count,
286 })
287}
288
289#[cfg(test)]
290mod tests {
291 use chrono::TimeZone;
292
293 use super::*;
294
295 fn utc() -> FixedOffset {
296 FixedOffset::east_opt(0).unwrap()
297 }
298
299 fn hit(message_id: &str, day: u32, month: u32) -> FindHit {
300 FindHit {
301 message_id: message_id.into(),
302 sent_at: Utc.with_ymd_and_hms(2026, month, day, 10, 0, 0).unwrap(),
303 sender_name: "Lea".into(),
304 sender_id: Some("8:orgid:ABC".into()),
305 text: message_id.into(),
306 highlights: Vec::new(),
307 mentions_me: false,
308 has_attachment: false,
309 }
310 }
311
312 fn today() -> NaiveDate {
313 NaiveDate::from_ymd_opt(2026, 10, 17).unwrap()
314 }
315
316 #[test]
317 fn merge_dedupes_by_message_id_and_sorts_newest_first() {
318 let local = vec![hit("a", 1, 10), hit("b", 5, 10)];
319 let mut server_copy = hit("a", 1, 10);
320 server_copy.text = "server".into();
321 let server = vec![server_copy, hit("c", 3, 10)];
322 let merged = merge(local, server);
323 let ids: Vec<&str> = merged.iter().map(|hit| hit.message_id.as_str()).collect();
324 assert_eq!(ids, ["b", "c", "a"]);
325 assert_eq!(merged[2].text, "a");
326 }
327
328 #[test]
329 fn groups_follow_teams_month_labels() {
330 let hits = vec![
331 hit("a", 16, 10),
332 hit("b", 2, 10),
333 hit("c", 30, 9),
334 hit("d", 1, 7),
335 ];
336 let groups = group_by_month(&hits, today(), utc());
337 let labels: Vec<(&str, usize)> = groups
338 .iter()
339 .map(|group| (group.label.as_str(), group.hits.len()))
340 .collect();
341 assert_eq!(labels, [(THIS_MONTH, 2), (LAST_MONTH, 1), ("July 2026", 1)]);
342 assert_eq!(
343 month_label(NaiveDate::from_ymd_opt(2025, 10, 3).unwrap(), today()),
344 "October 2025"
345 );
346 }
347
348 #[test]
349 fn date_ranges_use_the_local_calendar() {
350 let saturday = today();
351 let day = |day: u32| NaiveDate::from_ymd_opt(2026, 10, day).unwrap();
352 assert!(DateRange::Today.contains(day(17), saturday));
353 assert!(DateRange::Yesterday.contains(day(16), saturday));
354 assert!(!DateRange::Yesterday.contains(day(17), saturday));
355 assert!(DateRange::ThisWeek.contains(day(12), saturday));
356 assert!(!DateRange::ThisWeek.contains(day(11), saturday));
357 assert!(DateRange::ThisMonth.contains(day(1), saturday));
358 assert!(
359 !DateRange::ThisMonth.contains(NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(), saturday)
360 );
361 }
362
363 #[test]
364 fn filters_admit_matching_hits_only() {
365 let mut matching = hit("a", 17, 10);
366 matching.has_attachment = true;
367 matching.mentions_me = true;
368 let plain = hit("b", 1, 10);
369 let filters = FindFilters {
370 from: Some(Sender {
371 user_id: "abc".into(),
372 name: "Lea".into(),
373 }),
374 date: Some(DateRange::Today),
375 has_attachment: true,
376 mentions_me: true,
377 };
378 assert!(filters.admits(&matching, today(), utc()));
379 assert!(!filters.admits(&plain, today(), utc()));
380 assert!(FindFilters::default().admits(&plain, today(), utc()));
381 let other_sender = FindFilters {
382 from: Some(Sender {
383 user_id: "8:orgid:other".into(),
384 name: "Other".into(),
385 }),
386 ..Default::default()
387 };
388 assert!(!other_sender.admits(&matching, today(), utc()));
389 }
390
391 #[test]
392 fn server_filters_scope_to_the_chat_and_map_chips() {
393 let filters = FindFilters {
394 from: Some(Sender {
395 user_id: "abc".into(),
396 name: "Lea".into(),
397 }),
398 date: Some(DateRange::Today),
399 has_attachment: true,
400 mentions_me: true,
401 };
402 assert_eq!(
403 filters.server_filters("19:chat@thread.v2"),
404 [
405 MessageFilter::InChat {
406 thread_id: "19:chat@thread.v2".into()
407 },
408 MessageFilter::FromSender {
409 mri: "8:orgid:abc".into()
410 },
411 MessageFilter::HasAttachment,
412 MessageFilter::MentionsMe,
413 ]
414 );
415 }
416
417 #[test]
418 fn local_snippet_markers_become_highlight_ranges() {
419 let search_hit = SearchHit {
420 conversation_id: "c".into(),
421 message_id: "m".into(),
422 sender_name: Some("Lea".into()),
423 created_at: Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap(),
424 snippet: format!("access is {HIGHLIGHT_START}ready{HIGHLIGHT_END} now"),
425 };
426 let found = from_local(&search_hit, None, None);
427 assert_eq!(found.text, "access is ready now");
428 assert_eq!(&found.text[found.highlights[0].clone()], "ready");
429 }
430
431 #[test]
432 fn stepping_wraps_in_both_directions() {
433 assert_eq!(step_index(None, 0, false), None);
434 assert_eq!(step_index(None, 3, false), Some(0));
435 assert_eq!(step_index(None, 3, true), Some(2));
436 assert_eq!(step_index(Some(2), 3, false), Some(0));
437 assert_eq!(step_index(Some(0), 3, true), Some(2));
438 }
439}
crates/app-state/src/lib.rs +2 −0
@@ -11,6 +11,8 @@ pub mod card_refresh;
11 11 pub mod card_state;
12 12 pub mod channel_menu;
13 13 pub mod chat_actions;
14 pub mod chat_filter;
15 pub mod find_in_chat;
14 16 pub mod chat_members;
15 17 pub mod connection_banner;
16 18 pub mod data;
@@ -11,6 +11,8 @@ pub mod card_refresh;
11pub mod card_state;
11pub mod card_state;
12pub mod channel_menu;
12pub mod channel_menu;
13pub mod chat_actions;
13pub mod chat_actions;
14pub mod chat_filter;
15pub mod find_in_chat;
14pub mod chat_members;
16pub mod chat_members;
15pub mod connection_banner;
17pub mod connection_banner;
16pub mod data;
18pub mod data;
crates/app/src/layout_guard.rs +54 −2
@@ -186,6 +186,9 @@ mod frames {
186 186 CHANNEL_DETAILS_TAG,
187 187 };
188 188 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
189 use crate::views::find_panel::{
190 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
191 };
189 192 use crate::views::message_row::BUBBLE_TAGS;
190 193 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
191 194 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -195,10 +198,14 @@ mod frames {
195 198 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
196 199 };
197 200 use crate::views::shortcuts::{
198 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
201 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
202 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
199 203 };
200 204 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
201 205 use crate::views::sidebar::chat_row_selector;
206 use crate::views::sidebar::chat_filter_bar::{
207 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
208 };
202 209 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
203 210 use crate::views::widgets::{
204 211 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
@@ -234,6 +241,14 @@ mod frames {
234 241 "shell/islands/main/call-controls/leave",
235 242 ];
236 243 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
244 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
245 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
246 const FIND_TAGS: &[&str] = &[
247 FIND_PANEL_TAG,
248 FIND_DIVIDER_TAG,
249 FIND_INPUT_TAG,
250 FIND_RESULTS_TAG,
251 ];
237 252 const CALLS_TAGS: &[&str] = &[
238 253 "shell/islands/sidebar/calls-actions",
239 254 "shell/islands/sidebar/calls-actions/meet-now",
@@ -574,6 +589,9 @@ mod frames {
574 589 .iter()
575 590 .chain(CALL_GUARDED)
576 591 .chain(CALLS_TAGS)
592 .chain(CHAT_FILTER_TAGS)
593 .chain(CHAT_FILTER_OPEN_TAGS)
594 .chain(FIND_TAGS)
577 595 .chain(PREJOIN_TAGS)
578 596 .chain(SHARE_GUARDED)
579 597 .chain(CONSULT_GUARDED)
@@ -784,7 +802,26 @@ mod frames {
784 802 size: size(px(width), px(height)),
785 803 };
786 804 let screens = [
787 Screen::Tab("chats", None),
805 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
806 Screen::Tab(
807 "chat-filter",
808 Some(|visual| {
809 visual.dispatch_action(OpenChatsTab);
810 visual.dispatch_action(OpenChatFilter);
811 visual.dispatch_action(FilterMutedChats);
812 visual.run_until_parked();
813 visual.simulate_input("zzz");
814 }),
815 ),
816 Screen::Tab(
817 "find",
818 Some(|visual| {
819 visual.dispatch_action(OpenChatsTab);
820 visual.dispatch_action(FindInChat);
821 visual.run_until_parked();
822 visual.simulate_input("access");
823 }),
824 ),
788 825 Screen::Tab(
789 826 "activity",
790 827 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -917,6 +954,12 @@ mod frames {
917 954 expected.push(MENU);
918 955 }
919 956 match screen_name {
957 "chats" => expected.extend(CHAT_FILTER_TAGS),
958 "chat-filter" => {
959 expected.extend(CHAT_FILTER_TAGS);
960 expected.extend(CHAT_FILTER_OPEN_TAGS);
961 }
962 "find" => expected.extend(FIND_TAGS),
920 963 "calls" => expected.extend(CALLS_TAGS),
921 964 "agents" => expected.push(AGENTS_LIST),
922 965 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -956,6 +999,15 @@ mod frames {
956 999 })
957 1000 });
958 1001 }
1002 if screen_name == "find" {
1003 visual.dispatch_action(gpui_kit::component::input::Escape);
1004 visual.run_until_parked();
1005 }
1006 if screen_name == "chat-filter" {
1007 visual.dispatch_action(ClearChatFilters);
1008 visual.dispatch_action(OpenChatFilter);
1009 visual.run_until_parked();
1010 }
959 1011 if screen_name == "prejoin" {
960 1012 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
961 1013 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
@@ -186,6 +186,9 @@ mod frames {
186 CHANNEL_DETAILS_TAG,
186 CHANNEL_DETAILS_TAG,
187 };
187 };
188 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
188 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
189 use crate::views::find_panel::{
190 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
191 };
189 use crate::views::message_row::BUBBLE_TAGS;
192 use crate::views::message_row::BUBBLE_TAGS;
190 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
193 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
191 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
194 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -195,10 +198,14 @@ mod frames {
195 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
198 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
196 };
199 };
197 use crate::views::shortcuts::{
200 use crate::views::shortcuts::{
198 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
201 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
202 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
199 };
203 };
200 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
204 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
201 use crate::views::sidebar::chat_row_selector;
205 use crate::views::sidebar::chat_row_selector;
206 use crate::views::sidebar::chat_filter_bar::{
207 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
208 };
202 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
209 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
203 use crate::views::widgets::{
210 use crate::views::widgets::{
204 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
211 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
@@ -234,6 +241,14 @@ mod frames {
234 "shell/islands/main/call-controls/leave",
241 "shell/islands/main/call-controls/leave",
235 ];
242 ];
236 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
243 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
244 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
245 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
246 const FIND_TAGS: &[&str] = &[
247 FIND_PANEL_TAG,
248 FIND_DIVIDER_TAG,
249 FIND_INPUT_TAG,
250 FIND_RESULTS_TAG,
251 ];
237 const CALLS_TAGS: &[&str] = &[
252 const CALLS_TAGS: &[&str] = &[
238 "shell/islands/sidebar/calls-actions",
253 "shell/islands/sidebar/calls-actions",
239 "shell/islands/sidebar/calls-actions/meet-now",
254 "shell/islands/sidebar/calls-actions/meet-now",
@@ -574,6 +589,9 @@ mod frames {
574 .iter()
589 .iter()
575 .chain(CALL_GUARDED)
590 .chain(CALL_GUARDED)
576 .chain(CALLS_TAGS)
591 .chain(CALLS_TAGS)
592 .chain(CHAT_FILTER_TAGS)
593 .chain(CHAT_FILTER_OPEN_TAGS)
594 .chain(FIND_TAGS)
577 .chain(PREJOIN_TAGS)
595 .chain(PREJOIN_TAGS)
578 .chain(SHARE_GUARDED)
596 .chain(SHARE_GUARDED)
579 .chain(CONSULT_GUARDED)
597 .chain(CONSULT_GUARDED)
@@ -784,7 +802,26 @@ mod frames {
784 size: size(px(width), px(height)),
802 size: size(px(width), px(height)),
785 };
803 };
786 let screens = [
804 let screens = [
787 Screen::Tab("chats", None),
805 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
806 Screen::Tab(
807 "chat-filter",
808 Some(|visual| {
809 visual.dispatch_action(OpenChatsTab);
810 visual.dispatch_action(OpenChatFilter);
811 visual.dispatch_action(FilterMutedChats);
812 visual.run_until_parked();
813 visual.simulate_input("zzz");
814 }),
815 ),
816 Screen::Tab(
817 "find",
818 Some(|visual| {
819 visual.dispatch_action(OpenChatsTab);
820 visual.dispatch_action(FindInChat);
821 visual.run_until_parked();
822 visual.simulate_input("access");
823 }),
824 ),
788 Screen::Tab(
825 Screen::Tab(
789 "activity",
826 "activity",
790 Some(|visual| visual.dispatch_action(OpenActivity)),
827 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -917,6 +954,12 @@ mod frames {
917 expected.push(MENU);
954 expected.push(MENU);
918 }
955 }
919 match screen_name {
956 match screen_name {
957 "chats" => expected.extend(CHAT_FILTER_TAGS),
958 "chat-filter" => {
959 expected.extend(CHAT_FILTER_TAGS);
960 expected.extend(CHAT_FILTER_OPEN_TAGS);
961 }
962 "find" => expected.extend(FIND_TAGS),
920 "calls" => expected.extend(CALLS_TAGS),
963 "calls" => expected.extend(CALLS_TAGS),
921 "agents" => expected.push(AGENTS_LIST),
964 "agents" => expected.push(AGENTS_LIST),
922 "prejoin" => expected.extend(PREJOIN_TAGS),
965 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -956,6 +999,15 @@ mod frames {
956 })
999 })
957 });
1000 });
958 }
1001 }
1002 if screen_name == "find" {
1003 visual.dispatch_action(gpui_kit::component::input::Escape);
1004 visual.run_until_parked();
1005 }
1006 if screen_name == "chat-filter" {
1007 visual.dispatch_action(ClearChatFilters);
1008 visual.dispatch_action(OpenChatFilter);
1009 visual.run_until_parked();
1010 }
959 if screen_name == "prejoin" {
1011 if screen_name == "prejoin" {
960 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
1012 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
961 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
1013 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
crates/app/src/views/activity_panel.rs +4 −0
@@ -45,6 +45,10 @@ pub struct ActivityPanel {
45 45 impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
46 46
47 47 impl ActivityPanel {
48 pub fn activity(&self) -> Entity<ActivityCenter> {
49 self.activity.clone()
50 }
51
48 52 pub fn new(
49 53 app: Entity<AppState>,
50 54 activity: Entity<ActivityCenter>,
@@ -45,6 +45,10 @@ pub struct ActivityPanel {
45impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
45impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
46
46
47impl ActivityPanel {
47impl ActivityPanel {
48 pub fn activity(&self) -> Entity<ActivityCenter> {
49 self.activity.clone()
50 }
51
48 pub fn new(
52 pub fn new(
49 app: Entity<AppState>,
53 app: Entity<AppState>,
50 activity: Entity<ActivityCenter>,
54 activity: Entity<ActivityCenter>,
crates/app/src/views/conversation.rs +74 −1
@@ -47,6 +47,7 @@ use super::call_controls::header_call_controls;
47 47 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
48 48 use super::chat_members::members_popover;
49 49 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
50 use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
50 51 use super::group_name::group_name_button;
51 52 use super::message_actions::{Action, DelegateEntry, MessageMenu};
52 53 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
@@ -104,6 +105,7 @@ const HEADER_PADDING: f32 = 20.;
104 105 const HEADER_GAP: f32 = 12.;
105 106 const HEADER_LEAD_SIZE: f32 = 36.;
106 107 const TABS_INLINE_MIN_WIDTH: f32 = 560.;
108 const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
107 109 const TABS_ROW_HEIGHT: f32 = 36.;
108 110 const CHAT_OPEN_LIMIT: usize = 60;
109 111 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -243,6 +245,8 @@ pub struct ConversationView {
243 245 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
244 246 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
245 247 receipt_fade: receipt_fade::ReceiptFade,
248 find_panel: Option<Entity<FindPanel>>,
249 find_subscription: Option<Subscription>,
246 250 _subscriptions: Vec<Subscription>,
247 251 }
248 252
@@ -574,6 +578,8 @@ impl ConversationView {
574 578 agent_runs: Rc::new(RefCell::new(HashMap::new())),
575 579 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
576 580 receipt_fade: receipt_fade::ReceiptFade::default(),
581 find_panel: None,
582 find_subscription: None,
577 583 _subscriptions: subscriptions,
578 584 };
579 585 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -849,6 +855,14 @@ impl ConversationView {
849 855 }
850 856
851 857 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
858 if self
859 .find_panel
860 .as_ref()
861 .is_some_and(|panel| panel.read(cx).selection() != &selection)
862 {
863 self.find_panel = None;
864 self.find_subscription = None;
865 }
852 866 self.stop_typing(cx);
853 867 self.stop_reply_typing(cx);
854 868 self.new_post_open = false;
@@ -3232,6 +3246,51 @@ impl ConversationView {
3232 3246 )
3233 3247 }
3234 3248
3249 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3250 if self.pinned || self.draft_active {
3251 return;
3252 }
3253 let Some(selection) = self
3254 .current
3255 .as_ref()
3256 .map(|current| current.selection.clone())
3257 else {
3258 return;
3259 };
3260 self.channel_details_open = false;
3261 if let Some(panel) = &self.find_panel {
3262 panel.update(cx, |panel, cx| panel.focus(window, cx));
3263 return;
3264 }
3265 let app = self.app.clone();
3266 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3267 let subscription = cx.subscribe_in(
3268 &panel,
3269 window,
3270 move |this, _, event: &FindPanelEvent, window, cx| match event {
3271 FindPanelEvent::Close => this.close_find(window, cx),
3272 FindPanelEvent::Jump(message_id) => {
3273 let (selection, message_id) = (selection.clone(), message_id.clone());
3274 this.app.update(cx, |state, cx| {
3275 state.jump_to_message(selection, message_id, cx)
3276 });
3277 }
3278 },
3279 );
3280 panel.update(cx, |panel, cx| panel.focus(window, cx));
3281 self.find_panel = Some(panel);
3282 self.find_subscription = Some(subscription);
3283 cx.notify();
3284 }
3285
3286 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3287 self.find_panel = None;
3288 self.find_subscription = None;
3289 self.composer
3290 .update(cx, |composer, cx| composer.focus(window, cx));
3291 cx.notify();
3292 }
3293
3235 3294 fn header_width(&self, window: &Window) -> f32 {
3236 3295 match self.header_width.get() {
3237 3296 width if width > 0. => width,
@@ -3671,6 +3730,8 @@ impl Render for ConversationView {
3671 3730 scroller.into_any_element()
3672 3731 };
3673 3732 let channel_details = self.render_channel_details(cx);
3733 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3734 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3674 3735 let content = v_flex()
3675 3736 .relative()
3676 3737 .flex_1()
@@ -3698,12 +3759,24 @@ impl Render for ConversationView {
3698 3759 .child(self.render_drop_overlay(cx));
3699 3760 root.child(
3700 3761 h_flex()
3762 .relative()
3701 3763 .flex_1()
3702 3764 .min_h_0()
3703 3765 .w_full()
3704 3766 .items_stretch()
3705 3767 .child(content)
3706 .children(channel_details),
3768 .children(channel_details)
3769 .children(find_panel.map(|panel| {
3770 div()
3771 .h_full()
3772 .w(px(FIND_PANEL_WIDTH))
3773 .min_w_0()
3774 .flex_shrink(1.)
3775 .when(find_overlays, |slot| {
3776 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3777 })
3778 .child(panel)
3779 })),
3707 3780 )
3708 3781 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3709 3782 if this.reaction_details.is_some() {
@@ -47,6 +47,7 @@ use super::call_controls::header_call_controls;
47use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
47use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
48use super::chat_members::members_popover;
48use super::chat_members::members_popover;
49use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
49use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
50use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
50use super::group_name::group_name_button;
51use super::group_name::group_name_button;
51use super::message_actions::{Action, DelegateEntry, MessageMenu};
52use super::message_actions::{Action, DelegateEntry, MessageMenu};
52use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
53use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
@@ -104,6 +105,7 @@ const HEADER_PADDING: f32 = 20.;
104const HEADER_GAP: f32 = 12.;
105const HEADER_GAP: f32 = 12.;
105const HEADER_LEAD_SIZE: f32 = 36.;
106const HEADER_LEAD_SIZE: f32 = 36.;
106const TABS_INLINE_MIN_WIDTH: f32 = 560.;
107const TABS_INLINE_MIN_WIDTH: f32 = 560.;
108const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
107const TABS_ROW_HEIGHT: f32 = 36.;
109const TABS_ROW_HEIGHT: f32 = 36.;
108const CHAT_OPEN_LIMIT: usize = 60;
110const CHAT_OPEN_LIMIT: usize = 60;
109const CHANNEL_OPEN_LIMIT: usize = 300;
111const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -243,6 +245,8 @@ pub struct ConversationView {
243 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
245 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
244 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
246 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
245 receipt_fade: receipt_fade::ReceiptFade,
247 receipt_fade: receipt_fade::ReceiptFade,
248 find_panel: Option<Entity<FindPanel>>,
249 find_subscription: Option<Subscription>,
246 _subscriptions: Vec<Subscription>,
250 _subscriptions: Vec<Subscription>,
247}
251}
248
252
@@ -574,6 +578,8 @@ impl ConversationView {
574 agent_runs: Rc::new(RefCell::new(HashMap::new())),
578 agent_runs: Rc::new(RefCell::new(HashMap::new())),
575 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
579 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
576 receipt_fade: receipt_fade::ReceiptFade::default(),
580 receipt_fade: receipt_fade::ReceiptFade::default(),
581 find_panel: None,
582 find_subscription: None,
577 _subscriptions: subscriptions,
583 _subscriptions: subscriptions,
578 };
584 };
579 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
585 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -849,6 +855,14 @@ impl ConversationView {
849 }
855 }
850
856
851 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
857 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
858 if self
859 .find_panel
860 .as_ref()
861 .is_some_and(|panel| panel.read(cx).selection() != &selection)
862 {
863 self.find_panel = None;
864 self.find_subscription = None;
865 }
852 self.stop_typing(cx);
866 self.stop_typing(cx);
853 self.stop_reply_typing(cx);
867 self.stop_reply_typing(cx);
854 self.new_post_open = false;
868 self.new_post_open = false;
@@ -3232,6 +3246,51 @@ impl ConversationView {
3232 )
3246 )
3233 }
3247 }
3234
3248
3249 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3250 if self.pinned || self.draft_active {
3251 return;
3252 }
3253 let Some(selection) = self
3254 .current
3255 .as_ref()
3256 .map(|current| current.selection.clone())
3257 else {
3258 return;
3259 };
3260 self.channel_details_open = false;
3261 if let Some(panel) = &self.find_panel {
3262 panel.update(cx, |panel, cx| panel.focus(window, cx));
3263 return;
3264 }
3265 let app = self.app.clone();
3266 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3267 let subscription = cx.subscribe_in(
3268 &panel,
3269 window,
3270 move |this, _, event: &FindPanelEvent, window, cx| match event {
3271 FindPanelEvent::Close => this.close_find(window, cx),
3272 FindPanelEvent::Jump(message_id) => {
3273 let (selection, message_id) = (selection.clone(), message_id.clone());
3274 this.app.update(cx, |state, cx| {
3275 state.jump_to_message(selection, message_id, cx)
3276 });
3277 }
3278 },
3279 );
3280 panel.update(cx, |panel, cx| panel.focus(window, cx));
3281 self.find_panel = Some(panel);
3282 self.find_subscription = Some(subscription);
3283 cx.notify();
3284 }
3285
3286 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3287 self.find_panel = None;
3288 self.find_subscription = None;
3289 self.composer
3290 .update(cx, |composer, cx| composer.focus(window, cx));
3291 cx.notify();
3292 }
3293
3235 fn header_width(&self, window: &Window) -> f32 {
3294 fn header_width(&self, window: &Window) -> f32 {
3236 match self.header_width.get() {
3295 match self.header_width.get() {
3237 width if width > 0. => width,
3296 width if width > 0. => width,
@@ -3671,6 +3730,8 @@ impl Render for ConversationView {
3671 scroller.into_any_element()
3730 scroller.into_any_element()
3672 };
3731 };
3673 let channel_details = self.render_channel_details(cx);
3732 let channel_details = self.render_channel_details(cx);
3733 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3734 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3674 let content = v_flex()
3735 let content = v_flex()
3675 .relative()
3736 .relative()
3676 .flex_1()
3737 .flex_1()
@@ -3698,12 +3759,24 @@ impl Render for ConversationView {
3698 .child(self.render_drop_overlay(cx));
3759 .child(self.render_drop_overlay(cx));
3699 root.child(
3760 root.child(
3700 h_flex()
3761 h_flex()
3762 .relative()
3701 .flex_1()
3763 .flex_1()
3702 .min_h_0()
3764 .min_h_0()
3703 .w_full()
3765 .w_full()
3704 .items_stretch()
3766 .items_stretch()
3705 .child(content)
3767 .child(content)
3706 .children(channel_details),
3768 .children(channel_details)
3769 .children(find_panel.map(|panel| {
3770 div()
3771 .h_full()
3772 .w(px(FIND_PANEL_WIDTH))
3773 .min_w_0()
3774 .flex_shrink(1.)
3775 .when(find_overlays, |slot| {
3776 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3777 })
3778 .child(panel)
3779 })),
3707 )
3780 )
3708 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3781 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3709 if this.reaction_details.is_some() {
3782 if this.reaction_details.is_some() {
crates/app/src/views/conversation/channel_details.rs +2 −0
@@ -144,6 +144,8 @@ impl ConversationView {
144 144 this.channel_details_open = !this.channel_details_open;
145 145 this.pinned_posts_expanded = false;
146 146 if this.channel_details_open {
147 this.find_panel = None;
148 this.find_subscription = None;
147 149 this.refresh_shared_items(cx);
148 150 }
149 151 cx.notify();
@@ -144,6 +144,8 @@ impl ConversationView {
144 this.channel_details_open = !this.channel_details_open;
144 this.channel_details_open = !this.channel_details_open;
145 this.pinned_posts_expanded = false;
145 this.pinned_posts_expanded = false;
146 if this.channel_details_open {
146 if this.channel_details_open {
147 this.find_panel = None;
148 this.find_subscription = None;
147 this.refresh_shared_items(cx);
149 this.refresh_shared_items(cx);
148 }
150 }
149 cx.notify();
151 cx.notify();
crates/app/src/views/find_panel.rs added +664 −0
@@ -0,0 +1,664 @@
1 use std::time::Duration;
2
3 use chrono::{Local, NaiveDate, Offset};
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
7 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9 use gpui_kit::prelude::FluentBuilder as _;
10 use gpui_kit::*;
11 use store::Store;
12 use teams_core::substrate_search::{QueryRequest, QueryResults, QueryScope, SearchSession};
13
14 use super::widgets::icon;
15 use crate::app_state::{AppState, Selection};
16 use crate::find_in_chat::{
17 DATE_LABEL, DateRange, EMPTY_HINT, FIND_IN_CHANNEL, FIND_IN_CHAT, FROM_LABEL, FindFilters,
18 FindHit, HAS_ATTACHMENT_LABEL, LOAD_ERROR, LOADING, MENTIONS_LABEL, NO_RESULTS_CHANNEL,
19 NO_RESULTS_CHAT, Sender, from_local, from_record, from_server, group_by_month, merge,
20 no_results_with_filters, same_user, step_index,
21 };
22 use crate::format;
23 use crate::runtime;
24 use crate::theme;
25
26 pub const FIND_PANEL_TAG: &str = "shell/islands/main/find";
27 pub const FIND_DIVIDER_TAG: &str = "shell/islands/main/find/divider-side";
28 pub const FIND_INPUT_TAG: &str = "shell/islands/main/find/input";
29 pub const FIND_RESULTS_TAG: &str = "shell/islands/main/find/results";
30 pub const FIND_PANEL_WIDTH: f32 = 320.;
31 const HEADER_HEIGHT: f32 = 48.;
32 const SIDE_INSET: f32 = 16.;
33 const INPUT_HEIGHT: f32 = 32.;
34 const CHIP_HEIGHT: f32 = 24.;
35 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
36 const LOCAL_LIMIT: usize = 100;
37 const FILTER_SCAN_LIMIT: usize = 500;
38 const SENDER_SCAN_LIMIT: usize = 200;
39
40 pub enum FindPanelEvent {
41 Close,
42 Jump(String),
43 }
44
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 enum Status {
47 Idle,
48 Loading,
49 Ready,
50 Failed,
51 }
52
53 pub struct FindPanel {
54 app: Entity<AppState>,
55 selection: Selection,
56 input: Entity<InputState>,
57 query: String,
58 filters: FindFilters,
59 senders: Vec<Sender>,
60 local_hits: Vec<FindHit>,
61 hits: Vec<FindHit>,
62 status: Status,
63 generation: u64,
64 current_index: Option<usize>,
65 search_session: SearchSession,
66 scroll: ScrollHandle,
67 _subscription: Subscription,
68 }
69
70 impl EventEmitter<FindPanelEvent> for FindPanel {}
71
72 impl FindPanel {
73 pub fn new(
74 app: Entity<AppState>,
75 selection: Selection,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 let title = panel_title(&selection);
80 let input = cx.new(|cx| InputState::new(window, cx).placeholder(title));
81 let subscription = cx.subscribe_in(&input, window, Self::on_input);
82 let senders = senders_of(app.read(cx), selection.conversation_id());
83 FindPanel {
84 app,
85 selection,
86 input,
87 query: String::new(),
88 filters: FindFilters::default(),
89 senders,
90 local_hits: Vec::new(),
91 hits: Vec::new(),
92 status: Status::Idle,
93 generation: 0,
94 current_index: None,
95 search_session: SearchSession::new(),
96 scroll: ScrollHandle::new(),
97 _subscription: subscription,
98 }
99 }
100
101 pub fn selection(&self) -> &Selection {
102 &self.selection
103 }
104
105 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
106 self.input.update(cx, |input, cx| input.focus(window, cx));
107 }
108
109 fn on_input(
110 &mut self,
111 input: &Entity<InputState>,
112 event: &InputEvent,
113 _: &mut Window,
114 cx: &mut Context<Self>,
115 ) {
116 match event {
117 InputEvent::Change => {
118 self.query = input.read(cx).value().trim().to_owned();
119 self.schedule_search(cx);
120 }
121 InputEvent::PressEnter { shift, .. } => self.step(*shift, cx),
122 _ => {}
123 }
124 }
125
126 fn step(&mut self, backwards: bool, cx: &mut Context<Self>) {
127 if let Some(index) = step_index(self.current_index, self.hits.len(), backwards) {
128 self.pick(index, cx);
129 }
130 }
131
132 fn pick(&mut self, index: usize, cx: &mut Context<Self>) {
133 let Some(hit) = self.hits.get(index) else {
134 return;
135 };
136 self.current_index = Some(index);
137 self.scroll.scroll_to_item(index);
138 cx.emit(FindPanelEvent::Jump(hit.message_id.clone()));
139 cx.notify();
140 }
141
142 fn update_filters(&mut self, change: impl FnOnce(&mut FindFilters), cx: &mut Context<Self>) {
143 change(&mut self.filters);
144 self.schedule_search(cx);
145 cx.notify();
146 }
147
148 fn schedule_search(&mut self, cx: &mut Context<Self>) {
149 self.generation += 1;
150 let generation = self.generation;
151 cx.spawn(async move |this, cx| {
152 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
153 this.update(cx, |panel, cx| {
154 if panel.generation == generation {
155 panel.run_search(cx);
156 }
157 })
158 .ok();
159 })
160 .detach();
161 }
162
163 fn run_search(&mut self, cx: &mut Context<Self>) {
164 self.current_index = None;
165 if self.query.is_empty() && !self.filters.is_active() {
166 self.local_hits.clear();
167 self.hits.clear();
168 self.status = Status::Idle;
169 cx.notify();
170 return;
171 }
172 let (store, engine, my_id) = {
173 let state = self.app.read(cx);
174 (
175 state.store.clone(),
176 state.engine.clone(),
177 state.directory.me.as_ref().map(|me| me.user_id.clone()),
178 )
179 };
180 let (today, offset) = today_and_offset();
181 let conversation_id = self.selection.conversation_id().to_owned();
182 let local: Vec<FindHit> =
183 local_hits(&store, &conversation_id, &self.query, my_id.as_deref())
184 .into_iter()
185 .filter(|hit| self.filters.admits(hit, today, offset))
186 .collect();
187 self.local_hits = local;
188 self.hits = merge(self.local_hits.clone(), Vec::new());
189 let server_engine = engine.filter(|_| matches!(self.selection, Selection::Chat(_)));
190 let Some(engine) = server_engine else {
191 self.status = Status::Ready;
192 cx.notify();
193 return;
194 };
195 self.status = Status::Loading;
196 let request = QueryRequest::new(self.query.clone(), QueryScope::Messages)
197 .with_filters(self.filters.server_filters(&conversation_id));
198 let search_session = self.search_session.clone();
199 let generation = self.generation;
200 let receiver =
201 runtime::spawn(async move { engine.server_query(&search_session, &request).await });
202 cx.spawn(async move |this, cx| {
203 let results = match receiver.await {
204 Ok(Ok(results)) => Some(results),
205 _ => None,
206 };
207 this.update(cx, |panel, cx| panel.apply_server(generation, results, cx))
208 .ok();
209 })
210 .detach();
211 cx.notify();
212 }
213
214 fn apply_server(
215 &mut self,
216 generation: u64,
217 results: Option<QueryResults>,
218 cx: &mut Context<Self>,
219 ) {
220 if generation != self.generation {
221 return;
222 }
223 let Some(results) = results else {
224 self.status = if self.hits.is_empty() {
225 Status::Failed
226 } else {
227 Status::Ready
228 };
229 cx.notify();
230 return;
231 };
232 let (today, offset) = today_and_offset();
233 let conversation_id = self.selection.conversation_id();
234 let server: Vec<FindHit> = results
235 .messages
236 .items
237 .iter()
238 .filter(|message| message.conversation_id == conversation_id)
239 .filter_map(from_server)
240 .filter(|hit| self.filters.admits(hit, today, offset))
241 .collect();
242 self.hits = merge(self.local_hits.clone(), server);
243 self.status = Status::Ready;
244 cx.notify();
245 }
246
247 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
248 h_flex()
249 .h(px(HEADER_HEIGHT))
250 .flex_none()
251 .pl(px(SIDE_INSET))
252 .pr(px(12.))
253 .items_center()
254 .justify_between()
255 .child(
256 div()
257 .text_size(px(15.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .child(panel_title(&self.selection)),
260 )
261 .child(
262 div()
263 .id("find-close")
264 .size(px(28.))
265 .flex()
266 .items_center()
267 .justify_center()
268 .rounded(px(7.))
269 .cursor_pointer()
270 .hover(|button| button.bg(theme::row_hover()))
271 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
272 .child(icon(IconName::Close, 14., theme::text_muted()))
273 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
274 )
275 }
276
277 fn search_row(&self) -> impl IntoElement {
278 h_flex()
279 .debug_selector(|| FIND_INPUT_TAG.into())
280 .mx(px(SIDE_INSET))
281 .h(px(INPUT_HEIGHT))
282 .flex_none()
283 .px(px(10.))
284 .gap(px(8.))
285 .items_center()
286 .rounded(px(6.))
287 .bg(theme::surface_raised())
288 .child(icon(IconName::Search, 14., theme::text_muted()))
289 .child(
290 div()
291 .flex_1()
292 .min_w_0()
293 .child(Input::new(&self.input).appearance(false).bordered(false)),
294 )
295 }
296
297 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
298 let panel = cx.weak_entity();
299 h_flex()
300 .px(px(SIDE_INSET))
301 .pt(px(8.))
302 .flex_none()
303 .flex_wrap()
304 .gap(px(6.))
305 .child(self.from_chip(panel.clone()))
306 .child(self.date_chip(panel))
307 .child(self.toggle_chip(
308 "find-has-attachment",
309 HAS_ATTACHMENT_LABEL,
310 self.filters.has_attachment,
311 |filters| filters.has_attachment = !filters.has_attachment,
312 cx,
313 ))
314 .child(self.toggle_chip(
315 "find-mentions",
316 MENTIONS_LABEL,
317 self.filters.mentions_me,
318 |filters| filters.mentions_me = !filters.mentions_me,
319 cx,
320 ))
321 }
322
323 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
324 let selected = self.filters.from.clone();
325 let label = selected
326 .as_ref()
327 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
328 let senders = self.senders.clone();
329 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
330 senders.iter().fold(menu, |menu, sender| {
331 let checked = selected
332 .as_ref()
333 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
334 let (panel, sender) = (panel.clone(), sender.clone());
335 menu.item(
336 PopupMenuItem::new(sender.name.clone())
337 .checked(checked)
338 .on_click(move |_, _, cx| {
339 let pick = (!checked).then(|| sender.clone());
340 panel
341 .update(cx, |panel, cx| {
342 panel.update_filters(|filters| filters.from = pick, cx)
343 })
344 .ok();
345 }),
346 )
347 })
348 })
349 }
350
351 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
352 let selected = self.filters.date;
353 let label = selected.map_or(DATE_LABEL, DateRange::label);
354 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
355 move |menu, _, _| {
356 DateRange::ALL.into_iter().fold(menu, |menu, range| {
357 let checked = selected == Some(range);
358 let panel = panel.clone();
359 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
360 move |_, _, cx| {
361 let pick = (!checked).then_some(range);
362 panel
363 .update(cx, |panel, cx| {
364 panel.update_filters(|filters| filters.date = pick, cx)
365 })
366 .ok();
367 },
368 ))
369 })
370 },
371 )
372 }
373
374 fn toggle_chip(
375 &self,
376 id: &'static str,
377 label: &'static str,
378 selected: bool,
379 change: fn(&mut FindFilters),
380 cx: &mut Context<Self>,
381 ) -> impl IntoElement {
382 div()
383 .id(id)
384 .h(px(CHIP_HEIGHT))
385 .px(px(12.))
386 .flex()
387 .flex_none()
388 .items_center()
389 .rounded_full()
390 .cursor_pointer()
391 .text_size(px(12.))
392 .when(selected, |chip| {
393 chip.bg(theme::accent()).text_color(theme::on_accent())
394 })
395 .when(!selected, |chip| {
396 chip.bg(theme::surface_raised())
397 .text_color(theme::text_soft())
398 .hover(|chip| chip.bg(theme::border_strong()))
399 })
400 .child(label)
401 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
402 }
403
404 fn message_line(&self) -> Option<String> {
405 let no_results = || {
406 if self.filters.is_active() && !self.query.is_empty() {
407 no_results_with_filters(&self.query)
408 } else {
409 match self.selection {
410 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
411 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
412 }
413 }
414 };
415 match self.status {
416 Status::Idle => Some(EMPTY_HINT.to_owned()),
417 Status::Failed => Some(LOAD_ERROR.to_owned()),
418 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
419 Status::Ready if self.hits.is_empty() => Some(no_results()),
420 _ => None,
421 }
422 }
423
424 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
425 let (today, offset) = today_and_offset();
426 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
427 if let Some(message) = self.message_line() {
428 list = list.child(
429 div()
430 .px(px(SIDE_INSET))
431 .py(px(8.))
432 .text_size(px(13.))
433 .text_color(theme::text_muted())
434 .child(message),
435 );
436 }
437 let mut index = 0;
438 for group in group_by_month(&self.hits, today, offset) {
439 list = list.child(
440 div()
441 .px(px(SIDE_INSET))
442 .pt(px(12.))
443 .pb(px(4.))
444 .text_size(px(12.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .text_color(theme::text_muted())
447 .child(group.label),
448 );
449 for hit in group.hits {
450 list = list.child(self.hit_row(&hit, index, today, offset, cx));
451 index += 1;
452 }
453 }
454 div()
455 .debug_selector(|| FIND_RESULTS_TAG.into())
456 .id("find-results")
457 .flex_1()
458 .min_h_0()
459 .w_full()
460 .overflow_y_scroll()
461 .track_scroll(&self.scroll)
462 .child(list)
463 }
464
465 fn hit_row(
466 &self,
467 hit: &FindHit,
468 index: usize,
469 today: NaiveDate,
470 offset: chrono::FixedOffset,
471 cx: &mut Context<Self>,
472 ) -> impl IntoElement {
473 let current = self.current_index == Some(index);
474 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
475 .highlights
476 .iter()
477 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
478 .map(|range| {
479 (
480 range.clone(),
481 HighlightStyle {
482 color: Some(theme::accent_text()),
483 font_weight: Some(FontWeight::SEMIBOLD),
484 ..Default::default()
485 },
486 )
487 })
488 .collect();
489 v_flex()
490 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
491 .mx(px(8.))
492 .px(px(8.))
493 .py(px(8.))
494 .gap(px(2.))
495 .rounded(px(6.))
496 .cursor_pointer()
497 .when(current, |row| row.bg(theme::selection()))
498 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
499 .child(
500 h_flex()
501 .gap(px(8.))
502 .text_size(px(12.))
503 .child(
504 div()
505 .flex_1()
506 .min_w_0()
507 .truncate()
508 .font_weight(FontWeight::SEMIBOLD)
509 .text_color(theme::text())
510 .child(hit.sender_name.clone()),
511 )
512 .child(
513 div()
514 .flex_none()
515 .text_color(theme::text_muted())
516 .child(format::list_time_label(hit.sent_at, today, offset)),
517 ),
518 )
519 .child(
520 div()
521 .text_size(px(13.))
522 .text_color(theme::text_soft())
523 .line_clamp(2)
524 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
525 )
526 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
527 }
528 }
529
530 impl Render for FindPanel {
531 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
532 h_flex()
533 .debug_selector(|| FIND_PANEL_TAG.into())
534 .h_full()
535 .items_start()
536 .bg(theme::surface())
537 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
538 cx.emit(FindPanelEvent::Close);
539 cx.stop_propagation();
540 }))
541 .child(
542 div()
543 .debug_selector(|| FIND_DIVIDER_TAG.into())
544 .w(px(1.))
545 .h_full()
546 .flex_none()
547 .bg(theme::border()),
548 )
549 .child(
550 v_flex()
551 .flex_1()
552 .min_w_0()
553 .h_full()
554 .child(self.header(cx))
555 .child(self.search_row())
556 .child(self.chips(cx))
557 .child(self.results(cx)),
558 )
559 }
560 }
561
562 fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
563 Button::new(id)
564 .ghost()
565 .compact()
566 .label(label)
567 .dropdown_caret(true)
568 .rounded(px(CHIP_HEIGHT / 2.))
569 .h(px(CHIP_HEIGHT))
570 .text_size(px(12.))
571 .when(selected, |chip| {
572 chip.bg(theme::accent()).text_color(theme::on_accent())
573 })
574 .when(!selected, |chip| {
575 chip.bg(theme::surface_raised())
576 .text_color(theme::text_soft())
577 })
578 }
579
580 fn panel_title(selection: &Selection) -> &'static str {
581 match selection {
582 Selection::Chat(_) => FIND_IN_CHAT,
583 Selection::Channel(_) => FIND_IN_CHANNEL,
584 }
585 }
586
587 fn today_and_offset() -> (NaiveDate, chrono::FixedOffset) {
588 let now = Local::now();
589 (now.date_naive(), now.offset().fix())
590 }
591
592 fn local_hits(
593 store: &Store,
594 conversation_id: &str,
595 query: &str,
596 my_id: Option<&str>,
597 ) -> Vec<FindHit> {
598 if query.is_empty() {
599 return store
600 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
601 .unwrap_or_default()
602 .iter()
603 .filter(|record| !record.deleted)
604 .map(|record| from_record(record, my_id))
605 .collect();
606 }
607 let found = store
608 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
609 .unwrap_or_default();
610 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
611 let records = store
612 .messages_by_id(conversation_id, &message_ids)
613 .unwrap_or_default();
614 found
615 .iter()
616 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
617 .collect()
618 }
619
620 fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
621 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
622 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
623 let mut senders: Vec<Sender> = Vec::new();
624 let mut push = |user_id: &str, name: &str| {
625 if name.is_empty() || is_me(user_id) {
626 return;
627 }
628 if senders
629 .iter()
630 .any(|sender| same_user(&sender.user_id, user_id))
631 {
632 return;
633 }
634 senders.push(Sender {
635 user_id: user_id.to_owned(),
636 name: name.to_owned(),
637 });
638 };
639 if let Some(chat) = state
640 .sidebar
641 .chats
642 .iter()
643 .find(|chat| chat.id == conversation_id)
644 {
645 for member in &chat.members {
646 if let Some(user_id) = &member.user_id {
647 push(user_id, &member.display_name);
648 }
649 }
650 }
651 for record in state
652 .store
653 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
654 .unwrap_or_default()
655 .iter()
656 .rev()
657 {
658 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
659 push(user_id, name);
660 }
661 }
662 senders.sort_by_key(|sender| sender.name.to_lowercase());
663 senders
664 }
@@ -0,0 +1,664 @@
1use std::time::Duration;
2
3use chrono::{Local, NaiveDate, Offset};
4use gpui_kit::assets::IconName;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
7use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use store::Store;
12use teams_core::substrate_search::{QueryRequest, QueryResults, QueryScope, SearchSession};
13
14use super::widgets::icon;
15use crate::app_state::{AppState, Selection};
16use crate::find_in_chat::{
17 DATE_LABEL, DateRange, EMPTY_HINT, FIND_IN_CHANNEL, FIND_IN_CHAT, FROM_LABEL, FindFilters,
18 FindHit, HAS_ATTACHMENT_LABEL, LOAD_ERROR, LOADING, MENTIONS_LABEL, NO_RESULTS_CHANNEL,
19 NO_RESULTS_CHAT, Sender, from_local, from_record, from_server, group_by_month, merge,
20 no_results_with_filters, same_user, step_index,
21};
22use crate::format;
23use crate::runtime;
24use crate::theme;
25
26pub const FIND_PANEL_TAG: &str = "shell/islands/main/find";
27pub const FIND_DIVIDER_TAG: &str = "shell/islands/main/find/divider-side";
28pub const FIND_INPUT_TAG: &str = "shell/islands/main/find/input";
29pub const FIND_RESULTS_TAG: &str = "shell/islands/main/find/results";
30pub const FIND_PANEL_WIDTH: f32 = 320.;
31const HEADER_HEIGHT: f32 = 48.;
32const SIDE_INSET: f32 = 16.;
33const INPUT_HEIGHT: f32 = 32.;
34const CHIP_HEIGHT: f32 = 24.;
35const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
36const LOCAL_LIMIT: usize = 100;
37const FILTER_SCAN_LIMIT: usize = 500;
38const SENDER_SCAN_LIMIT: usize = 200;
39
40pub enum FindPanelEvent {
41 Close,
42 Jump(String),
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46enum Status {
47 Idle,
48 Loading,
49 Ready,
50 Failed,
51}
52
53pub struct FindPanel {
54 app: Entity<AppState>,
55 selection: Selection,
56 input: Entity<InputState>,
57 query: String,
58 filters: FindFilters,
59 senders: Vec<Sender>,
60 local_hits: Vec<FindHit>,
61 hits: Vec<FindHit>,
62 status: Status,
63 generation: u64,
64 current_index: Option<usize>,
65 search_session: SearchSession,
66 scroll: ScrollHandle,
67 _subscription: Subscription,
68}
69
70impl EventEmitter<FindPanelEvent> for FindPanel {}
71
72impl FindPanel {
73 pub fn new(
74 app: Entity<AppState>,
75 selection: Selection,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 let title = panel_title(&selection);
80 let input = cx.new(|cx| InputState::new(window, cx).placeholder(title));
81 let subscription = cx.subscribe_in(&input, window, Self::on_input);
82 let senders = senders_of(app.read(cx), selection.conversation_id());
83 FindPanel {
84 app,
85 selection,
86 input,
87 query: String::new(),
88 filters: FindFilters::default(),
89 senders,
90 local_hits: Vec::new(),
91 hits: Vec::new(),
92 status: Status::Idle,
93 generation: 0,
94 current_index: None,
95 search_session: SearchSession::new(),
96 scroll: ScrollHandle::new(),
97 _subscription: subscription,
98 }
99 }
100
101 pub fn selection(&self) -> &Selection {
102 &self.selection
103 }
104
105 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
106 self.input.update(cx, |input, cx| input.focus(window, cx));
107 }
108
109 fn on_input(
110 &mut self,
111 input: &Entity<InputState>,
112 event: &InputEvent,
113 _: &mut Window,
114 cx: &mut Context<Self>,
115 ) {
116 match event {
117 InputEvent::Change => {
118 self.query = input.read(cx).value().trim().to_owned();
119 self.schedule_search(cx);
120 }
121 InputEvent::PressEnter { shift, .. } => self.step(*shift, cx),
122 _ => {}
123 }
124 }
125
126 fn step(&mut self, backwards: bool, cx: &mut Context<Self>) {
127 if let Some(index) = step_index(self.current_index, self.hits.len(), backwards) {
128 self.pick(index, cx);
129 }
130 }
131
132 fn pick(&mut self, index: usize, cx: &mut Context<Self>) {
133 let Some(hit) = self.hits.get(index) else {
134 return;
135 };
136 self.current_index = Some(index);
137 self.scroll.scroll_to_item(index);
138 cx.emit(FindPanelEvent::Jump(hit.message_id.clone()));
139 cx.notify();
140 }
141
142 fn update_filters(&mut self, change: impl FnOnce(&mut FindFilters), cx: &mut Context<Self>) {
143 change(&mut self.filters);
144 self.schedule_search(cx);
145 cx.notify();
146 }
147
148 fn schedule_search(&mut self, cx: &mut Context<Self>) {
149 self.generation += 1;
150 let generation = self.generation;
151 cx.spawn(async move |this, cx| {
152 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
153 this.update(cx, |panel, cx| {
154 if panel.generation == generation {
155 panel.run_search(cx);
156 }
157 })
158 .ok();
159 })
160 .detach();
161 }
162
163 fn run_search(&mut self, cx: &mut Context<Self>) {
164 self.current_index = None;
165 if self.query.is_empty() && !self.filters.is_active() {
166 self.local_hits.clear();
167 self.hits.clear();
168 self.status = Status::Idle;
169 cx.notify();
170 return;
171 }
172 let (store, engine, my_id) = {
173 let state = self.app.read(cx);
174 (
175 state.store.clone(),
176 state.engine.clone(),
177 state.directory.me.as_ref().map(|me| me.user_id.clone()),
178 )
179 };
180 let (today, offset) = today_and_offset();
181 let conversation_id = self.selection.conversation_id().to_owned();
182 let local: Vec<FindHit> =
183 local_hits(&store, &conversation_id, &self.query, my_id.as_deref())
184 .into_iter()
185 .filter(|hit| self.filters.admits(hit, today, offset))
186 .collect();
187 self.local_hits = local;
188 self.hits = merge(self.local_hits.clone(), Vec::new());
189 let server_engine = engine.filter(|_| matches!(self.selection, Selection::Chat(_)));
190 let Some(engine) = server_engine else {
191 self.status = Status::Ready;
192 cx.notify();
193 return;
194 };
195 self.status = Status::Loading;
196 let request = QueryRequest::new(self.query.clone(), QueryScope::Messages)
197 .with_filters(self.filters.server_filters(&conversation_id));
198 let search_session = self.search_session.clone();
199 let generation = self.generation;
200 let receiver =
201 runtime::spawn(async move { engine.server_query(&search_session, &request).await });
202 cx.spawn(async move |this, cx| {
203 let results = match receiver.await {
204 Ok(Ok(results)) => Some(results),
205 _ => None,
206 };
207 this.update(cx, |panel, cx| panel.apply_server(generation, results, cx))
208 .ok();
209 })
210 .detach();
211 cx.notify();
212 }
213
214 fn apply_server(
215 &mut self,
216 generation: u64,
217 results: Option<QueryResults>,
218 cx: &mut Context<Self>,
219 ) {
220 if generation != self.generation {
221 return;
222 }
223 let Some(results) = results else {
224 self.status = if self.hits.is_empty() {
225 Status::Failed
226 } else {
227 Status::Ready
228 };
229 cx.notify();
230 return;
231 };
232 let (today, offset) = today_and_offset();
233 let conversation_id = self.selection.conversation_id();
234 let server: Vec<FindHit> = results
235 .messages
236 .items
237 .iter()
238 .filter(|message| message.conversation_id == conversation_id)
239 .filter_map(from_server)
240 .filter(|hit| self.filters.admits(hit, today, offset))
241 .collect();
242 self.hits = merge(self.local_hits.clone(), server);
243 self.status = Status::Ready;
244 cx.notify();
245 }
246
247 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
248 h_flex()
249 .h(px(HEADER_HEIGHT))
250 .flex_none()
251 .pl(px(SIDE_INSET))
252 .pr(px(12.))
253 .items_center()
254 .justify_between()
255 .child(
256 div()
257 .text_size(px(15.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .child(panel_title(&self.selection)),
260 )
261 .child(
262 div()
263 .id("find-close")
264 .size(px(28.))
265 .flex()
266 .items_center()
267 .justify_center()
268 .rounded(px(7.))
269 .cursor_pointer()
270 .hover(|button| button.bg(theme::row_hover()))
271 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
272 .child(icon(IconName::Close, 14., theme::text_muted()))
273 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
274 )
275 }
276
277 fn search_row(&self) -> impl IntoElement {
278 h_flex()
279 .debug_selector(|| FIND_INPUT_TAG.into())
280 .mx(px(SIDE_INSET))
281 .h(px(INPUT_HEIGHT))
282 .flex_none()
283 .px(px(10.))
284 .gap(px(8.))
285 .items_center()
286 .rounded(px(6.))
287 .bg(theme::surface_raised())
288 .child(icon(IconName::Search, 14., theme::text_muted()))
289 .child(
290 div()
291 .flex_1()
292 .min_w_0()
293 .child(Input::new(&self.input).appearance(false).bordered(false)),
294 )
295 }
296
297 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
298 let panel = cx.weak_entity();
299 h_flex()
300 .px(px(SIDE_INSET))
301 .pt(px(8.))
302 .flex_none()
303 .flex_wrap()
304 .gap(px(6.))
305 .child(self.from_chip(panel.clone()))
306 .child(self.date_chip(panel))
307 .child(self.toggle_chip(
308 "find-has-attachment",
309 HAS_ATTACHMENT_LABEL,
310 self.filters.has_attachment,
311 |filters| filters.has_attachment = !filters.has_attachment,
312 cx,
313 ))
314 .child(self.toggle_chip(
315 "find-mentions",
316 MENTIONS_LABEL,
317 self.filters.mentions_me,
318 |filters| filters.mentions_me = !filters.mentions_me,
319 cx,
320 ))
321 }
322
323 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
324 let selected = self.filters.from.clone();
325 let label = selected
326 .as_ref()
327 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
328 let senders = self.senders.clone();
329 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
330 senders.iter().fold(menu, |menu, sender| {
331 let checked = selected
332 .as_ref()
333 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
334 let (panel, sender) = (panel.clone(), sender.clone());
335 menu.item(
336 PopupMenuItem::new(sender.name.clone())
337 .checked(checked)
338 .on_click(move |_, _, cx| {
339 let pick = (!checked).then(|| sender.clone());
340 panel
341 .update(cx, |panel, cx| {
342 panel.update_filters(|filters| filters.from = pick, cx)
343 })
344 .ok();
345 }),
346 )
347 })
348 })
349 }
350
351 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
352 let selected = self.filters.date;
353 let label = selected.map_or(DATE_LABEL, DateRange::label);
354 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
355 move |menu, _, _| {
356 DateRange::ALL.into_iter().fold(menu, |menu, range| {
357 let checked = selected == Some(range);
358 let panel = panel.clone();
359 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
360 move |_, _, cx| {
361 let pick = (!checked).then_some(range);
362 panel
363 .update(cx, |panel, cx| {
364 panel.update_filters(|filters| filters.date = pick, cx)
365 })
366 .ok();
367 },
368 ))
369 })
370 },
371 )
372 }
373
374 fn toggle_chip(
375 &self,
376 id: &'static str,
377 label: &'static str,
378 selected: bool,
379 change: fn(&mut FindFilters),
380 cx: &mut Context<Self>,
381 ) -> impl IntoElement {
382 div()
383 .id(id)
384 .h(px(CHIP_HEIGHT))
385 .px(px(12.))
386 .flex()
387 .flex_none()
388 .items_center()
389 .rounded_full()
390 .cursor_pointer()
391 .text_size(px(12.))
392 .when(selected, |chip| {
393 chip.bg(theme::accent()).text_color(theme::on_accent())
394 })
395 .when(!selected, |chip| {
396 chip.bg(theme::surface_raised())
397 .text_color(theme::text_soft())
398 .hover(|chip| chip.bg(theme::border_strong()))
399 })
400 .child(label)
401 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
402 }
403
404 fn message_line(&self) -> Option<String> {
405 let no_results = || {
406 if self.filters.is_active() && !self.query.is_empty() {
407 no_results_with_filters(&self.query)
408 } else {
409 match self.selection {
410 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
411 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
412 }
413 }
414 };
415 match self.status {
416 Status::Idle => Some(EMPTY_HINT.to_owned()),
417 Status::Failed => Some(LOAD_ERROR.to_owned()),
418 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
419 Status::Ready if self.hits.is_empty() => Some(no_results()),
420 _ => None,
421 }
422 }
423
424 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
425 let (today, offset) = today_and_offset();
426 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
427 if let Some(message) = self.message_line() {
428 list = list.child(
429 div()
430 .px(px(SIDE_INSET))
431 .py(px(8.))
432 .text_size(px(13.))
433 .text_color(theme::text_muted())
434 .child(message),
435 );
436 }
437 let mut index = 0;
438 for group in group_by_month(&self.hits, today, offset) {
439 list = list.child(
440 div()
441 .px(px(SIDE_INSET))
442 .pt(px(12.))
443 .pb(px(4.))
444 .text_size(px(12.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .text_color(theme::text_muted())
447 .child(group.label),
448 );
449 for hit in group.hits {
450 list = list.child(self.hit_row(&hit, index, today, offset, cx));
451 index += 1;
452 }
453 }
454 div()
455 .debug_selector(|| FIND_RESULTS_TAG.into())
456 .id("find-results")
457 .flex_1()
458 .min_h_0()
459 .w_full()
460 .overflow_y_scroll()
461 .track_scroll(&self.scroll)
462 .child(list)
463 }
464
465 fn hit_row(
466 &self,
467 hit: &FindHit,
468 index: usize,
469 today: NaiveDate,
470 offset: chrono::FixedOffset,
471 cx: &mut Context<Self>,
472 ) -> impl IntoElement {
473 let current = self.current_index == Some(index);
474 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
475 .highlights
476 .iter()
477 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
478 .map(|range| {
479 (
480 range.clone(),
481 HighlightStyle {
482 color: Some(theme::accent_text()),
483 font_weight: Some(FontWeight::SEMIBOLD),
484 ..Default::default()
485 },
486 )
487 })
488 .collect();
489 v_flex()
490 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
491 .mx(px(8.))
492 .px(px(8.))
493 .py(px(8.))
494 .gap(px(2.))
495 .rounded(px(6.))
496 .cursor_pointer()
497 .when(current, |row| row.bg(theme::selection()))
498 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
499 .child(
500 h_flex()
501 .gap(px(8.))
502 .text_size(px(12.))
503 .child(
504 div()
505 .flex_1()
506 .min_w_0()
507 .truncate()
508 .font_weight(FontWeight::SEMIBOLD)
509 .text_color(theme::text())
510 .child(hit.sender_name.clone()),
511 )
512 .child(
513 div()
514 .flex_none()
515 .text_color(theme::text_muted())
516 .child(format::list_time_label(hit.sent_at, today, offset)),
517 ),
518 )
519 .child(
520 div()
521 .text_size(px(13.))
522 .text_color(theme::text_soft())
523 .line_clamp(2)
524 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
525 )
526 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
527 }
528}
529
530impl Render for FindPanel {
531 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
532 h_flex()
533 .debug_selector(|| FIND_PANEL_TAG.into())
534 .h_full()
535 .items_start()
536 .bg(theme::surface())
537 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
538 cx.emit(FindPanelEvent::Close);
539 cx.stop_propagation();
540 }))
541 .child(
542 div()
543 .debug_selector(|| FIND_DIVIDER_TAG.into())
544 .w(px(1.))
545 .h_full()
546 .flex_none()
547 .bg(theme::border()),
548 )
549 .child(
550 v_flex()
551 .flex_1()
552 .min_w_0()
553 .h_full()
554 .child(self.header(cx))
555 .child(self.search_row())
556 .child(self.chips(cx))
557 .child(self.results(cx)),
558 )
559 }
560}
561
562fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
563 Button::new(id)
564 .ghost()
565 .compact()
566 .label(label)
567 .dropdown_caret(true)
568 .rounded(px(CHIP_HEIGHT / 2.))
569 .h(px(CHIP_HEIGHT))
570 .text_size(px(12.))
571 .when(selected, |chip| {
572 chip.bg(theme::accent()).text_color(theme::on_accent())
573 })
574 .when(!selected, |chip| {
575 chip.bg(theme::surface_raised())
576 .text_color(theme::text_soft())
577 })
578}
579
580fn panel_title(selection: &Selection) -> &'static str {
581 match selection {
582 Selection::Chat(_) => FIND_IN_CHAT,
583 Selection::Channel(_) => FIND_IN_CHANNEL,
584 }
585}
586
587fn today_and_offset() -> (NaiveDate, chrono::FixedOffset) {
588 let now = Local::now();
589 (now.date_naive(), now.offset().fix())
590}
591
592fn local_hits(
593 store: &Store,
594 conversation_id: &str,
595 query: &str,
596 my_id: Option<&str>,
597) -> Vec<FindHit> {
598 if query.is_empty() {
599 return store
600 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
601 .unwrap_or_default()
602 .iter()
603 .filter(|record| !record.deleted)
604 .map(|record| from_record(record, my_id))
605 .collect();
606 }
607 let found = store
608 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
609 .unwrap_or_default();
610 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
611 let records = store
612 .messages_by_id(conversation_id, &message_ids)
613 .unwrap_or_default();
614 found
615 .iter()
616 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
617 .collect()
618}
619
620fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
621 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
622 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
623 let mut senders: Vec<Sender> = Vec::new();
624 let mut push = |user_id: &str, name: &str| {
625 if name.is_empty() || is_me(user_id) {
626 return;
627 }
628 if senders
629 .iter()
630 .any(|sender| same_user(&sender.user_id, user_id))
631 {
632 return;
633 }
634 senders.push(Sender {
635 user_id: user_id.to_owned(),
636 name: name.to_owned(),
637 });
638 };
639 if let Some(chat) = state
640 .sidebar
641 .chats
642 .iter()
643 .find(|chat| chat.id == conversation_id)
644 {
645 for member in &chat.members {
646 if let Some(user_id) = &member.user_id {
647 push(user_id, &member.display_name);
648 }
649 }
650 }
651 for record in state
652 .store
653 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
654 .unwrap_or_default()
655 .iter()
656 .rev()
657 {
658 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
659 push(user_id, name);
660 }
661 }
662 senders.sort_by_key(|sender| sender.name.to_lowercase());
663 senders
664}
crates/app/src/views/mod.rs +1 −0
@@ -43,6 +43,7 @@ pub mod dialog_overlay;
43 43 pub mod emoji_popup;
44 44 pub mod format_toolbar;
45 45 pub mod forward_dialog;
46 pub mod find_panel;
46 47 pub mod fun_picker;
47 48 pub mod group_name;
48 49 pub mod image_menu;
@@ -43,6 +43,7 @@ pub mod dialog_overlay;
43pub mod emoji_popup;
43pub mod emoji_popup;
44pub mod format_toolbar;
44pub mod format_toolbar;
45pub mod forward_dialog;
45pub mod forward_dialog;
46pub mod find_panel;
46pub mod fun_picker;
47pub mod fun_picker;
47pub mod group_name;
48pub mod group_name;
48pub mod image_menu;
49pub mod image_menu;
crates/app/src/views/shell.rs +40 −3
@@ -17,10 +17,12 @@ use super::prejoin_view::PrejoinView;
17 17 use super::profile_card::{ProfileCard, ProfileCardEvent};
18 18 use gpui_kit::prelude::FluentBuilder as _;
19 19 use super::rail::RailView;
20 use crate::chat_filter::ChatFilterPill;
20 21 use super::saved_panel::{SavedPanel, SavedPanelEvent};
21 22 use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 28 ZoomShareReset,
@@ -28,7 +30,7 @@ use super::shortcuts::{
28 30 use super::window_zoom::{WindowZoom, change_zoom};
29 31 use super::call_pop_out::zoom_listener;
30 32 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
31 use super::sidebar::SidebarView;
33 use super::sidebar::{SidebarEvent, SidebarView};
32 34 use app_ui_kit::render::hooks::RenderHooks;
33 35 use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
34 36 use super::connection_banner::render_connection_banner;
@@ -138,6 +140,7 @@ pub struct AppShell {
138 140 call_mini: Entity<CallMiniView>,
139 141 _call_media_observation: Subscription,
140 142 _panel_subscriptions: [Subscription; 2],
143 _sidebar_subscription: Subscription,
141 144 _agents_subscription: Option<Subscription>,
142 145 _agent_subscription: Option<Subscription>,
143 146 _escape_observation: Subscription,
@@ -251,6 +254,9 @@ impl AppShell {
251 254 )
252 255 });
253 256 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
257 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, _: &SidebarEvent, window, cx| {
258 this.restore_focus(window, cx);
259 });
254 260 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
255 261 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
256 262 let timeline = conversation.read(cx).timeline_bounds();
@@ -332,6 +338,7 @@ impl AppShell {
332 338 call_mini,
333 339 _call_media_observation: call_media_observation,
334 340 _panel_subscriptions: panel_subscriptions,
341 _sidebar_subscription: sidebar_subscription,
335 342 _agents_subscription: agents_subscription,
336 343 _agent_subscription: agent_subscription,
337 344 _escape_observation: escape_observation,
@@ -968,6 +975,36 @@ impl Render for AppShell {
968 975 this.sidebar
969 976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
970 977 }))
978 .on_action(cx.listener(|this, _: &FindInChat, window, cx| {
979 this.close_image_viewer(window, cx);
980 this.conversation
981 .update(cx, |conversation, cx| conversation.open_find(window, cx));
982 }))
983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
984 this.close_image_viewer(window, cx);
985 this.sidebar
986 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
987 }))
988 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
989 this.sidebar
990 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
991 }))
992 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
993 this.sidebar
994 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
995 }))
996 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
997 this.sidebar
998 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
999 }))
1000 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1001 this.sidebar
1002 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1003 }))
1004 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1005 this.sidebar
1006 .update(cx, |sidebar, cx| sidebar.clear_filters(window, cx));
1007 }))
971 1008 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
972 1009 this.close_image_viewer(window, cx);
973 1010 this.sidebar
@@ -17,10 +17,12 @@ use super::prejoin_view::PrejoinView;
17use super::profile_card::{ProfileCard, ProfileCardEvent};
17use super::profile_card::{ProfileCard, ProfileCardEvent};
18use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::prelude::FluentBuilder as _;
19use super::rail::RailView;
19use super::rail::RailView;
20use crate::chat_filter::ChatFilterPill;
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::shortcuts::{
22use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 ZoomShareReset,
28 ZoomShareReset,
@@ -28,7 +30,7 @@ use super::shortcuts::{
28use super::window_zoom::{WindowZoom, change_zoom};
30use super::window_zoom::{WindowZoom, change_zoom};
29use super::call_pop_out::zoom_listener;
31use super::call_pop_out::zoom_listener;
30use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
32use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
31use super::sidebar::SidebarView;
33use super::sidebar::{SidebarEvent, SidebarView};
32use app_ui_kit::render::hooks::RenderHooks;
34use app_ui_kit::render::hooks::RenderHooks;
33use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
35use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
34use super::connection_banner::render_connection_banner;
36use super::connection_banner::render_connection_banner;
@@ -138,6 +140,7 @@ pub struct AppShell {
138 call_mini: Entity<CallMiniView>,
140 call_mini: Entity<CallMiniView>,
139 _call_media_observation: Subscription,
141 _call_media_observation: Subscription,
140 _panel_subscriptions: [Subscription; 2],
142 _panel_subscriptions: [Subscription; 2],
143 _sidebar_subscription: Subscription,
141 _agents_subscription: Option<Subscription>,
144 _agents_subscription: Option<Subscription>,
142 _agent_subscription: Option<Subscription>,
145 _agent_subscription: Option<Subscription>,
143 _escape_observation: Subscription,
146 _escape_observation: Subscription,
@@ -251,6 +254,9 @@ impl AppShell {
251 )
254 )
252 });
255 });
253 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
256 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
257 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, _: &SidebarEvent, window, cx| {
258 this.restore_focus(window, cx);
259 });
254 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
260 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
255 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
261 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
256 let timeline = conversation.read(cx).timeline_bounds();
262 let timeline = conversation.read(cx).timeline_bounds();
@@ -332,6 +338,7 @@ impl AppShell {
332 call_mini,
338 call_mini,
333 _call_media_observation: call_media_observation,
339 _call_media_observation: call_media_observation,
334 _panel_subscriptions: panel_subscriptions,
340 _panel_subscriptions: panel_subscriptions,
341 _sidebar_subscription: sidebar_subscription,
335 _agents_subscription: agents_subscription,
342 _agents_subscription: agents_subscription,
336 _agent_subscription: agent_subscription,
343 _agent_subscription: agent_subscription,
337 _escape_observation: escape_observation,
344 _escape_observation: escape_observation,
@@ -968,6 +975,36 @@ impl Render for AppShell {
968 this.sidebar
975 this.sidebar
969 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
970 }))
977 }))
978 .on_action(cx.listener(|this, _: &FindInChat, window, cx| {
979 this.close_image_viewer(window, cx);
980 this.conversation
981 .update(cx, |conversation, cx| conversation.open_find(window, cx));
982 }))
983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
984 this.close_image_viewer(window, cx);
985 this.sidebar
986 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
987 }))
988 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
989 this.sidebar
990 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
991 }))
992 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
993 this.sidebar
994 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
995 }))
996 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
997 this.sidebar
998 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
999 }))
1000 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1001 this.sidebar
1002 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1003 }))
1004 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1005 this.sidebar
1006 .update(cx, |sidebar, cx| sidebar.clear_filters(window, cx));
1007 }))
971 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
1008 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
972 this.close_image_viewer(window, cx);
1009 this.close_image_viewer(window, cx);
973 this.sidebar
1010 this.sidebar
crates/app/src/views/shortcuts.rs +14 −0
@@ -29,6 +29,13 @@ actions!(
29 29 OpenSaved,
30 30 OpenCallsTab,
31 31 OpenAgents,
32 OpenChatFilter,
33 FindInChat,
34 FilterUnreadChats,
35 FilterNonMeetingChats,
36 FilterMeetingChats,
37 FilterMutedChats,
38 ClearChatFilters,
32 39 PreviousConversation,
33 40 NextConversation,
34 41 JumpToLastReadOrNewest,
@@ -129,6 +136,13 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 136 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
130 137 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
131 138 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
139 shortcut!(Navigation, GlobalOverTextFields, "Open filter", "ctrl-shift-f", Some("cmd-shift-f"), OpenChatFilter),
140 shortcut!(Navigation, OutsideTextFields, "Filter chat list by unread chats only", "ctrl-alt-u", None, FilterUnreadChats),
141 shortcut!(Navigation, OutsideTextFields, "Filter chat list by chats only", "ctrl-alt-c", None, FilterNonMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
144 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
145 shortcut!(Composer, GlobalOverTextFields, "Find in chat", "ctrl-f", Some("cmd-f"), FindInChat),
132 146 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 147 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
134 148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
@@ -29,6 +29,13 @@ actions!(
29 OpenSaved,
29 OpenSaved,
30 OpenCallsTab,
30 OpenCallsTab,
31 OpenAgents,
31 OpenAgents,
32 OpenChatFilter,
33 FindInChat,
34 FilterUnreadChats,
35 FilterNonMeetingChats,
36 FilterMeetingChats,
37 FilterMutedChats,
38 ClearChatFilters,
32 PreviousConversation,
39 PreviousConversation,
33 NextConversation,
40 NextConversation,
34 JumpToLastReadOrNewest,
41 JumpToLastReadOrNewest,
@@ -129,6 +136,13 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
136 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
137 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
138 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
139 shortcut!(Navigation, GlobalOverTextFields, "Open filter", "ctrl-shift-f", Some("cmd-shift-f"), OpenChatFilter),
140 shortcut!(Navigation, OutsideTextFields, "Filter chat list by unread chats only", "ctrl-alt-u", None, FilterUnreadChats),
141 shortcut!(Navigation, OutsideTextFields, "Filter chat list by chats only", "ctrl-alt-c", None, FilterNonMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
144 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
145 shortcut!(Composer, GlobalOverTextFields, "Find in chat", "ctrl-f", Some("cmd-f"), FindInChat),
132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
146 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
147 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
crates/app/src/views/sidebar.rs +56 −4
@@ -28,6 +28,7 @@ use crate::channel_menu::{
28 28 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
29 29 };
30 30 use crate::chat_actions::TITLE_LIMIT;
31 use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
31 32 use crate::data::{Directory, is_pending_folder};
32 33 use crate::format;
33 34 use crate::local_previews::LocalPreview;
@@ -41,6 +42,9 @@ use crate::sidebar_model::{
41 42 };
42 43 use crate::theme;
43 44 use app_ui_kit::layout::SIDEBAR_WIDTH;
45 use gpui_kit::component::input::InputState;
46
47 pub(crate) mod chat_filter_bar;
44 48
45 49 pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
46 50 const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -523,6 +527,12 @@ pub(crate) fn confirm_leave(
523 527 });
524 528 }
525 529
530 pub enum SidebarEvent {
531 RestoreFocus,
532 }
533
534 impl EventEmitter<SidebarEvent> for SidebarView {}
535
526 536 pub struct SidebarView {
527 537 state: Entity<AppState>,
528 538 tab: SidebarTab,
@@ -537,6 +547,12 @@ pub struct SidebarView {
537 547 older_chats_seen: Cell<(bool, bool)>,
538 548 channels_scroll: ScrollHandle,
539 549 calls_scroll: ScrollHandle,
550 chat_filter: ChatFilter,
551 filter_box_open: bool,
552 more_filters_open: bool,
553 filter_input: Option<Entity<InputState>>,
554 filter_subscription: Option<Subscription>,
555 _activity_observation: Subscription,
540 556 _subscription: Subscription,
541 557 _state_observation: Subscription,
542 558 _agent_observation: Option<Subscription>,
@@ -627,6 +643,15 @@ impl SidebarView {
627 643 SidebarTab::Chats
628 644 };
629 645 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
646 let activity = activity_panel.read(cx).activity();
647 let activity_observation = cx.observe(&activity, |view, _, cx| {
648 if view
649 .chat_filter
650 .has(crate::chat_filter::ChatFilterPill::Mentions)
651 {
652 cx.notify();
653 }
654 });
630 655 cx.spawn(async move |this, cx| {
631 656 loop {
632 657 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -655,6 +680,12 @@ impl SidebarView {
655 680 older_chats_seen: Cell::new((false, false)),
656 681 channels_scroll: ScrollHandle::new(),
657 682 calls_scroll: ScrollHandle::new(),
683 chat_filter: ChatFilter::default(),
684 filter_box_open: false,
685 more_filters_open: false,
686 filter_input: None,
687 filter_subscription: None,
688 _activity_observation: activity_observation,
658 689 _subscription: subscription,
659 690 _state_observation: state_observation,
660 691 _agent_observation: agent_observation,
@@ -1142,7 +1173,18 @@ impl SidebarView {
1142 1173 now,
1143 1174 offset,
1144 1175 };
1145 let sections = build_sections(&input);
1176 let sections = if self.chat_filter.is_active() {
1177 let mentioned = self.mentioned_chats(cx);
1178 let selected_id = self.selected_chat_id(cx);
1179 filtered_sections(
1180 &input,
1181 &self.chat_filter,
1182 &mentioned,
1183 selected_id.as_deref(),
1184 )
1185 } else {
1186 build_sections(&input)
1187 };
1146 1188 let menu = MenuContext {
1147 1189 state: self.state.clone(),
1148 1190 folders: state.directory.move_targets(),
@@ -1267,6 +1309,10 @@ impl SidebarView {
1267 1309 .child(LOADING_OLDER_LABEL),
1268 1310 );
1269 1311 }
1312 let selected_chat_id = self.selected_chat_id(cx);
1313 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1314 list = list.child(self.filter_empty_state(cx));
1315 }
1270 1316 list = with_spacer(list, &mut skipped_height);
1271 1317 self.request_lazy_data(faces, presence_users, cx);
1272 1318 let scroll_area = div()
@@ -1952,9 +1998,15 @@ impl Render for SidebarView {
1952 1998 };
1953 1999 let header = match self.tab {
1954 2000 SidebarTab::Chats => Some(
1955 page_header(self.tab.title())
1956 .child(self.chat_list_menu_button(cx))
1957 .child(self.new_chat_button(cx)),
2001 v_flex()
2002 .flex_none()
2003 .child(
2004 page_header(self.tab.title())
2005 .child(self.chat_list_menu_button(cx))
2006 .child(self.filter_toggle_button(cx))
2007 .child(self.new_chat_button(cx)),
2008 )
2009 .child(self.filter_bar(cx)),
1958 2010 ),
1959 2011 SidebarTab::Channels => {
1960 2012 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
@@ -28,6 +28,7 @@ use crate::channel_menu::{
28 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
28 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
29};
29};
30use crate::chat_actions::TITLE_LIMIT;
30use crate::chat_actions::TITLE_LIMIT;
31use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
31use crate::data::{Directory, is_pending_folder};
32use crate::data::{Directory, is_pending_folder};
32use crate::format;
33use crate::format;
33use crate::local_previews::LocalPreview;
34use crate::local_previews::LocalPreview;
@@ -41,6 +42,9 @@ use crate::sidebar_model::{
41};
42};
42use crate::theme;
43use crate::theme;
43use app_ui_kit::layout::SIDEBAR_WIDTH;
44use app_ui_kit::layout::SIDEBAR_WIDTH;
45use gpui_kit::component::input::InputState;
46
47pub(crate) mod chat_filter_bar;
44
48
45pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
49pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
46const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
50const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -523,6 +527,12 @@ pub(crate) fn confirm_leave(
523 });
527 });
524}
528}
525
529
530pub enum SidebarEvent {
531 RestoreFocus,
532}
533
534impl EventEmitter<SidebarEvent> for SidebarView {}
535
526pub struct SidebarView {
536pub struct SidebarView {
527 state: Entity<AppState>,
537 state: Entity<AppState>,
528 tab: SidebarTab,
538 tab: SidebarTab,
@@ -537,6 +547,12 @@ pub struct SidebarView {
537 older_chats_seen: Cell<(bool, bool)>,
547 older_chats_seen: Cell<(bool, bool)>,
538 channels_scroll: ScrollHandle,
548 channels_scroll: ScrollHandle,
539 calls_scroll: ScrollHandle,
549 calls_scroll: ScrollHandle,
550 chat_filter: ChatFilter,
551 filter_box_open: bool,
552 more_filters_open: bool,
553 filter_input: Option<Entity<InputState>>,
554 filter_subscription: Option<Subscription>,
555 _activity_observation: Subscription,
540 _subscription: Subscription,
556 _subscription: Subscription,
541 _state_observation: Subscription,
557 _state_observation: Subscription,
542 _agent_observation: Option<Subscription>,
558 _agent_observation: Option<Subscription>,
@@ -627,6 +643,15 @@ impl SidebarView {
627 SidebarTab::Chats
643 SidebarTab::Chats
628 };
644 };
629 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
645 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
646 let activity = activity_panel.read(cx).activity();
647 let activity_observation = cx.observe(&activity, |view, _, cx| {
648 if view
649 .chat_filter
650 .has(crate::chat_filter::ChatFilterPill::Mentions)
651 {
652 cx.notify();
653 }
654 });
630 cx.spawn(async move |this, cx| {
655 cx.spawn(async move |this, cx| {
631 loop {
656 loop {
632 cx.background_executor().timer(CALLS_REFRESH).await;
657 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -655,6 +680,12 @@ impl SidebarView {
655 older_chats_seen: Cell::new((false, false)),
680 older_chats_seen: Cell::new((false, false)),
656 channels_scroll: ScrollHandle::new(),
681 channels_scroll: ScrollHandle::new(),
657 calls_scroll: ScrollHandle::new(),
682 calls_scroll: ScrollHandle::new(),
683 chat_filter: ChatFilter::default(),
684 filter_box_open: false,
685 more_filters_open: false,
686 filter_input: None,
687 filter_subscription: None,
688 _activity_observation: activity_observation,
658 _subscription: subscription,
689 _subscription: subscription,
659 _state_observation: state_observation,
690 _state_observation: state_observation,
660 _agent_observation: agent_observation,
691 _agent_observation: agent_observation,
@@ -1142,7 +1173,18 @@ impl SidebarView {
1142 now,
1173 now,
1143 offset,
1174 offset,
1144 };
1175 };
1145 let sections = build_sections(&input);
1176 let sections = if self.chat_filter.is_active() {
1177 let mentioned = self.mentioned_chats(cx);
1178 let selected_id = self.selected_chat_id(cx);
1179 filtered_sections(
1180 &input,
1181 &self.chat_filter,
1182 &mentioned,
1183 selected_id.as_deref(),
1184 )
1185 } else {
1186 build_sections(&input)
1187 };
1146 let menu = MenuContext {
1188 let menu = MenuContext {
1147 state: self.state.clone(),
1189 state: self.state.clone(),
1148 folders: state.directory.move_targets(),
1190 folders: state.directory.move_targets(),
@@ -1267,6 +1309,10 @@ impl SidebarView {
1267 .child(LOADING_OLDER_LABEL),
1309 .child(LOADING_OLDER_LABEL),
1268 );
1310 );
1269 }
1311 }
1312 let selected_chat_id = self.selected_chat_id(cx);
1313 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1314 list = list.child(self.filter_empty_state(cx));
1315 }
1270 list = with_spacer(list, &mut skipped_height);
1316 list = with_spacer(list, &mut skipped_height);
1271 self.request_lazy_data(faces, presence_users, cx);
1317 self.request_lazy_data(faces, presence_users, cx);
1272 let scroll_area = div()
1318 let scroll_area = div()
@@ -1952,9 +1998,15 @@ impl Render for SidebarView {
1952 };
1998 };
1953 let header = match self.tab {
1999 let header = match self.tab {
1954 SidebarTab::Chats => Some(
2000 SidebarTab::Chats => Some(
1955 page_header(self.tab.title())
2001 v_flex()
1956 .child(self.chat_list_menu_button(cx))
2002 .flex_none()
1957 .child(self.new_chat_button(cx)),
2003 .child(
2004 page_header(self.tab.title())
2005 .child(self.chat_list_menu_button(cx))
2006 .child(self.filter_toggle_button(cx))
2007 .child(self.new_chat_button(cx)),
2008 )
2009 .child(self.filter_bar(cx)),
1958 ),
2010 ),
1959 SidebarTab::Channels => {
2011 SidebarTab::Channels => {
1960 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
2012 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
crates/app/src/views/sidebar/chat_filter_bar.rs added +320 −0
@@ -0,0 +1,320 @@
1 use std::collections::HashSet;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8
9 use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10 use crate::app_state::Selection;
11 use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FEWER_FILTERS,
13 FILTER_PLACEHOLDER, MORE_FILTERS, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14 };
15 use crate::theme;
16 use crate::views::widgets::icon;
17
18 pub const FILTER_TAG: &str = "shell/islands/sidebar/chat-filter";
19 pub const FILTER_INPUT_TAG: &str = "shell/islands/sidebar/chat-filter/input";
20 pub const FILTER_PILLS_TAG: &str = "shell/islands/sidebar/chat-filter/pills";
21 pub const FILTER_EMPTY_TAG: &str = "shell/islands/sidebar/chat-filter-empty";
22 const INPUT_HEIGHT: f32 = 32.;
23 const PILL_HEIGHT: f32 = 24.;
24 const SIDE_INSET: f32 = 16.;
25
26 impl SidebarView {
27 pub fn toggle_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28 if self.tab != SidebarTab::Chats {
29 self.open_tab(SidebarTab::Chats, cx);
30 } else if self.filter_box_open {
31 self.close_filter_box(window, cx);
32 return;
33 }
34 self.filter_box_open = true;
35 let input = self.filter_input(window, cx);
36 input.update(cx, |input, cx| input.focus(window, cx));
37 cx.notify();
38 }
39
40 pub fn toggle_pill(&mut self, pill: ChatFilterPill, cx: &mut Context<Self>) {
41 if self.tab != SidebarTab::Chats {
42 self.open_tab(SidebarTab::Chats, cx);
43 }
44 if self.chat_filter.toggle(pill) {
45 cx.notify();
46 }
47 }
48
49 pub fn clear_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) {
50 self.chat_filter.clear();
51 if let Some(input) = &self.filter_input {
52 input.update(cx, |input, cx| input.set_value("", window, cx));
53 }
54 cx.notify();
55 }
56
57 pub(super) fn mentioned_chats(&self, cx: &App) -> HashSet<String> {
58 if !self.chat_filter.has(ChatFilterPill::Mentions) {
59 return HashSet::new();
60 }
61 let activity = self.activity_panel.read(cx).activity();
62 mentioned_conversations(activity.read(cx).feed().unread_entries())
63 }
64
65 pub(super) fn selected_chat_id(&self, cx: &App) -> Option<String> {
66 match &self.state.read(cx).selection {
67 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
68 _ => None,
69 }
70 }
71
72 fn close_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
73 self.filter_box_open = false;
74 cx.emit(SidebarEvent::RestoreFocus);
75 self.chat_filter.text.clear();
76 if let Some(input) = &self.filter_input {
77 input.update(cx, |input, cx| input.set_value("", window, cx));
78 }
79 cx.notify();
80 }
81
82 fn filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
83 if let Some(input) = &self.filter_input {
84 return input.clone();
85 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 if matches!(event, InputEvent::Change) {
89 this.chat_filter.text = input.read(cx).value().to_string();
90 cx.notify();
91 }
92 });
93 self.filter_subscription = Some(subscription);
94 self.filter_input = Some(input.clone());
95 input
96 }
97
98 pub(super) fn filter_toggle_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
99 let open = self.filter_box_open;
100 let active = open || self.chat_filter.is_active();
101 let label = if open {
102 CLOSE_FILTER_TEXT
103 } else {
104 SHOW_FILTER_TEXT
105 };
106 div()
107 .id("chat-filter-toggle")
108 .size(px(NEW_CHAT_BUTTON_SIZE))
109 .flex_none()
110 .flex()
111 .items_center()
112 .justify_center()
113 .rounded(px(8.))
114 .cursor_pointer()
115 .when(active, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 })
120 .child(icon(
121 IconName::Funnel,
122 16.,
123 if active {
124 theme::accent_text()
125 } else {
126 theme::text_soft()
127 },
128 ))
129 .on_click(cx.listener(|this, _, window, cx| this.toggle_filter_box(window, cx)))
130 }
131
132 pub(super) fn filter_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
133 let input_row = self
134 .filter_input
135 .clone()
136 .filter(|_| self.filter_box_open)
137 .map(|input| self.filter_input_row(&input, cx));
138 v_flex()
139 .debug_selector(|| FILTER_TAG.into())
140 .flex_none()
141 .w_full()
142 .pb(px(8.))
143 .gap(px(8.))
144 .children(input_row)
145 .child(self.filter_pills(cx))
146 }
147
148 fn filter_input_row(&self, input: &Entity<InputState>, cx: &mut Context<Self>) -> Div {
149 let has_text = !self.chat_filter.text.is_empty();
150 h_flex()
151 .debug_selector(|| FILTER_INPUT_TAG.into())
152 .mx(px(SIDE_INSET))
153 .h(px(INPUT_HEIGHT))
154 .flex_none()
155 .pl(px(10.))
156 .pr(px(4.))
157 .gap(px(8.))
158 .items_center()
159 .rounded(px(6.))
160 .bg(theme::surface_raised())
161 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
162 this.close_filter_box(window, cx);
163 cx.stop_propagation();
164 }))
165 .child(icon(IconName::Funnel, 14., theme::text_muted()))
166 .child(
167 div()
168 .flex_1()
169 .min_w_0()
170 .child(Input::new(input).appearance(false).bordered(false)),
171 )
172 .when(has_text, |row| {
173 row.child(
174 div()
175 .id("chat-filter-clear-text")
176 .size(px(PILL_HEIGHT))
177 .flex_none()
178 .flex()
179 .items_center()
180 .justify_center()
181 .rounded(px(6.))
182 .cursor_pointer()
183 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
185 .child(icon(IconName::X, 14., theme::text_muted()))
186 .on_click(cx.listener(|this, _, window, cx| {
187 this.chat_filter.text.clear();
188 if let Some(input) = &this.filter_input {
189 input.update(cx, |input, cx| {
190 input.set_value("", window, cx);
191 input.focus(window, cx);
192 });
193 }
194 cx.notify();
195 })),
196 )
197 })
198 }
199
200 fn filter_pills(&self, cx: &mut Context<Self>) -> impl IntoElement {
201 let overflow_active = ChatFilterPill::OVERFLOW
202 .iter()
203 .any(|pill| self.chat_filter.has(*pill));
204 let show_overflow = self.more_filters_open || overflow_active;
205 let mut pills: Vec<AnyElement> = ChatFilterPill::PRIMARY
206 .into_iter()
207 .map(|pill| self.filter_pill(pill, cx).into_any_element())
208 .collect();
209 if show_overflow {
210 pills.extend(
211 ChatFilterPill::OVERFLOW
212 .into_iter()
213 .map(|pill| self.filter_pill(pill, cx).into_any_element()),
214 );
215 }
216 if !overflow_active {
217 pills.push(self.more_filters_button(cx).into_any_element());
218 }
219 h_flex()
220 .debug_selector(|| FILTER_PILLS_TAG.into())
221 .px(px(SIDE_INSET))
222 .flex_wrap()
223 .gap(px(6.))
224 .children(pills)
225 }
226
227 fn filter_pill(&self, pill: ChatFilterPill, cx: &mut Context<Self>) -> impl IntoElement {
228 let selected = self.chat_filter.has(pill);
229 let disabled = self.chat_filter.is_disabled(pill);
230 div()
231 .id(ElementId::Name(
232 format!("chat-filter-{}", pill.label()).into(),
233 ))
234 .h(px(PILL_HEIGHT))
235 .px(px(12.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .rounded_full()
240 .text_size(px(12.))
241 .when(selected, |chip| {
242 chip.bg(theme::accent()).text_color(theme::on_accent())
243 })
244 .when(!selected && disabled, |chip| {
245 chip.bg(theme::surface_raised())
246 .text_color(theme::text_faint())
247 })
248 .when(!selected && !disabled, |chip| {
249 chip.bg(theme::surface_raised())
250 .text_color(theme::text_soft())
251 .cursor_pointer()
252 .hover(|chip| chip.bg(theme::border_strong()))
253 })
254 .child(pill.label())
255 .when(!disabled, |chip| {
256 chip.on_click(cx.listener(move |this, _, _, cx| this.toggle_pill(pill, cx)))
257 })
258 }
259
260 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
261 let open = self.more_filters_open;
262 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
263 div()
264 .id("chat-filter-more")
265 .size(px(PILL_HEIGHT))
266 .flex()
267 .flex_none()
268 .items_center()
269 .justify_center()
270 .rounded_full()
271 .cursor_pointer()
272 .bg(theme::surface_raised())
273 .hover(|chip| chip.bg(theme::border_strong()))
274 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
275 .child(icon(
276 if open {
277 IconName::ChevronUp
278 } else {
279 IconName::ChevronDown
280 },
281 14.,
282 theme::text_soft(),
283 ))
284 .on_click(cx.listener(|this, _, _, cx| {
285 this.more_filters_open = !this.more_filters_open;
286 cx.notify();
287 }))
288 }
289
290 pub(super) fn filter_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
291 v_flex()
292 .debug_selector(|| FILTER_EMPTY_TAG.into())
293 .w_full()
294 .px(px(SIDE_INSET))
295 .py(px(SIDE_INSET))
296 .gap(px(8.))
297 .items_center()
298 .child(
299 div()
300 .text_size(px(13.))
301 .text_color(theme::text_muted())
302 .child(NO_MATCHES),
303 )
304 .child(
305 div()
306 .id("chat-filter-clear-all")
307 .px(px(8.))
308 .h(px(PILL_HEIGHT))
309 .flex()
310 .items_center()
311 .rounded(px(6.))
312 .cursor_pointer()
313 .text_size(px(12.))
314 .text_color(theme::accent_text())
315 .hover(|button| button.bg(theme::surface_raised()))
316 .child(CLEAR_FILTERS)
317 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
318 )
319 }
320 }
@@ -0,0 +1,320 @@
1use std::collections::HashSet;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10use crate::app_state::Selection;
11use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FEWER_FILTERS,
13 FILTER_PLACEHOLDER, MORE_FILTERS, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14};
15use crate::theme;
16use crate::views::widgets::icon;
17
18pub const FILTER_TAG: &str = "shell/islands/sidebar/chat-filter";
19pub const FILTER_INPUT_TAG: &str = "shell/islands/sidebar/chat-filter/input";
20pub const FILTER_PILLS_TAG: &str = "shell/islands/sidebar/chat-filter/pills";
21pub const FILTER_EMPTY_TAG: &str = "shell/islands/sidebar/chat-filter-empty";
22const INPUT_HEIGHT: f32 = 32.;
23const PILL_HEIGHT: f32 = 24.;
24const SIDE_INSET: f32 = 16.;
25
26impl SidebarView {
27 pub fn toggle_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28 if self.tab != SidebarTab::Chats {
29 self.open_tab(SidebarTab::Chats, cx);
30 } else if self.filter_box_open {
31 self.close_filter_box(window, cx);
32 return;
33 }
34 self.filter_box_open = true;
35 let input = self.filter_input(window, cx);
36 input.update(cx, |input, cx| input.focus(window, cx));
37 cx.notify();
38 }
39
40 pub fn toggle_pill(&mut self, pill: ChatFilterPill, cx: &mut Context<Self>) {
41 if self.tab != SidebarTab::Chats {
42 self.open_tab(SidebarTab::Chats, cx);
43 }
44 if self.chat_filter.toggle(pill) {
45 cx.notify();
46 }
47 }
48
49 pub fn clear_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) {
50 self.chat_filter.clear();
51 if let Some(input) = &self.filter_input {
52 input.update(cx, |input, cx| input.set_value("", window, cx));
53 }
54 cx.notify();
55 }
56
57 pub(super) fn mentioned_chats(&self, cx: &App) -> HashSet<String> {
58 if !self.chat_filter.has(ChatFilterPill::Mentions) {
59 return HashSet::new();
60 }
61 let activity = self.activity_panel.read(cx).activity();
62 mentioned_conversations(activity.read(cx).feed().unread_entries())
63 }
64
65 pub(super) fn selected_chat_id(&self, cx: &App) -> Option<String> {
66 match &self.state.read(cx).selection {
67 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
68 _ => None,
69 }
70 }
71
72 fn close_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
73 self.filter_box_open = false;
74 cx.emit(SidebarEvent::RestoreFocus);
75 self.chat_filter.text.clear();
76 if let Some(input) = &self.filter_input {
77 input.update(cx, |input, cx| input.set_value("", window, cx));
78 }
79 cx.notify();
80 }
81
82 fn filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
83 if let Some(input) = &self.filter_input {
84 return input.clone();
85 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 if matches!(event, InputEvent::Change) {
89 this.chat_filter.text = input.read(cx).value().to_string();
90 cx.notify();
91 }
92 });
93 self.filter_subscription = Some(subscription);
94 self.filter_input = Some(input.clone());
95 input
96 }
97
98 pub(super) fn filter_toggle_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
99 let open = self.filter_box_open;
100 let active = open || self.chat_filter.is_active();
101 let label = if open {
102 CLOSE_FILTER_TEXT
103 } else {
104 SHOW_FILTER_TEXT
105 };
106 div()
107 .id("chat-filter-toggle")
108 .size(px(NEW_CHAT_BUTTON_SIZE))
109 .flex_none()
110 .flex()
111 .items_center()
112 .justify_center()
113 .rounded(px(8.))
114 .cursor_pointer()
115 .when(active, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 })
120 .child(icon(
121 IconName::Funnel,
122 16.,
123 if active {
124 theme::accent_text()
125 } else {
126 theme::text_soft()
127 },
128 ))
129 .on_click(cx.listener(|this, _, window, cx| this.toggle_filter_box(window, cx)))
130 }
131
132 pub(super) fn filter_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
133 let input_row = self
134 .filter_input
135 .clone()
136 .filter(|_| self.filter_box_open)
137 .map(|input| self.filter_input_row(&input, cx));
138 v_flex()
139 .debug_selector(|| FILTER_TAG.into())
140 .flex_none()
141 .w_full()
142 .pb(px(8.))
143 .gap(px(8.))
144 .children(input_row)
145 .child(self.filter_pills(cx))
146 }
147
148 fn filter_input_row(&self, input: &Entity<InputState>, cx: &mut Context<Self>) -> Div {
149 let has_text = !self.chat_filter.text.is_empty();
150 h_flex()
151 .debug_selector(|| FILTER_INPUT_TAG.into())
152 .mx(px(SIDE_INSET))
153 .h(px(INPUT_HEIGHT))
154 .flex_none()
155 .pl(px(10.))
156 .pr(px(4.))
157 .gap(px(8.))
158 .items_center()
159 .rounded(px(6.))
160 .bg(theme::surface_raised())
161 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
162 this.close_filter_box(window, cx);
163 cx.stop_propagation();
164 }))
165 .child(icon(IconName::Funnel, 14., theme::text_muted()))
166 .child(
167 div()
168 .flex_1()
169 .min_w_0()
170 .child(Input::new(input).appearance(false).bordered(false)),
171 )
172 .when(has_text, |row| {
173 row.child(
174 div()
175 .id("chat-filter-clear-text")
176 .size(px(PILL_HEIGHT))
177 .flex_none()
178 .flex()
179 .items_center()
180 .justify_center()
181 .rounded(px(6.))
182 .cursor_pointer()
183 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
185 .child(icon(IconName::X, 14., theme::text_muted()))
186 .on_click(cx.listener(|this, _, window, cx| {
187 this.chat_filter.text.clear();
188 if let Some(input) = &this.filter_input {
189 input.update(cx, |input, cx| {
190 input.set_value("", window, cx);
191 input.focus(window, cx);
192 });
193 }
194 cx.notify();
195 })),
196 )
197 })
198 }
199
200 fn filter_pills(&self, cx: &mut Context<Self>) -> impl IntoElement {
201 let overflow_active = ChatFilterPill::OVERFLOW
202 .iter()
203 .any(|pill| self.chat_filter.has(*pill));
204 let show_overflow = self.more_filters_open || overflow_active;
205 let mut pills: Vec<AnyElement> = ChatFilterPill::PRIMARY
206 .into_iter()
207 .map(|pill| self.filter_pill(pill, cx).into_any_element())
208 .collect();
209 if show_overflow {
210 pills.extend(
211 ChatFilterPill::OVERFLOW
212 .into_iter()
213 .map(|pill| self.filter_pill(pill, cx).into_any_element()),
214 );
215 }
216 if !overflow_active {
217 pills.push(self.more_filters_button(cx).into_any_element());
218 }
219 h_flex()
220 .debug_selector(|| FILTER_PILLS_TAG.into())
221 .px(px(SIDE_INSET))
222 .flex_wrap()
223 .gap(px(6.))
224 .children(pills)
225 }
226
227 fn filter_pill(&self, pill: ChatFilterPill, cx: &mut Context<Self>) -> impl IntoElement {
228 let selected = self.chat_filter.has(pill);
229 let disabled = self.chat_filter.is_disabled(pill);
230 div()
231 .id(ElementId::Name(
232 format!("chat-filter-{}", pill.label()).into(),
233 ))
234 .h(px(PILL_HEIGHT))
235 .px(px(12.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .rounded_full()
240 .text_size(px(12.))
241 .when(selected, |chip| {
242 chip.bg(theme::accent()).text_color(theme::on_accent())
243 })
244 .when(!selected && disabled, |chip| {
245 chip.bg(theme::surface_raised())
246 .text_color(theme::text_faint())
247 })
248 .when(!selected && !disabled, |chip| {
249 chip.bg(theme::surface_raised())
250 .text_color(theme::text_soft())
251 .cursor_pointer()
252 .hover(|chip| chip.bg(theme::border_strong()))
253 })
254 .child(pill.label())
255 .when(!disabled, |chip| {
256 chip.on_click(cx.listener(move |this, _, _, cx| this.toggle_pill(pill, cx)))
257 })
258 }
259
260 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
261 let open = self.more_filters_open;
262 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
263 div()
264 .id("chat-filter-more")
265 .size(px(PILL_HEIGHT))
266 .flex()
267 .flex_none()
268 .items_center()
269 .justify_center()
270 .rounded_full()
271 .cursor_pointer()
272 .bg(theme::surface_raised())
273 .hover(|chip| chip.bg(theme::border_strong()))
274 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
275 .child(icon(
276 if open {
277 IconName::ChevronUp
278 } else {
279 IconName::ChevronDown
280 },
281 14.,
282 theme::text_soft(),
283 ))
284 .on_click(cx.listener(|this, _, _, cx| {
285 this.more_filters_open = !this.more_filters_open;
286 cx.notify();
287 }))
288 }
289
290 pub(super) fn filter_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
291 v_flex()
292 .debug_selector(|| FILTER_EMPTY_TAG.into())
293 .w_full()
294 .px(px(SIDE_INSET))
295 .py(px(SIDE_INSET))
296 .gap(px(8.))
297 .items_center()
298 .child(
299 div()
300 .text_size(px(13.))
301 .text_color(theme::text_muted())
302 .child(NO_MATCHES),
303 )
304 .child(
305 div()
306 .id("chat-filter-clear-all")
307 .px(px(8.))
308 .h(px(PILL_HEIGHT))
309 .flex()
310 .items_center()
311 .rounded(px(6.))
312 .cursor_pointer()
313 .text_size(px(12.))
314 .text_color(theme::accent_text())
315 .hover(|button| button.bg(theme::surface_raised()))
316 .child(CLEAR_FILTERS)
317 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
318 )
319 }
320}