BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / find_panel.rs

find_panel.rs

find_panel.rs 22.1 KiB Download Raw
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}