BlueGit

ict rusty-teams

Files

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

find_panel.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
find_panel.rs 22.2 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::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 self.hits = merge(self.local_hits.clone(), server);
244 self.status = Status::Ready;
245 cx.notify();
246 }
247
248 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
249 h_flex()
250 .h(px(HEADER_HEIGHT))
251 .flex_none()
252 .pl(px(SIDE_INSET))
253 .pr(px(12.))
254 .items_center()
255 .justify_between()
256 .child(
257 div()
258 .text_size(px(15.))
259 .font_weight(FontWeight::SEMIBOLD)
260 .child(panel_title(&self.selection)),
261 )
262 .child(
263 div()
264 .id("find-close")
265 .size(px(28.))
266 .flex()
267 .items_center()
268 .justify_center()
269 .rounded(px(7.))
270 .cursor_pointer()
271 .hover(|button| button.bg(theme::row_hover()))
272 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
273 .child(icon(IconName::Close, 14., theme::text_muted()))
274 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
275 )
276 }
277
278 fn search_row(&self) -> impl IntoElement {
279 h_flex()
280 .debug_selector(|| FIND_INPUT_TAG.into())
281 .mx(px(SIDE_INSET))
282 .h(px(INPUT_HEIGHT))
283 .flex_none()
284 .px(px(10.))
285 .gap(px(8.))
286 .items_center()
287 .rounded(px(6.))
288 .bg(theme::surface_raised())
289 .child(icon(IconName::Search, 14., theme::text_muted()))
290 .child(
291 div()
292 .flex_1()
293 .min_w_0()
294 .child(Input::new(&self.input).appearance(false).bordered(false)),
295 )
296 }
297
298 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
299 let panel = cx.weak_entity();
300 h_flex()
301 .px(px(SIDE_INSET))
302 .pt(px(8.))
303 .flex_none()
304 .flex_wrap()
305 .gap(px(6.))
306 .child(self.from_chip(panel.clone()))
307 .child(self.date_chip(panel))
308 .child(self.toggle_chip(
309 "find-has-attachment",
310 HAS_ATTACHMENT_LABEL,
311 self.filters.has_attachment,
312 |filters| filters.has_attachment = !filters.has_attachment,
313 cx,
314 ))
315 .child(self.toggle_chip(
316 "find-mentions",
317 MENTIONS_LABEL,
318 self.filters.mentions_me,
319 |filters| filters.mentions_me = !filters.mentions_me,
320 cx,
321 ))
322 }
323
324 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
325 let selected = self.filters.from.clone();
326 let label = selected
327 .as_ref()
328 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
329 let senders = self.senders.clone();
330 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
331 senders.iter().fold(menu, |menu, sender| {
332 let checked = selected
333 .as_ref()
334 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
335 let (panel, sender) = (panel.clone(), sender.clone());
336 menu.item(
337 PopupMenuItem::new(sender.name.clone())
338 .checked(checked)
339 .on_click(move |_, _, cx| {
340 let pick = (!checked).then(|| sender.clone());
341 panel
342 .update(cx, |panel, cx| {
343 panel.update_filters(|filters| filters.from = pick, cx)
344 })
345 .ok();
346 }),
347 )
348 })
349 })
350 }
351
352 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
353 let selected = self.filters.date;
354 let label = selected.map_or(DATE_LABEL, DateRange::label);
355 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
356 move |menu, _, _| {
357 DateRange::ALL.into_iter().fold(menu, |menu, range| {
358 let checked = selected == Some(range);
359 let panel = panel.clone();
360 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
361 move |_, _, cx| {
362 let pick = (!checked).then_some(range);
363 panel
364 .update(cx, |panel, cx| {
365 panel.update_filters(|filters| filters.date = pick, cx)
366 })
367 .ok();
368 },
369 ))
370 })
371 },
372 )
373 }
374
375 fn toggle_chip(
376 &self,
377 id: &'static str,
378 label: &'static str,
379 selected: bool,
380 change: fn(&mut FindFilters),
381 cx: &mut Context<Self>,
382 ) -> impl IntoElement {
383 div()
384 .id(id)
385 .h(px(CHIP_HEIGHT))
386 .px(px(12.))
387 .flex()
388 .flex_none()
389 .items_center()
390 .rounded_full()
391 .cursor_pointer()
392 .text_size(px(12.))
393 .when(selected, |chip| {
394 chip.bg(theme::accent()).text_color(theme::on_accent())
395 })
396 .when(!selected, |chip| {
397 chip.bg(theme::surface_raised())
398 .text_color(theme::text_soft())
399 .hover(|chip| chip.bg(theme::border_strong()))
400 })
401 .child(label)
402 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
403 }
404
405 fn message_line(&self) -> Option<String> {
406 let no_results = || {
407 if self.filters.is_active() && !self.query.is_empty() {
408 no_results_with_filters(&self.query)
409 } else {
410 match self.selection {
411 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
412 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
413 }
414 }
415 };
416 match self.status {
417 Status::Idle => Some(EMPTY_HINT.to_owned()),
418 Status::Failed => Some(LOAD_ERROR.to_owned()),
419 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
420 Status::Ready if self.hits.is_empty() => Some(no_results()),
421 _ => None,
422 }
423 }
424
425 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
426 let (today, offset) = today_and_offset();
427 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
428 if let Some(message) = self.message_line() {
429 list = list.child(
430 div()
431 .px(px(SIDE_INSET))
432 .py(px(8.))
433 .text_size(px(13.))
434 .text_color(theme::text_muted())
435 .child(message),
436 );
437 }
438 let mut index = 0;
439 for group in group_by_month(&self.hits, today, offset) {
440 list = list.child(
441 div()
442 .px(px(SIDE_INSET))
443 .pt(px(12.))
444 .pb(px(4.))
445 .text_size(px(12.))
446 .font_weight(FontWeight::SEMIBOLD)
447 .text_color(theme::text_muted())
448 .child(group.label),
449 );
450 for hit in group.hits {
451 list = list.child(self.hit_row(&hit, index, today, offset, cx));
452 index += 1;
453 }
454 }
455 div()
456 .debug_selector(|| FIND_RESULTS_TAG.into())
457 .id("find-results")
458 .flex_1()
459 .min_h_0()
460 .w_full()
461 .overflow_y_scrollbar()
462 .track_scroll(&self.scroll)
463 .child(list)
464 }
465
466 fn hit_row(
467 &self,
468 hit: &FindHit,
469 index: usize,
470 today: NaiveDate,
471 offset: chrono::FixedOffset,
472 cx: &mut Context<Self>,
473 ) -> impl IntoElement {
474 let current = self.current_index == Some(index);
475 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
476 .highlights
477 .iter()
478 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
479 .map(|range| {
480 (
481 range.clone(),
482 HighlightStyle {
483 color: Some(theme::accent_text()),
484 font_weight: Some(FontWeight::SEMIBOLD),
485 ..Default::default()
486 },
487 )
488 })
489 .collect();
490 v_flex()
491 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
492 .mx(px(8.))
493 .px(px(8.))
494 .py(px(8.))
495 .gap(px(2.))
496 .rounded(px(6.))
497 .cursor_pointer()
498 .when(current, |row| row.bg(theme::selection()))
499 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
500 .child(
501 h_flex()
502 .gap(px(8.))
503 .text_size(px(12.))
504 .child(
505 div()
506 .flex_1()
507 .min_w_0()
508 .truncate()
509 .font_weight(FontWeight::SEMIBOLD)
510 .text_color(theme::text())
511 .child(hit.sender_name.clone()),
512 )
513 .child(
514 div()
515 .flex_none()
516 .text_color(theme::text_muted())
517 .child(format::list_time_label(hit.sent_at, today, offset)),
518 ),
519 )
520 .child(
521 div()
522 .text_size(px(13.))
523 .text_color(theme::text_soft())
524 .line_clamp(2)
525 .text_ellipsis()
526 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
527 )
528 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
529 }
530}
531
532impl Render for FindPanel {
533 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
534 h_flex()
535 .debug_selector(|| FIND_PANEL_TAG.into())
536 .h_full()
537 .items_start()
538 .bg(theme::surface())
539 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
540 cx.emit(FindPanelEvent::Close);
541 cx.stop_propagation();
542 }))
543 .child(
544 div()
545 .debug_selector(|| FIND_DIVIDER_TAG.into())
546 .w(px(1.))
547 .h_full()
548 .flex_none()
549 .bg(theme::border()),
550 )
551 .child(
552 v_flex()
553 .flex_1()
554 .min_w_0()
555 .h_full()
556 .child(self.header(cx))
557 .child(self.search_row())
558 .child(self.chips(cx))
559 .child(self.results(cx)),
560 )
561 }
562}
563
564fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
565 Button::new(id)
566 .ghost()
567 .compact()
568 .label(label)
569 .dropdown_caret(true)
570 .rounded(px(CHIP_HEIGHT / 2.))
571 .h(px(CHIP_HEIGHT))
572 .text_size(px(12.))
573 .when(selected, |chip| {
574 chip.bg(theme::accent()).text_color(theme::on_accent())
575 })
576 .when(!selected, |chip| {
577 chip.bg(theme::surface_raised())
578 .text_color(theme::text_soft())
579 })
580}
581
582fn panel_title(selection: &Selection) -> &'static str {
583 match selection {
584 Selection::Chat(_) => FIND_IN_CHAT,
585 Selection::Channel(_) => FIND_IN_CHANNEL,
586 }
587}
588
589fn today_and_offset() -> (NaiveDate, chrono::FixedOffset) {
590 let now = Local::now();
591 (now.date_naive(), now.offset().fix())
592}
593
594fn local_hits(
595 store: &Store,
596 conversation_id: &str,
597 query: &str,
598 my_id: Option<&str>,
599) -> Vec<FindHit> {
600 if query.is_empty() {
601 return store
602 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
603 .unwrap_or_default()
604 .iter()
605 .filter(|record| !record.deleted)
606 .map(|record| from_record(record, my_id))
607 .collect();
608 }
609 let found = store
610 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
611 .unwrap_or_default();
612 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
613 let records = store
614 .messages_by_id(conversation_id, &message_ids)
615 .unwrap_or_default();
616 found
617 .iter()
618 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
619 .collect()
620}
621
622fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
623 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
624 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
625 let mut senders: Vec<Sender> = Vec::new();
626 let mut push = |user_id: &str, name: &str| {
627 if name.is_empty() || is_me(user_id) {
628 return;
629 }
630 if senders
631 .iter()
632 .any(|sender| same_user(&sender.user_id, user_id))
633 {
634 return;
635 }
636 senders.push(Sender {
637 user_id: user_id.to_owned(),
638 name: name.to_owned(),
639 });
640 };
641 if let Some(chat) = state
642 .sidebar
643 .chats
644 .iter()
645 .find(|chat| chat.id == conversation_id)
646 {
647 for member in &chat.members {
648 if let Some(user_id) = &member.user_id {
649 push(user_id, &member.display_name);
650 }
651 }
652 }
653 for record in state
654 .store
655 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
656 .unwrap_or_default()
657 .iter()
658 .rev()
659 {
660 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
661 push(user_id, name);
662 }
663 }
664 senders.sort_by_key(|sender| sender.name.to_lowercase());
665 senders
666}