BlueGit

ict rusty-teams

feat(find): Find in chat side panel on Ctrl+F like Teams

- Right panel "Find in chat" / "Find in channel" with input and From, Date, Has attachment, @Mentions chips
- Local FTS first, then Substrate clientthreadid query, deduped by message id
- Results grouped by month (This month, Last month, Month Year), click jumps and highlights
- Enter / Shift+Enter step through hits, Esc closes and returns focus to the composer
- Narrow windows overlay the timeline; unit tests and layout_guard screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
b832c46a39049e69dbb3098260d94a374724a771
Parent
240d6149
8 files changed +1238 −25
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 +1 −0
@@ -11,6 +11,7 @@ pub mod card_refresh;
11 11 pub mod card_state;
12 12 pub mod chat_actions;
13 13 pub mod chat_filter;
14 pub mod find_in_chat;
14 15 pub mod chat_members;
15 16 pub mod connection_banner;
16 17 pub mod data;
@@ -11,6 +11,7 @@ pub mod card_refresh;
11pub mod card_state;
11pub mod card_state;
12pub mod chat_actions;
12pub mod chat_actions;
13pub mod chat_filter;
13pub mod chat_filter;
14pub mod find_in_chat;
14pub mod chat_members;
15pub mod chat_members;
15pub mod connection_banner;
16pub mod connection_banner;
16pub mod data;
17pub mod data;
crates/app/src/layout_guard.rs +25 −1
@@ -181,6 +181,9 @@ mod frames {
181 181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 182 };
183 183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
184 use crate::views::find_panel::{
185 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
186 };
184 187 use crate::views::message_row::BUBBLE_TAGS;
185 188 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186 189 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -189,7 +192,7 @@ mod frames {
189 192 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
190 193 };
191 194 use crate::views::shortcuts::{
192 ClearChatFilters, FilterMutedChats, OpenActivity, OpenAgents, OpenCallsTab,
195 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
193 196 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
194 197 };
195 198 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
@@ -220,6 +223,12 @@ mod frames {
220 223 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
221 224 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
222 225 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
226 const FIND_TAGS: &[&str] = &[
227 FIND_PANEL_TAG,
228 FIND_DIVIDER_TAG,
229 FIND_INPUT_TAG,
230 FIND_RESULTS_TAG,
231 ];
223 232 const CALLS_TAGS: &[&str] = &[
224 233 "shell/islands/sidebar/calls-actions",
225 234 "shell/islands/sidebar/calls-actions/meet-now",
@@ -562,6 +571,7 @@ mod frames {
562 571 .chain(CALLS_TAGS)
563 572 .chain(CHAT_FILTER_TAGS)
564 573 .chain(CHAT_FILTER_OPEN_TAGS)
574 .chain(FIND_TAGS)
565 575 .chain(PREJOIN_TAGS)
566 576 .chain(SHARE_GUARDED)
567 577 .chain(CONSULT_GUARDED)
@@ -783,6 +793,15 @@ mod frames {
783 793 visual.simulate_input("zzz");
784 794 }),
785 795 ),
796 Screen::Tab(
797 "find",
798 Some(|visual| {
799 visual.dispatch_action(OpenChatsTab);
800 visual.dispatch_action(FindInChat);
801 visual.run_until_parked();
802 visual.simulate_input("access");
803 }),
804 ),
786 805 Screen::Tab(
787 806 "activity",
788 807 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -920,6 +939,7 @@ mod frames {
920 939 expected.extend(CHAT_FILTER_TAGS);
921 940 expected.extend(CHAT_FILTER_OPEN_TAGS);
922 941 }
942 "find" => expected.extend(FIND_TAGS),
923 943 "calls" => expected.extend(CALLS_TAGS),
924 944 "agents" => expected.push(AGENTS_LIST),
925 945 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -959,6 +979,10 @@ mod frames {
959 979 })
960 980 });
961 981 }
982 if screen_name == "find" {
983 visual.dispatch_action(gpui_kit::component::input::Escape);
984 visual.run_until_parked();
985 }
962 986 if screen_name == "chat-filter" {
963 987 visual.dispatch_action(ClearChatFilters);
964 988 visual.dispatch_action(OpenChatFilter);
@@ -181,6 +181,9 @@ mod frames {
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
182 };
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
183 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON};
184 use crate::views::find_panel::{
185 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
186 };
184 use crate::views::message_row::BUBBLE_TAGS;
187 use crate::views::message_row::BUBBLE_TAGS;
185 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
188 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
186 use crate::views::reaction_proposal_pill::REACTION_PILL;
189 use crate::views::reaction_proposal_pill::REACTION_PILL;
@@ -189,7 +192,7 @@ mod frames {
189 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
192 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
190 };
193 };
191 use crate::views::shortcuts::{
194 use crate::views::shortcuts::{
192 ClearChatFilters, FilterMutedChats, OpenActivity, OpenAgents, OpenCallsTab,
195 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
193 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
196 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
194 };
197 };
195 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
198 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
@@ -220,6 +223,12 @@ mod frames {
220 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
223 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
221 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
224 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
222 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
225 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
226 const FIND_TAGS: &[&str] = &[
227 FIND_PANEL_TAG,
228 FIND_DIVIDER_TAG,
229 FIND_INPUT_TAG,
230 FIND_RESULTS_TAG,
231 ];
223 const CALLS_TAGS: &[&str] = &[
232 const CALLS_TAGS: &[&str] = &[
224 "shell/islands/sidebar/calls-actions",
233 "shell/islands/sidebar/calls-actions",
225 "shell/islands/sidebar/calls-actions/meet-now",
234 "shell/islands/sidebar/calls-actions/meet-now",
@@ -562,6 +571,7 @@ mod frames {
562 .chain(CALLS_TAGS)
571 .chain(CALLS_TAGS)
563 .chain(CHAT_FILTER_TAGS)
572 .chain(CHAT_FILTER_TAGS)
564 .chain(CHAT_FILTER_OPEN_TAGS)
573 .chain(CHAT_FILTER_OPEN_TAGS)
574 .chain(FIND_TAGS)
565 .chain(PREJOIN_TAGS)
575 .chain(PREJOIN_TAGS)
566 .chain(SHARE_GUARDED)
576 .chain(SHARE_GUARDED)
567 .chain(CONSULT_GUARDED)
577 .chain(CONSULT_GUARDED)
@@ -783,6 +793,15 @@ mod frames {
783 visual.simulate_input("zzz");
793 visual.simulate_input("zzz");
784 }),
794 }),
785 ),
795 ),
796 Screen::Tab(
797 "find",
798 Some(|visual| {
799 visual.dispatch_action(OpenChatsTab);
800 visual.dispatch_action(FindInChat);
801 visual.run_until_parked();
802 visual.simulate_input("access");
803 }),
804 ),
786 Screen::Tab(
805 Screen::Tab(
787 "activity",
806 "activity",
788 Some(|visual| visual.dispatch_action(OpenActivity)),
807 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -920,6 +939,7 @@ mod frames {
920 expected.extend(CHAT_FILTER_TAGS);
939 expected.extend(CHAT_FILTER_TAGS);
921 expected.extend(CHAT_FILTER_OPEN_TAGS);
940 expected.extend(CHAT_FILTER_OPEN_TAGS);
922 }
941 }
942 "find" => expected.extend(FIND_TAGS),
923 "calls" => expected.extend(CALLS_TAGS),
943 "calls" => expected.extend(CALLS_TAGS),
924 "agents" => expected.push(AGENTS_LIST),
944 "agents" => expected.push(AGENTS_LIST),
925 "prejoin" => expected.extend(PREJOIN_TAGS),
945 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -959,6 +979,10 @@ mod frames {
959 })
979 })
960 });
980 });
961 }
981 }
982 if screen_name == "find" {
983 visual.dispatch_action(gpui_kit::component::input::Escape);
984 visual.run_until_parked();
985 }
962 if screen_name == "chat-filter" {
986 if screen_name == "chat-filter" {
963 visual.dispatch_action(ClearChatFilters);
987 visual.dispatch_action(ClearChatFilters);
964 visual.dispatch_action(OpenChatFilter);
988 visual.dispatch_action(OpenChatFilter);
crates/app/src/views/conversation.rs +100 −23
@@ -33,15 +33,16 @@ mod render_env;
33 33 mod scheduled;
34 34 mod shared;
35 35
36 use super::add_people_dialog::open_add_people;
36 37 use super::attachments::FileActions;
37 38 use super::avatar::{
38 39 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
39 40 };
40 41 use super::call_controls::header_call_controls;
41 42 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
42 use super::add_people_dialog::open_add_people;
43 43 use super::chat_members::members_popover;
44 44 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
45 use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
45 46 use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
46 47 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
47 48 use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
@@ -53,7 +54,6 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
53 54 use super::scroll_edge::edge_divider;
54 55 use super::toolbar_placement::{TimelineBounds, record_bounds};
55 56 use super::widgets::{icon, symbol};
56 use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
57 57 use crate::agents::{AgentRun, StartRequest};
58 58 use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
59 59 use crate::backend::Engine;
@@ -84,6 +84,7 @@ use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
84 84 use crate::theme;
85 85 use crate::translation::TranslationLine;
86 86 use crate::typing::typing_tooltip;
87 use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
87 88 use detached::DetachedWindow;
88 89 use feed::{FeedStash, subject_input};
89 90 use mcp::ReactionProposal;
@@ -97,6 +98,7 @@ const HEADER_PADDING: f32 = 20.;
97 98 const HEADER_GAP: f32 = 12.;
98 99 const HEADER_LEAD_SIZE: f32 = 36.;
99 100 const TABS_INLINE_MIN_WIDTH: f32 = 560.;
101 const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
100 102 const TABS_ROW_HEIGHT: f32 = 36.;
101 103 const CHAT_OPEN_LIMIT: usize = 60;
102 104 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -234,6 +236,8 @@ pub struct ConversationView {
234 236 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
235 237 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
236 238 receipt_fade: receipt_fade::ReceiptFade,
239 find_panel: Option<Entity<FindPanel>>,
240 find_subscription: Option<Subscription>,
237 241 _subscriptions: Vec<Subscription>,
238 242 }
239 243
@@ -563,6 +567,8 @@ impl ConversationView {
563 567 agent_runs: Rc::new(RefCell::new(HashMap::new())),
564 568 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
565 569 receipt_fade: receipt_fade::ReceiptFade::default(),
570 find_panel: None,
571 find_subscription: None,
566 572 _subscriptions: subscriptions,
567 573 };
568 574 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -838,6 +844,14 @@ impl ConversationView {
838 844 }
839 845
840 846 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
847 if self
848 .find_panel
849 .as_ref()
850 .is_some_and(|panel| panel.read(cx).selection() != &selection)
851 {
852 self.find_panel = None;
853 self.find_subscription = None;
854 }
841 855 self.stop_typing(cx);
842 856 self.stop_reply_typing(cx);
843 857 self.new_post_open = false;
@@ -3211,6 +3225,50 @@ impl ConversationView {
3211 3225 )
3212 3226 }
3213 3227
3228 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3229 if self.pinned || self.draft_active {
3230 return;
3231 }
3232 let Some(selection) = self
3233 .current
3234 .as_ref()
3235 .map(|current| current.selection.clone())
3236 else {
3237 return;
3238 };
3239 if let Some(panel) = &self.find_panel {
3240 panel.update(cx, |panel, cx| panel.focus(window, cx));
3241 return;
3242 }
3243 let app = self.app.clone();
3244 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3245 let subscription = cx.subscribe_in(
3246 &panel,
3247 window,
3248 move |this, _, event: &FindPanelEvent, window, cx| match event {
3249 FindPanelEvent::Close => this.close_find(window, cx),
3250 FindPanelEvent::Jump(message_id) => {
3251 let (selection, message_id) = (selection.clone(), message_id.clone());
3252 this.app.update(cx, |state, cx| {
3253 state.jump_to_message(selection, message_id, cx)
3254 });
3255 }
3256 },
3257 );
3258 panel.update(cx, |panel, cx| panel.focus(window, cx));
3259 self.find_panel = Some(panel);
3260 self.find_subscription = Some(subscription);
3261 cx.notify();
3262 }
3263
3264 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3265 self.find_panel = None;
3266 self.find_subscription = None;
3267 self.composer
3268 .update(cx, |composer, cx| composer.focus(window, cx));
3269 cx.notify();
3270 }
3271
3214 3272 fn header_width(&self, window: &Window) -> f32 {
3215 3273 match self.header_width.get() {
3216 3274 width if width > 0. => width,
@@ -3629,32 +3687,51 @@ impl Render for ConversationView {
3629 3687 } else {
3630 3688 scroller.into_any_element()
3631 3689 };
3690 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3691 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3692 let body_column = v_flex()
3693 .relative()
3694 .flex_1()
3695 .min_w_0()
3696 .min_h_0()
3697 .children(new_post)
3698 .child(
3699 div()
3700 .relative()
3701 .flex_1()
3702 .min_h_0()
3703 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3704 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3705 .child(body)
3706 .children(pin_banner.map(pin_banner_overlay)),
3707 )
3708 .children(self.render_draft_error(cx))
3709 .when(!in_feed && !recap_active, |column| {
3710 column
3711 .child(self.render_typing_line(cx))
3712 .children(self.render_proposal_card(cx))
3713 .child(self.composer.clone())
3714 })
3715 .child(self.render_drop_overlay(cx));
3632 3716 root.child(
3633 v_flex()
3717 div()
3634 3718 .relative()
3719 .flex()
3720 .flex_row()
3635 3721 .flex_1()
3636 3722 .min_h_0()
3637 .children(new_post)
3638 .child(
3723 .child(body_column)
3724 .children(find_panel.map(|panel| {
3639 3725 div()
3640 .relative()
3641 .flex_1()
3642 .min_h_0()
3643 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3644 .on_scroll_wheel(
3645 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3646 )
3647 .child(body)
3648 .children(pin_banner.map(pin_banner_overlay)),
3649 )
3650 .children(self.render_draft_error(cx))
3651 .when(!in_feed && !recap_active, |column| {
3652 column
3653 .child(self.render_typing_line(cx))
3654 .children(self.render_proposal_card(cx))
3655 .child(self.composer.clone())
3656 })
3657 .child(self.render_drop_overlay(cx)),
3726 .h_full()
3727 .w(px(FIND_PANEL_WIDTH))
3728 .min_w_0()
3729 .flex_shrink(1.)
3730 .when(find_overlays, |slot| {
3731 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3732 })
3733 .child(panel)
3734 })),
3658 3735 )
3659 3736 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3660 3737 if this.reaction_details.is_some() {
@@ -33,15 +33,16 @@ mod render_env;
33mod scheduled;
33mod scheduled;
34mod shared;
34mod shared;
35
35
36use super::add_people_dialog::open_add_people;
36use super::attachments::FileActions;
37use super::attachments::FileActions;
37use super::avatar::{
38use super::avatar::{
38 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
39 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
39};
40};
40use super::call_controls::header_call_controls;
41use super::call_controls::header_call_controls;
41use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
42use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
42use super::add_people_dialog::open_add_people;
43use super::chat_members::members_popover;
43use super::chat_members::members_popover;
44use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
44use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
45use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
45use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
46use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
46use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
47use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
47use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
48use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
@@ -53,7 +54,6 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
53use super::scroll_edge::edge_divider;
54use super::scroll_edge::edge_divider;
54use super::toolbar_placement::{TimelineBounds, record_bounds};
55use super::toolbar_placement::{TimelineBounds, record_bounds};
55use super::widgets::{icon, symbol};
56use super::widgets::{icon, symbol};
56use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
57use crate::agents::{AgentRun, StartRequest};
57use crate::agents::{AgentRun, StartRequest};
58use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
58use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
59use crate::backend::Engine;
59use crate::backend::Engine;
@@ -84,6 +84,7 @@ use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
84use crate::theme;
84use crate::theme;
85use crate::translation::TranslationLine;
85use crate::translation::TranslationLine;
86use crate::typing::typing_tooltip;
86use crate::typing::typing_tooltip;
87use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
87use detached::DetachedWindow;
88use detached::DetachedWindow;
88use feed::{FeedStash, subject_input};
89use feed::{FeedStash, subject_input};
89use mcp::ReactionProposal;
90use mcp::ReactionProposal;
@@ -97,6 +98,7 @@ const HEADER_PADDING: f32 = 20.;
97const HEADER_GAP: f32 = 12.;
98const HEADER_GAP: f32 = 12.;
98const HEADER_LEAD_SIZE: f32 = 36.;
99const HEADER_LEAD_SIZE: f32 = 36.;
99const TABS_INLINE_MIN_WIDTH: f32 = 560.;
100const TABS_INLINE_MIN_WIDTH: f32 = 560.;
101const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
100const TABS_ROW_HEIGHT: f32 = 36.;
102const TABS_ROW_HEIGHT: f32 = 36.;
101const CHAT_OPEN_LIMIT: usize = 60;
103const CHAT_OPEN_LIMIT: usize = 60;
102const CHANNEL_OPEN_LIMIT: usize = 300;
104const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -234,6 +236,8 @@ pub struct ConversationView {
234 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
236 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
235 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
237 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
236 receipt_fade: receipt_fade::ReceiptFade,
238 receipt_fade: receipt_fade::ReceiptFade,
239 find_panel: Option<Entity<FindPanel>>,
240 find_subscription: Option<Subscription>,
237 _subscriptions: Vec<Subscription>,
241 _subscriptions: Vec<Subscription>,
238}
242}
239
243
@@ -563,6 +567,8 @@ impl ConversationView {
563 agent_runs: Rc::new(RefCell::new(HashMap::new())),
567 agent_runs: Rc::new(RefCell::new(HashMap::new())),
564 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
568 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
565 receipt_fade: receipt_fade::ReceiptFade::default(),
569 receipt_fade: receipt_fade::ReceiptFade::default(),
570 find_panel: None,
571 find_subscription: None,
566 _subscriptions: subscriptions,
572 _subscriptions: subscriptions,
567 };
573 };
568 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
574 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -838,6 +844,14 @@ impl ConversationView {
838 }
844 }
839
845
840 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
846 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
847 if self
848 .find_panel
849 .as_ref()
850 .is_some_and(|panel| panel.read(cx).selection() != &selection)
851 {
852 self.find_panel = None;
853 self.find_subscription = None;
854 }
841 self.stop_typing(cx);
855 self.stop_typing(cx);
842 self.stop_reply_typing(cx);
856 self.stop_reply_typing(cx);
843 self.new_post_open = false;
857 self.new_post_open = false;
@@ -3211,6 +3225,50 @@ impl ConversationView {
3211 )
3225 )
3212 }
3226 }
3213
3227
3228 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3229 if self.pinned || self.draft_active {
3230 return;
3231 }
3232 let Some(selection) = self
3233 .current
3234 .as_ref()
3235 .map(|current| current.selection.clone())
3236 else {
3237 return;
3238 };
3239 if let Some(panel) = &self.find_panel {
3240 panel.update(cx, |panel, cx| panel.focus(window, cx));
3241 return;
3242 }
3243 let app = self.app.clone();
3244 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3245 let subscription = cx.subscribe_in(
3246 &panel,
3247 window,
3248 move |this, _, event: &FindPanelEvent, window, cx| match event {
3249 FindPanelEvent::Close => this.close_find(window, cx),
3250 FindPanelEvent::Jump(message_id) => {
3251 let (selection, message_id) = (selection.clone(), message_id.clone());
3252 this.app.update(cx, |state, cx| {
3253 state.jump_to_message(selection, message_id, cx)
3254 });
3255 }
3256 },
3257 );
3258 panel.update(cx, |panel, cx| panel.focus(window, cx));
3259 self.find_panel = Some(panel);
3260 self.find_subscription = Some(subscription);
3261 cx.notify();
3262 }
3263
3264 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3265 self.find_panel = None;
3266 self.find_subscription = None;
3267 self.composer
3268 .update(cx, |composer, cx| composer.focus(window, cx));
3269 cx.notify();
3270 }
3271
3214 fn header_width(&self, window: &Window) -> f32 {
3272 fn header_width(&self, window: &Window) -> f32 {
3215 match self.header_width.get() {
3273 match self.header_width.get() {
3216 width if width > 0. => width,
3274 width if width > 0. => width,
@@ -3629,32 +3687,51 @@ impl Render for ConversationView {
3629 } else {
3687 } else {
3630 scroller.into_any_element()
3688 scroller.into_any_element()
3631 };
3689 };
3690 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3691 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3692 let body_column = v_flex()
3693 .relative()
3694 .flex_1()
3695 .min_w_0()
3696 .min_h_0()
3697 .children(new_post)
3698 .child(
3699 div()
3700 .relative()
3701 .flex_1()
3702 .min_h_0()
3703 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3704 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3705 .child(body)
3706 .children(pin_banner.map(pin_banner_overlay)),
3707 )
3708 .children(self.render_draft_error(cx))
3709 .when(!in_feed && !recap_active, |column| {
3710 column
3711 .child(self.render_typing_line(cx))
3712 .children(self.render_proposal_card(cx))
3713 .child(self.composer.clone())
3714 })
3715 .child(self.render_drop_overlay(cx));
3632 root.child(
3716 root.child(
3633 v_flex()
3717 div()
3634 .relative()
3718 .relative()
3719 .flex()
3720 .flex_row()
3635 .flex_1()
3721 .flex_1()
3636 .min_h_0()
3722 .min_h_0()
3637 .children(new_post)
3723 .child(body_column)
3638 .child(
3724 .children(find_panel.map(|panel| {
3639 div()
3725 div()
3640 .relative()
3726 .h_full()
3641 .flex_1()
3727 .w(px(FIND_PANEL_WIDTH))
3642 .min_h_0()
3728 .min_w_0()
3643 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3729 .flex_shrink(1.)
3644 .on_scroll_wheel(
3730 .when(find_overlays, |slot| {
3645 cx.listener(|this, _, _, cx| this.close_reaction_details(cx)),
3731 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3646 )
3732 })
3647 .child(body)
3733 .child(panel)
3648 .children(pin_banner.map(pin_banner_overlay)),
3734 })),
3649 )
3650 .children(self.render_draft_error(cx))
3651 .when(!in_feed && !recap_active, |column| {
3652 column
3653 .child(self.render_typing_line(cx))
3654 .children(self.render_proposal_card(cx))
3655 .child(self.composer.clone())
3656 })
3657 .child(self.render_drop_overlay(cx)),
3658 )
3735 )
3659 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3736 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3660 if this.reaction_details.is_some() {
3737 if this.reaction_details.is_some() {
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
@@ -42,6 +42,7 @@ pub mod dialog_overlay;
42 42 pub mod emoji_popup;
43 43 pub mod format_toolbar;
44 44 pub mod forward_dialog;
45 pub mod find_panel;
45 46 pub mod fun_picker;
46 47 pub mod image_menu;
47 48 pub mod image_viewer;
@@ -42,6 +42,7 @@ pub mod dialog_overlay;
42pub mod emoji_popup;
42pub mod emoji_popup;
43pub mod format_toolbar;
43pub mod format_toolbar;
44pub mod forward_dialog;
44pub mod forward_dialog;
45pub mod find_panel;
45pub mod fun_picker;
46pub mod fun_picker;
46pub mod image_menu;
47pub mod image_menu;
47pub mod image_viewer;
48pub mod image_viewer;
crates/app/src/views/shell.rs +6 −1
@@ -21,7 +21,7 @@ use crate::chat_filter::ChatFilterPill;
21 21 use super::saved_panel::{SavedPanel, SavedPanelEvent};
22 22 use super::shortcuts::{
23 23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
24 FilterNonMeetingChats, FilterUnreadChats, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
26 26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
27 27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
@@ -975,6 +975,11 @@ impl Render for AppShell {
975 975 this.sidebar
976 976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
977 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 }))
978 983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
979 984 this.close_image_viewer(window, cx);
980 985 this.sidebar
@@ -21,7 +21,7 @@ use crate::chat_filter::ChatFilterPill;
21use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::saved_panel::{SavedPanel, SavedPanelEvent};
22use super::shortcuts::{
22use super::shortcuts::{
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
24 FilterNonMeetingChats, FilterUnreadChats, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
@@ -975,6 +975,11 @@ impl Render for AppShell {
975 this.sidebar
975 this.sidebar
976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
977 }))
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 }))
978 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
979 this.close_image_viewer(window, cx);
984 this.close_image_viewer(window, cx);
980 this.sidebar
985 this.sidebar
crates/app/src/views/shortcuts.rs +2 −0
@@ -30,6 +30,7 @@ actions!(
30 30 OpenCallsTab,
31 31 OpenAgents,
32 32 OpenChatFilter,
33 FindInChat,
33 34 FilterUnreadChats,
34 35 FilterNonMeetingChats,
35 36 FilterMeetingChats,
@@ -141,6 +142,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
141 142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
142 143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
143 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),
144 146 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
145 147 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
146 148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
@@ -30,6 +30,7 @@ actions!(
30 OpenCallsTab,
30 OpenCallsTab,
31 OpenAgents,
31 OpenAgents,
32 OpenChatFilter,
32 OpenChatFilter,
33 FindInChat,
33 FilterUnreadChats,
34 FilterUnreadChats,
34 FilterNonMeetingChats,
35 FilterNonMeetingChats,
35 FilterMeetingChats,
36 FilterMeetingChats,
@@ -141,6 +142,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
141 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
143 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
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),
144 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),
145 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),
146 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),