BlueGit

ict rusty-teams

Files

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

find_panel.rs

0ff9db96 History
find_panel.rs 22.5 KiB Download Raw
1use std::time::Duration;
2
3use chrono::{Local, NaiveDate};
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::scroll::ScrollableElement as _;
9use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use store::Store;
13use teams_core::substrate_search::{QueryRequest, QueryResults, QueryScope, SearchSession};
14
15use super::widgets::icon;
16use crate::app_state::{AppState, Selection};
17use crate::find_in_chat::{
18 DATE_LABEL, DateRange, EMPTY_HINT, FIND_IN_CHANNEL, FIND_IN_CHAT, FROM_LABEL, FindFilters,
19 FindHit, HAS_ATTACHMENT_LABEL, LOAD_ERROR, LOADING, MENTIONS_LABEL, NO_RESULTS_CHANNEL,
20 NO_RESULTS_CHAT, Sender, from_local, from_record, from_server, group_by_month, merge,
21 no_results_with_filters, same_user, step_index,
22};
23use crate::format;
24use crate::runtime;
25use crate::theme;
26
27pub const FIND_PANEL_TAG: &str = "shell/islands/main/find";
28pub const FIND_DIVIDER_TAG: &str = "shell/islands/main/find/divider-side";
29pub const FIND_INPUT_TAG: &str = "shell/islands/main/find/input";
30pub const FIND_RESULTS_TAG: &str = "shell/islands/main/find/results";
31pub const FIND_PANEL_WIDTH: f32 = 320.;
32const HEADER_HEIGHT: f32 = 48.;
33const SIDE_INSET: f32 = 16.;
34const INPUT_HEIGHT: f32 = 32.;
35const CHIP_HEIGHT: f32 = 24.;
36const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
37const LOCAL_LIMIT: usize = 100;
38const FILTER_SCAN_LIMIT: usize = 500;
39const SENDER_SCAN_LIMIT: usize = 200;
40
41pub enum FindPanelEvent {
42 Close,
43 Jump(String),
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47enum Status {
48 Idle,
49 Loading,
50 Ready,
51 Failed,
52}
53
54pub struct FindPanel {
55 app: Entity<AppState>,
56 selection: Selection,
57 input: Entity<InputState>,
58 query: String,
59 filters: FindFilters,
60 senders: Vec<Sender>,
61 local_hits: Vec<FindHit>,
62 hits: Vec<FindHit>,
63 status: Status,
64 generation: u64,
65 current_index: Option<usize>,
66 search_session: SearchSession,
67 scroll: ScrollHandle,
68 _subscription: Subscription,
69}
70
71impl EventEmitter<FindPanelEvent> for FindPanel {}
72
73impl FindPanel {
74 pub fn new(
75 app: Entity<AppState>,
76 selection: Selection,
77 window: &mut Window,
78 cx: &mut Context<Self>,
79 ) -> Self {
80 let title = panel_title(&selection);
81 let input = cx.new(|cx| InputState::new(window, cx).placeholder(title));
82 let subscription = cx.subscribe_in(&input, window, Self::on_input);
83 let senders = senders_of(app.read(cx), selection.conversation_id());
84 FindPanel {
85 app,
86 selection,
87 input,
88 query: String::new(),
89 filters: FindFilters::default(),
90 senders,
91 local_hits: Vec::new(),
92 hits: Vec::new(),
93 status: Status::Idle,
94 generation: 0,
95 current_index: None,
96 search_session: SearchSession::new(),
97 scroll: ScrollHandle::new(),
98 _subscription: subscription,
99 }
100 }
101
102 pub fn selection(&self) -> &Selection {
103 &self.selection
104 }
105
106 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
107 self.input.update(cx, |input, cx| input.focus(window, cx));
108 }
109
110 fn on_input(
111 &mut self,
112 input: &Entity<InputState>,
113 event: &InputEvent,
114 _: &mut Window,
115 cx: &mut Context<Self>,
116 ) {
117 match event {
118 InputEvent::Change => {
119 self.query = input.read(cx).value().trim().to_owned();
120 self.schedule_search(cx);
121 }
122 InputEvent::PressEnter { shift, .. } => self.step(*shift, cx),
123 _ => {}
124 }
125 }
126
127 fn step(&mut self, backwards: bool, cx: &mut Context<Self>) {
128 if let Some(index) = step_index(self.current_index, self.hits.len(), backwards) {
129 self.pick(index, cx);
130 }
131 }
132
133 fn pick(&mut self, index: usize, cx: &mut Context<Self>) {
134 let Some(hit) = self.hits.get(index) else {
135 return;
136 };
137 self.current_index = Some(index);
138 self.scroll.scroll_to_item(index);
139 cx.emit(FindPanelEvent::Jump(hit.message_id.clone()));
140 cx.notify();
141 }
142
143 fn update_filters(&mut self, change: impl FnOnce(&mut FindFilters), cx: &mut Context<Self>) {
144 change(&mut self.filters);
145 self.schedule_search(cx);
146 cx.notify();
147 }
148
149 fn schedule_search(&mut self, cx: &mut Context<Self>) {
150 self.generation += 1;
151 let generation = self.generation;
152 cx.spawn(async move |this, cx| {
153 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
154 this.update(cx, |panel, cx| {
155 if panel.generation == generation {
156 panel.run_search(cx);
157 }
158 })
159 .ok();
160 })
161 .detach();
162 }
163
164 fn run_search(&mut self, cx: &mut Context<Self>) {
165 self.current_index = None;
166 if self.query.is_empty() && !self.filters.is_active() {
167 self.local_hits.clear();
168 self.hits.clear();
169 self.status = Status::Idle;
170 cx.notify();
171 return;
172 }
173 let (store, engine, my_id) = {
174 let state = self.app.read(cx);
175 (
176 state.store.clone(),
177 state.engine.clone(),
178 state.directory.me.as_ref().map(|me| me.user_id.clone()),
179 )
180 };
181 let (today, offset) = today_and_offset();
182 let conversation_id = self.selection.conversation_id().to_owned();
183 let local: Vec<FindHit> =
184 local_hits(&store, &conversation_id, &self.query, my_id.as_deref())
185 .into_iter()
186 .filter(|hit| self.filters.admits(hit, today, offset))
187 .collect();
188 self.local_hits = local;
189 self.hits = merge(self.local_hits.clone(), Vec::new());
190 let server_engine = engine.filter(|_| matches!(self.selection, Selection::Chat(_)));
191 let Some(engine) = server_engine else {
192 self.status = Status::Ready;
193 cx.notify();
194 return;
195 };
196 self.status = Status::Loading;
197 let request = QueryRequest::new(self.query.clone(), QueryScope::Messages)
198 .with_filters(self.filters.server_filters(&conversation_id));
199 let search_session = self.search_session.clone();
200 let generation = self.generation;
201 let receiver =
202 runtime::spawn(async move { engine.server_query(&search_session, &request).await });
203 cx.spawn(async move |this, cx| {
204 let results = match receiver.await {
205 Ok(Ok(results)) => Some(results),
206 _ => None,
207 };
208 this.update(cx, |panel, cx| panel.apply_server(generation, results, cx))
209 .ok();
210 })
211 .detach();
212 cx.notify();
213 }
214
215 fn apply_server(
216 &mut self,
217 generation: u64,
218 results: Option<QueryResults>,
219 cx: &mut Context<Self>,
220 ) {
221 if generation != self.generation {
222 return;
223 }
224 let Some(results) = results else {
225 self.status = if self.hits.is_empty() {
226 Status::Failed
227 } else {
228 Status::Ready
229 };
230 cx.notify();
231 return;
232 };
233 let (today, offset) = today_and_offset();
234 let conversation_id = self.selection.conversation_id();
235 let server: Vec<FindHit> = results
236 .messages
237 .items
238 .iter()
239 .filter(|message| message.conversation_id == conversation_id)
240 .filter_map(from_server)
241 .filter(|hit| self.filters.admits(hit, today, offset))
242 .collect();
243 let current = self
244 .current_index
245 .and_then(|index| self.hits.get(index))
246 .map(|hit| hit.message_id.clone());
247 self.hits = merge(self.local_hits.clone(), server);
248 self.current_index = current.and_then(|message_id| {
249 self.hits
250 .iter()
251 .position(|hit| hit.message_id == message_id)
252 });
253 self.status = Status::Ready;
254 cx.notify();
255 }
256
257 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
258 h_flex()
259 .h(px(HEADER_HEIGHT))
260 .flex_none()
261 .pl(px(SIDE_INSET))
262 .pr(px(12.))
263 .items_center()
264 .justify_between()
265 .child(
266 div()
267 .text_size(px(15.))
268 .font_weight(FontWeight::SEMIBOLD)
269 .child(panel_title(&self.selection)),
270 )
271 .child(
272 div()
273 .id("find-close")
274 .size(px(28.))
275 .flex()
276 .items_center()
277 .justify_center()
278 .rounded(px(7.))
279 .cursor_pointer()
280 .hover(|button| button.bg(theme::row_hover()))
281 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
282 .child(icon(IconName::Close, 14., theme::text_muted()))
283 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
284 )
285 }
286
287 fn search_row(&self) -> impl IntoElement {
288 h_flex()
289 .debug_selector(|| FIND_INPUT_TAG.into())
290 .mx(px(SIDE_INSET))
291 .h(px(INPUT_HEIGHT))
292 .flex_none()
293 .px(px(10.))
294 .gap(px(8.))
295 .items_center()
296 .rounded(px(6.))
297 .bg(theme::surface_raised())
298 .child(icon(IconName::Search, 14., theme::text_muted()))
299 .child(
300 div()
301 .flex_1()
302 .min_w_0()
303 .child(Input::new(&self.input).appearance(false).bordered(false)),
304 )
305 }
306
307 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
308 let panel = cx.weak_entity();
309 h_flex()
310 .px(px(SIDE_INSET))
311 .pt(px(8.))
312 .flex_none()
313 .flex_wrap()
314 .gap(px(6.))
315 .child(self.from_chip(panel.clone()))
316 .child(self.date_chip(panel))
317 .child(self.toggle_chip(
318 "find-has-attachment",
319 HAS_ATTACHMENT_LABEL,
320 self.filters.has_attachment,
321 |filters| filters.has_attachment = !filters.has_attachment,
322 cx,
323 ))
324 .child(self.toggle_chip(
325 "find-mentions",
326 MENTIONS_LABEL,
327 self.filters.mentions_me,
328 |filters| filters.mentions_me = !filters.mentions_me,
329 cx,
330 ))
331 }
332
333 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
334 let selected = self.filters.from.clone();
335 let label = selected
336 .as_ref()
337 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
338 let senders = self.senders.clone();
339 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
340 senders.iter().fold(menu, |menu, sender| {
341 let checked = selected
342 .as_ref()
343 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
344 let (panel, sender) = (panel.clone(), sender.clone());
345 menu.item(
346 PopupMenuItem::new(sender.name.clone())
347 .checked(checked)
348 .on_click(move |_, _, cx| {
349 let pick = (!checked).then(|| sender.clone());
350 panel
351 .update(cx, |panel, cx| {
352 panel.update_filters(|filters| filters.from = pick, cx)
353 })
354 .ok();
355 }),
356 )
357 })
358 })
359 }
360
361 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
362 let selected = self.filters.date;
363 let label = selected.map_or(DATE_LABEL, DateRange::label);
364 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
365 move |menu, _, _| {
366 DateRange::ALL.into_iter().fold(menu, |menu, range| {
367 let checked = selected == Some(range);
368 let panel = panel.clone();
369 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
370 move |_, _, cx| {
371 let pick = (!checked).then_some(range);
372 panel
373 .update(cx, |panel, cx| {
374 panel.update_filters(|filters| filters.date = pick, cx)
375 })
376 .ok();
377 },
378 ))
379 })
380 },
381 )
382 }
383
384 fn toggle_chip(
385 &self,
386 id: &'static str,
387 label: &'static str,
388 selected: bool,
389 change: fn(&mut FindFilters),
390 cx: &mut Context<Self>,
391 ) -> impl IntoElement {
392 div()
393 .id(id)
394 .h(px(CHIP_HEIGHT))
395 .px(px(12.))
396 .flex()
397 .flex_none()
398 .items_center()
399 .rounded_full()
400 .cursor_pointer()
401 .text_size(px(12.))
402 .when(selected, |chip| {
403 chip.bg(theme::accent()).text_color(theme::on_accent())
404 })
405 .when(!selected, |chip| {
406 chip.bg(theme::surface_raised())
407 .text_color(theme::text_soft())
408 .hover(|chip| chip.bg(theme::border_strong()))
409 })
410 .child(label)
411 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
412 }
413
414 fn message_line(&self) -> Option<String> {
415 let no_results = || {
416 if self.filters.is_active() && !self.query.is_empty() {
417 no_results_with_filters(&self.query)
418 } else {
419 match self.selection {
420 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
421 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
422 }
423 }
424 };
425 match self.status {
426 Status::Idle => Some(EMPTY_HINT.to_owned()),
427 Status::Failed => Some(LOAD_ERROR.to_owned()),
428 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
429 Status::Ready if self.hits.is_empty() => Some(no_results()),
430 _ => None,
431 }
432 }
433
434 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
435 let (today, offset) = today_and_offset();
436 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
437 if let Some(message) = self.message_line() {
438 list = list.child(
439 div()
440 .px(px(SIDE_INSET))
441 .py(px(8.))
442 .text_size(px(13.))
443 .text_color(theme::text_muted())
444 .child(message),
445 );
446 }
447 let mut index = 0;
448 for group in group_by_month(&self.hits, today, offset) {
449 list = list.child(
450 div()
451 .px(px(SIDE_INSET))
452 .pt(px(12.))
453 .pb(px(4.))
454 .text_size(px(12.))
455 .font_weight(FontWeight::SEMIBOLD)
456 .text_color(theme::text_muted())
457 .child(group.label),
458 );
459 for hit in group.hits {
460 list = list.child(self.hit_row(&hit, index, today, offset, cx));
461 index += 1;
462 }
463 }
464 div()
465 .debug_selector(|| FIND_RESULTS_TAG.into())
466 .id("find-results")
467 .flex_1()
468 .min_h_0()
469 .w_full()
470 .overflow_y_scrollbar()
471 .track_scroll(&self.scroll)
472 .child(list)
473 }
474
475 fn hit_row(
476 &self,
477 hit: &FindHit,
478 index: usize,
479 today: NaiveDate,
480 offset: app_base::format::Zone,
481 cx: &mut Context<Self>,
482 ) -> impl IntoElement {
483 let current = self.current_index == Some(index);
484 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
485 .highlights
486 .iter()
487 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
488 .map(|range| {
489 (
490 range.clone(),
491 HighlightStyle {
492 color: Some(theme::accent_text()),
493 font_weight: Some(FontWeight::SEMIBOLD),
494 ..Default::default()
495 },
496 )
497 })
498 .collect();
499 v_flex()
500 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
501 .mx(px(8.))
502 .px(px(8.))
503 .py(px(8.))
504 .gap(px(2.))
505 .rounded(px(6.))
506 .cursor_pointer()
507 .when(current, |row| row.bg(theme::selection()))
508 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
509 .child(
510 h_flex()
511 .gap(px(8.))
512 .text_size(px(12.))
513 .child(
514 div()
515 .flex_1()
516 .min_w_0()
517 .truncate()
518 .font_weight(FontWeight::SEMIBOLD)
519 .text_color(theme::text())
520 .child(hit.sender_name.clone()),
521 )
522 .child(
523 div()
524 .flex_none()
525 .text_color(theme::text_muted())
526 .child(format::list_time_label(hit.sent_at, today, offset)),
527 ),
528 )
529 .child(
530 div()
531 .text_size(px(13.))
532 .text_color(theme::text_soft())
533 .line_clamp(2)
534 .text_ellipsis()
535 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
536 )
537 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
538 }
539}
540
541impl Render for FindPanel {
542 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
543 h_flex()
544 .debug_selector(|| FIND_PANEL_TAG.into())
545 .h_full()
546 .items_start()
547 .bg(theme::surface())
548 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
549 cx.emit(FindPanelEvent::Close);
550 cx.stop_propagation();
551 }))
552 .child(
553 div()
554 .debug_selector(|| FIND_DIVIDER_TAG.into())
555 .w(px(1.))
556 .h_full()
557 .flex_none()
558 .bg(theme::border()),
559 )
560 .child(
561 v_flex()
562 .flex_1()
563 .min_w_0()
564 .h_full()
565 .child(self.header(cx))
566 .child(self.search_row())
567 .child(self.chips(cx))
568 .child(self.results(cx)),
569 )
570 }
571}
572
573fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
574 Button::new(id)
575 .ghost()
576 .compact()
577 .label(label)
578 .dropdown_caret(true)
579 .rounded(px(CHIP_HEIGHT / 2.))
580 .h(px(CHIP_HEIGHT))
581 .text_size(px(12.))
582 .when(selected, |chip| {
583 chip.bg(theme::accent()).text_color(theme::on_accent())
584 })
585 .when(!selected, |chip| {
586 chip.bg(theme::surface_raised())
587 .text_color(theme::text_soft())
588 })
589}
590
591fn panel_title(selection: &Selection) -> &'static str {
592 match selection {
593 Selection::Chat(_) => FIND_IN_CHAT,
594 Selection::Channel(_) => FIND_IN_CHANNEL,
595 }
596}
597
598fn today_and_offset() -> (NaiveDate, app_base::format::Zone) {
599 (Local::now().date_naive(), app_base::format::Zone::Local)
600}
601
602fn local_hits(
603 store: &Store,
604 conversation_id: &str,
605 query: &str,
606 my_id: Option<&str>,
607) -> Vec<FindHit> {
608 if query.is_empty() {
609 return store
610 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
611 .unwrap_or_default()
612 .iter()
613 .filter(|record| !record.deleted)
614 .map(|record| from_record(record, my_id))
615 .collect();
616 }
617 let found = store
618 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
619 .unwrap_or_default();
620 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
621 let records = store
622 .messages_by_id(conversation_id, &message_ids)
623 .unwrap_or_default();
624 found
625 .iter()
626 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
627 .collect()
628}
629
630fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
631 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
632 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
633 let mut senders: Vec<Sender> = Vec::new();
634 let mut push = |user_id: &str, name: &str| {
635 if name.is_empty() || is_me(user_id) {
636 return;
637 }
638 if senders
639 .iter()
640 .any(|sender| same_user(&sender.user_id, user_id))
641 {
642 return;
643 }
644 senders.push(Sender {
645 user_id: user_id.to_owned(),
646 name: name.to_owned(),
647 });
648 };
649 if let Some(chat) = state
650 .sidebar
651 .chats
652 .iter()
653 .find(|chat| chat.id == conversation_id)
654 {
655 for member in &chat.members {
656 if let Some(user_id) = &member.user_id {
657 push(user_id, &member.display_name);
658 }
659 }
660 }
661 for record in state
662 .store
663 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
664 .unwrap_or_default()
665 .iter()
666 .rev()
667 {
668 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
669 push(user_id, name);
670 }
671 }
672 senders.sort_by_key(|sender| sender.name.to_lowercase());
673 senders
674}