BlueGit

ict rusty-teams

Files

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

switcher.rs

switcher.rs 18.3 KiB Download Raw
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{
3 h_flex,
4 input::{Input, InputEvent, InputState},
5 v_flex,
6};
7use std::collections::HashMap;
8use std::ops::Range;
9
10use chrono::{Local, Offset};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13use store::SearchHit;
14use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
15
16use super::avatar::{person_avatar, spec_avatar, team_avatar};
17use super::widgets::icon;
18use crate::app_state::{AppState, Selection, chat_title};
19use crate::data::{Directory, is_one_on_one};
20use crate::format;
21use crate::fuzzy;
22use crate::sidebar_model::{AvatarSpec, avatar_for};
23use crate::theme::{self, ElevatedSurface as _};
24
25const MAX_RESULTS: usize = 9;
26const MAX_RESULTS_WITH_MESSAGES: usize = 5;
27const MAX_MESSAGE_RESULTS: usize = 5;
28const MIN_MESSAGE_QUERY_CHARS: usize = 2;
29const MESSAGE_GROUP: &str = "Messages";
30const CARD_WIDTH: f32 = 520.;
31
32pub enum SwitcherEvent {
33 Pick(Selection),
34 PickMessage {
35 selection: Selection,
36 message_id: String,
37 },
38 Close,
39}
40
41#[derive(Clone)]
42pub struct MessageResult {
43 pub selection: Selection,
44 pub message_id: String,
45 pub author: String,
46 pub conversation: String,
47 pub date: String,
48 pub snippet: String,
49 pub matches: Vec<Range<usize>>,
50}
51
52pub fn parse_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
53 let mut text = String::with_capacity(snippet.len());
54 let mut matches = Vec::new();
55 let mut start: Option<usize> = None;
56 for character in snippet.chars() {
57 match character {
58 HIGHLIGHT_START => start = Some(text.len()),
59 HIGHLIGHT_END => {
60 if let Some(begin) = start.take().filter(|begin| *begin < text.len()) {
61 matches.push(begin..text.len());
62 }
63 }
64 '\n' | '\r' => text.push(' '),
65 other => text.push(other),
66 }
67 }
68 (text, matches)
69}
70
71pub fn message_results(
72 hits: Vec<SearchHit>,
73 conversations: &HashMap<String, (String, Selection)>,
74 today: chrono::NaiveDate,
75 offset: chrono::FixedOffset,
76) -> Vec<MessageResult> {
77 hits.into_iter()
78 .filter_map(|hit| {
79 let (conversation, selection) = conversations.get(&hit.conversation_id)?.clone();
80 let (snippet, matches) = parse_snippet(&hit.snippet);
81 Some(MessageResult {
82 selection,
83 message_id: hit.message_id,
84 author: hit.sender_name.unwrap_or_else(|| "Unknown".to_owned()),
85 conversation,
86 date: format::list_time_label(hit.created_at, today, offset),
87 snippet,
88 matches,
89 })
90 })
91 .collect()
92}
93
94#[derive(Clone)]
95pub enum CandidateAvatar {
96 Chat(AvatarSpec),
97 Team { name: String, key: String },
98}
99
100#[derive(Clone)]
101pub struct Candidate {
102 pub title: String,
103 pub subtitle: String,
104 pub avatar: CandidateAvatar,
105 pub selection: Selection,
106}
107
108impl Candidate {
109 fn group(&self) -> &'static str {
110 match self.selection {
111 Selection::Chat(_) => "Chats",
112 Selection::Channel(_) => "Channels",
113 }
114 }
115}
116
117pub struct Switcher {
118 app: Entity<AppState>,
119 input: Entity<InputState>,
120 candidates: Vec<(String, Candidate)>,
121 conversations: HashMap<String, (String, Selection)>,
122 results: Vec<Candidate>,
123 messages: Vec<MessageResult>,
124 highlighted: usize,
125 _subscription: Subscription,
126}
127
128impl EventEmitter<SwitcherEvent> for Switcher {}
129
130pub fn candidates_from(state: &AppState) -> Vec<(String, Candidate)> {
131 let me = state.directory.me.as_ref();
132 let chats = state.sidebar.chats.iter().map(|chat| {
133 let title = chat_title(chat);
134 (
135 title.clone(),
136 Candidate {
137 title,
138 subtitle: if is_one_on_one(chat) {
139 "Chat".to_owned()
140 } else {
141 format!("Group chat, {} participants", chat.members.len())
142 },
143 avatar: CandidateAvatar::Chat(avatar_for(chat, me)),
144 selection: Selection::Chat(chat.id.clone()),
145 },
146 )
147 });
148 let channels = state.sidebar.teams.iter().flat_map(|team| {
149 team.channels.iter().map(|channel| {
150 (
151 format!("{} / {}", team.team.name, channel.name),
152 Candidate {
153 title: channel.name.clone(),
154 subtitle: team.team.name.clone(),
155 avatar: CandidateAvatar::Team {
156 name: team.team.name.clone(),
157 key: team.team.id.clone(),
158 },
159 selection: Selection::Channel(channel.id.clone()),
160 },
161 )
162 })
163 });
164 chats.chain(channels).collect()
165}
166
167pub fn candidate_avatar(
168 directory: &Directory,
169 avatar: &CandidateAvatar,
170 size: f32,
171 ring: Hsla,
172) -> AnyElement {
173 match avatar {
174 CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, size, ring),
175 CandidateAvatar::Team { name, key } => {
176 let photo = directory.avatar(&teams_core::team_avatar_key(key));
177 team_avatar(photo, name, key, size, size / 4.)
178 }
179 }
180}
181
182pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {
183 if length == 0 {
184 return 0;
185 }
186 (current as isize + delta).clamp(0, length as isize - 1) as usize
187}
188
189impl Switcher {
190 pub fn new(
191 app: Entity<AppState>,
192 candidates: Vec<(String, Candidate)>,
193 initial_query: &str,
194 window: &mut Window,
195 cx: &mut Context<Self>,
196 ) -> Self {
197 let input = cx.new(|cx| {
198 InputState::new(window, cx).placeholder("Jump to a chat, channel or message")
199 });
200 if !initial_query.is_empty() {
201 let query = initial_query.to_owned();
202 input.update(cx, |input, cx| input.set_value(query, window, cx));
203 }
204 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
205 input.update(cx, |input, cx| input.focus(window, cx));
206 let conversations = candidates
207 .iter()
208 .map(|(title, candidate)| {
209 (
210 candidate.selection.conversation_id().to_owned(),
211 (title.clone(), candidate.selection.clone()),
212 )
213 })
214 .collect();
215 let mut switcher = Switcher {
216 app,
217 input,
218 candidates,
219 conversations,
220 results: Vec::new(),
221 messages: Vec::new(),
222 highlighted: 0,
223 _subscription: subscription,
224 };
225 switcher.refresh(initial_query, cx);
226 switcher
227 }
228
229 fn refresh(&mut self, query: &str, cx: &App) {
230 let wants_messages = query.trim().chars().count() >= MIN_MESSAGE_QUERY_CHARS;
231 let limit = if wants_messages {
232 MAX_RESULTS_WITH_MESSAGES
233 } else {
234 MAX_RESULTS
235 };
236 self.results = fuzzy::rank(query, &self.candidates, limit);
237 self.results
238 .sort_by_key(|candidate| candidate.group() != "Chats");
239 self.messages = if wants_messages {
240 let hits = self
241 .app
242 .read(cx)
243 .store
244 .search_messages(query, None, MAX_MESSAGE_RESULTS)
245 .unwrap_or_default();
246 let now = Local::now();
247 message_results(
248 hits,
249 &self.conversations,
250 now.date_naive(),
251 now.offset().fix(),
252 )
253 } else {
254 Vec::new()
255 };
256 self.highlighted = 0;
257 }
258
259 fn result_count(&self) -> usize {
260 self.results.len() + self.messages.len()
261 }
262
263 fn on_input_event(
264 &mut self,
265 input: &Entity<InputState>,
266 event: &InputEvent,
267 _: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 match event {
271 InputEvent::Change => {
272 let query = input.read(cx).value().to_string();
273 self.refresh(&query, cx);
274 cx.notify();
275 }
276 InputEvent::PressEnter { .. } => self.pick(cx),
277 _ => {}
278 }
279 }
280
281 fn pick(&mut self, cx: &mut Context<Self>) {
282 if let Some(candidate) = self.results.get(self.highlighted) {
283 cx.emit(SwitcherEvent::Pick(candidate.selection.clone()));
284 } else if let Some(message) = self
285 .highlighted
286 .checked_sub(self.results.len())
287 .and_then(|index| self.messages.get(index))
288 {
289 cx.emit(SwitcherEvent::PickMessage {
290 selection: message.selection.clone(),
291 message_id: message.message_id.clone(),
292 });
293 } else {
294 cx.emit(SwitcherEvent::Close);
295 }
296 }
297
298 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
299 match event.keystroke.key.as_str() {
300 "down" => self.highlighted = clamp_highlight(self.highlighted, 1, self.result_count()),
301 "up" => self.highlighted = clamp_highlight(self.highlighted, -1, self.result_count()),
302 "escape" => cx.emit(SwitcherEvent::Close),
303 _ => return,
304 }
305 cx.notify();
306 }
307}
308
309fn group_header(label: &'static str) -> AnyElement {
310 div()
311 .px(px(12.))
312 .pt(px(8.))
313 .pb(px(4.))
314 .text_size(px(11.))
315 .font_weight(FontWeight::SEMIBOLD)
316 .text_color(theme::text_muted())
317 .child(label)
318 .into_any_element()
319}
320
321impl Render for Switcher {
322 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
323 let highlighted = self.highlighted;
324 let directory = &self.app.read(cx).directory;
325 let mut rows: Vec<AnyElement> = Vec::new();
326 let mut last_group = "";
327 for (index, candidate) in self.results.iter().enumerate() {
328 if candidate.group() != last_group {
329 last_group = candidate.group();
330 rows.push(group_header(last_group));
331 }
332 let selection = candidate.selection.clone();
333 let avatar = candidate_avatar(directory, &candidate.avatar, 28., theme::popup());
334 let kind_icon = match candidate.selection {
335 Selection::Chat(_) => IconName::MessageCircle,
336 Selection::Channel(_) => IconName::Hash,
337 };
338 rows.push(
339 h_flex()
340 .id(ElementId::Name(format!("switch-{index}").into()))
341 .mx(px(6.))
342 .px(px(6.))
343 .h(px(44.))
344 .gap(px(10.))
345 .items_center()
346 .rounded(px(6.))
347 .cursor_pointer()
348 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
349 .hover(|row| row.bg(theme::popup_hover()))
350 .child(avatar)
351 .child(
352 v_flex()
353 .flex_1()
354 .min_w_0()
355 .child(
356 div()
357 .truncate()
358 .text_size(px(14.))
359 .text_color(theme::text())
360 .child(candidate.title.clone()),
361 )
362 .child(
363 div()
364 .truncate()
365 .text_size(px(12.))
366 .text_color(theme::text_muted())
367 .child(candidate.subtitle.clone()),
368 ),
369 )
370 .child(icon(kind_icon, 14., theme::text_muted()))
371 .on_click(cx.listener(move |_, _, _, cx| {
372 cx.emit(SwitcherEvent::Pick(selection.clone()));
373 }))
374 .into_any_element(),
375 );
376 }
377 if !self.messages.is_empty() {
378 rows.push(group_header(MESSAGE_GROUP));
379 }
380 for (offset, message) in self.messages.iter().enumerate() {
381 let index = self.results.len() + offset;
382 let (selection, message_id) = (message.selection.clone(), message.message_id.clone());
383 let marks = message
384 .matches
385 .iter()
386 .map(|range| {
387 (
388 range.clone(),
389 HighlightStyle {
390 color: Some(theme::accent_text()),
391 font_weight: Some(FontWeight::SEMIBOLD),
392 ..Default::default()
393 },
394 )
395 })
396 .collect::<Vec<_>>();
397 rows.push(
398 h_flex()
399 .id(ElementId::Name(format!("switch-message-{index}").into()))
400 .mx(px(6.))
401 .px(px(6.))
402 .h(px(52.))
403 .gap(px(10.))
404 .items_center()
405 .rounded(px(6.))
406 .cursor_pointer()
407 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
408 .hover(|row| row.bg(theme::popup_hover()))
409 .child(person_avatar(directory, None, &message.author, 28.))
410 .child(
411 v_flex()
412 .flex_1()
413 .min_w_0()
414 .gap(px(1.))
415 .child(
416 h_flex()
417 .gap(px(6.))
418 .items_baseline()
419 .child(
420 div()
421 .flex_none()
422 .text_size(px(13.))
423 .font_weight(FontWeight::SEMIBOLD)
424 .text_color(theme::text())
425 .child(message.author.clone()),
426 )
427 .child(
428 div()
429 .min_w_0()
430 .truncate()
431 .text_size(px(12.))
432 .text_color(theme::text_muted())
433 .child(format!("in {}", message.conversation)),
434 )
435 .child(div().flex_1())
436 .child(
437 div()
438 .flex_none()
439 .text_size(px(11.))
440 .text_color(theme::text_muted())
441 .child(message.date.clone()),
442 ),
443 )
444 .child(
445 div()
446 .truncate()
447 .text_size(px(12.5))
448 .text_color(theme::text_soft())
449 .child(
450 StyledText::new(message.snippet.clone())
451 .with_highlights(marks),
452 ),
453 ),
454 )
455 .on_click(cx.listener(move |_, _, _, cx| {
456 cx.emit(SwitcherEvent::PickMessage {
457 selection: selection.clone(),
458 message_id: message_id.clone(),
459 });
460 }))
461 .into_any_element(),
462 );
463 }
464 let footer = h_flex()
465 .h(px(32.))
466 .px(px(12.))
467 .gap(px(16.))
468 .items_center()
469 .text_size(px(11.))
470 .text_color(theme::text_muted())
471 .child("Enter to open")
472 .child("Arrows to select")
473 .child("Esc to close");
474 div()
475 .id("switcher-backdrop")
476 .absolute()
477 .size_full()
478 .top_0()
479 .left_0()
480 .bg(theme::background().opacity(0.6))
481 .flex()
482 .justify_center()
483 .items_start()
484 .pt(px(72.))
485 .on_click(cx.listener(|_, _, _, cx| cx.emit(SwitcherEvent::Close)))
486 .child(
487 v_flex()
488 .id("switcher-card")
489 .w(px(CARD_WIDTH))
490 .max_h(px(640.))
491 .rounded(px(10.))
492 .flyout_surface()
493 .overflow_hidden()
494 .on_click(|_, _, cx| cx.stop_propagation())
495 .on_key_down(cx.listener(Self::on_key_down))
496 .child(
497 div()
498 .p(px(8.))
499 .child(Input::new(&self.input).appearance(false).bordered(false)),
500 )
501 .child(v_flex().w_full().py_1().children(rows))
502 .child(footer),
503 )
504 }
505}
506
507#[cfg(test)]
508mod tests {
509 use super::{clamp_highlight, parse_snippet};
510 use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
511
512 #[test]
513 fn snippet_markers_become_ranges() {
514 let raw = format!("a {HIGHLIGHT_START}Build{HIGHLIGHT_END} 42\nok");
515 let (text, matches) = parse_snippet(&raw);
516 assert_eq!(text, "a Build 42 ok");
517 assert_eq!(matches, vec![2..7]);
518 }
519
520 #[test]
521 fn unterminated_or_empty_markers_are_ignored() {
522 let raw = format!("{HIGHLIGHT_START}{HIGHLIGHT_END}x{HIGHLIGHT_START}y");
523 assert_eq!(parse_snippet(&raw), ("xy".to_owned(), Vec::new()));
524 }
525
526 #[test]
527 fn highlight_stays_inside_the_list() {
528 assert_eq!(clamp_highlight(0, -1, 3), 0);
529 assert_eq!(clamp_highlight(2, 1, 3), 2);
530 assert_eq!(clamp_highlight(1, 1, 3), 2);
531 assert_eq!(clamp_highlight(0, 1, 0), 0);
532 }
533}