BlueGit

ict rusty-teams

Files

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

switcher.rs

switcher.rs 18.2 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, square_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;
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 square_avatar(name, key, size, size / 4.).into_any_element()
177 }
178 }
179}
180
181pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {
182 if length == 0 {
183 return 0;
184 }
185 (current as isize + delta).clamp(0, length as isize - 1) as usize
186}
187
188impl Switcher {
189 pub fn new(
190 app: Entity<AppState>,
191 candidates: Vec<(String, Candidate)>,
192 initial_query: &str,
193 window: &mut Window,
194 cx: &mut Context<Self>,
195 ) -> Self {
196 let input = cx.new(|cx| {
197 InputState::new(window, cx).placeholder("Jump to a chat, channel or message")
198 });
199 if !initial_query.is_empty() {
200 let query = initial_query.to_owned();
201 input.update(cx, |input, cx| input.set_value(query, window, cx));
202 }
203 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
204 input.update(cx, |input, cx| input.focus(window, cx));
205 let conversations = candidates
206 .iter()
207 .map(|(title, candidate)| {
208 (
209 candidate.selection.conversation_id().to_owned(),
210 (title.clone(), candidate.selection.clone()),
211 )
212 })
213 .collect();
214 let mut switcher = Switcher {
215 app,
216 input,
217 candidates,
218 conversations,
219 results: Vec::new(),
220 messages: Vec::new(),
221 highlighted: 0,
222 _subscription: subscription,
223 };
224 switcher.refresh(initial_query, cx);
225 switcher
226 }
227
228 fn refresh(&mut self, query: &str, cx: &App) {
229 let wants_messages = query.trim().chars().count() >= MIN_MESSAGE_QUERY_CHARS;
230 let limit = if wants_messages {
231 MAX_RESULTS_WITH_MESSAGES
232 } else {
233 MAX_RESULTS
234 };
235 self.results = fuzzy::rank(query, &self.candidates, limit);
236 self.results
237 .sort_by_key(|candidate| candidate.group() != "Chats");
238 self.messages = if wants_messages {
239 let hits = self
240 .app
241 .read(cx)
242 .store
243 .search_messages(query, None, MAX_MESSAGE_RESULTS)
244 .unwrap_or_default();
245 let now = Local::now();
246 message_results(
247 hits,
248 &self.conversations,
249 now.date_naive(),
250 now.offset().fix(),
251 )
252 } else {
253 Vec::new()
254 };
255 self.highlighted = 0;
256 }
257
258 fn result_count(&self) -> usize {
259 self.results.len() + self.messages.len()
260 }
261
262 fn on_input_event(
263 &mut self,
264 input: &Entity<InputState>,
265 event: &InputEvent,
266 _: &mut Window,
267 cx: &mut Context<Self>,
268 ) {
269 match event {
270 InputEvent::Change => {
271 let query = input.read(cx).value().to_string();
272 self.refresh(&query, cx);
273 cx.notify();
274 }
275 InputEvent::PressEnter { .. } => self.pick(cx),
276 _ => {}
277 }
278 }
279
280 fn pick(&mut self, cx: &mut Context<Self>) {
281 if let Some(candidate) = self.results.get(self.highlighted) {
282 cx.emit(SwitcherEvent::Pick(candidate.selection.clone()));
283 } else if let Some(message) = self
284 .highlighted
285 .checked_sub(self.results.len())
286 .and_then(|index| self.messages.get(index))
287 {
288 cx.emit(SwitcherEvent::PickMessage {
289 selection: message.selection.clone(),
290 message_id: message.message_id.clone(),
291 });
292 } else {
293 cx.emit(SwitcherEvent::Close);
294 }
295 }
296
297 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
298 match event.keystroke.key.as_str() {
299 "down" => self.highlighted = clamp_highlight(self.highlighted, 1, self.result_count()),
300 "up" => self.highlighted = clamp_highlight(self.highlighted, -1, self.result_count()),
301 "escape" => cx.emit(SwitcherEvent::Close),
302 _ => return,
303 }
304 cx.notify();
305 }
306}
307
308fn group_header(label: &'static str) -> AnyElement {
309 div()
310 .px(px(12.))
311 .pt(px(8.))
312 .pb(px(4.))
313 .text_size(px(11.))
314 .font_weight(FontWeight::SEMIBOLD)
315 .text_color(theme::text_muted())
316 .child(label)
317 .into_any_element()
318}
319
320impl Render for Switcher {
321 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
322 let highlighted = self.highlighted;
323 let directory = &self.app.read(cx).directory;
324 let mut rows: Vec<AnyElement> = Vec::new();
325 let mut last_group = "";
326 for (index, candidate) in self.results.iter().enumerate() {
327 if candidate.group() != last_group {
328 last_group = candidate.group();
329 rows.push(group_header(last_group));
330 }
331 let selection = candidate.selection.clone();
332 let avatar = candidate_avatar(directory, &candidate.avatar, 28., theme::popup());
333 let kind_icon = match candidate.selection {
334 Selection::Chat(_) => IconName::MessageCircle,
335 Selection::Channel(_) => IconName::Hash,
336 };
337 rows.push(
338 h_flex()
339 .id(ElementId::Name(format!("switch-{index}").into()))
340 .mx(px(6.))
341 .px(px(6.))
342 .h(px(44.))
343 .gap(px(10.))
344 .items_center()
345 .rounded(px(6.))
346 .cursor_pointer()
347 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
348 .hover(|row| row.bg(theme::popup_hover()))
349 .child(avatar)
350 .child(
351 v_flex()
352 .flex_1()
353 .min_w_0()
354 .child(
355 div()
356 .truncate()
357 .text_size(px(14.))
358 .text_color(theme::text())
359 .child(candidate.title.clone()),
360 )
361 .child(
362 div()
363 .truncate()
364 .text_size(px(12.))
365 .text_color(theme::text_muted())
366 .child(candidate.subtitle.clone()),
367 ),
368 )
369 .child(icon(kind_icon, 14., theme::text_muted()))
370 .on_click(cx.listener(move |_, _, _, cx| {
371 cx.emit(SwitcherEvent::Pick(selection.clone()));
372 }))
373 .into_any_element(),
374 );
375 }
376 if !self.messages.is_empty() {
377 rows.push(group_header(MESSAGE_GROUP));
378 }
379 for (offset, message) in self.messages.iter().enumerate() {
380 let index = self.results.len() + offset;
381 let (selection, message_id) = (message.selection.clone(), message.message_id.clone());
382 let marks = message
383 .matches
384 .iter()
385 .map(|range| {
386 (
387 range.clone(),
388 HighlightStyle {
389 color: Some(theme::accent_text()),
390 font_weight: Some(FontWeight::SEMIBOLD),
391 ..Default::default()
392 },
393 )
394 })
395 .collect::<Vec<_>>();
396 rows.push(
397 h_flex()
398 .id(ElementId::Name(format!("switch-message-{index}").into()))
399 .mx(px(6.))
400 .px(px(6.))
401 .h(px(52.))
402 .gap(px(10.))
403 .items_center()
404 .rounded(px(6.))
405 .cursor_pointer()
406 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
407 .hover(|row| row.bg(theme::popup_hover()))
408 .child(person_avatar(directory, None, &message.author, 28.))
409 .child(
410 v_flex()
411 .flex_1()
412 .min_w_0()
413 .gap(px(1.))
414 .child(
415 h_flex()
416 .gap(px(6.))
417 .items_baseline()
418 .child(
419 div()
420 .flex_none()
421 .text_size(px(13.))
422 .font_weight(FontWeight::SEMIBOLD)
423 .text_color(theme::text())
424 .child(message.author.clone()),
425 )
426 .child(
427 div()
428 .min_w_0()
429 .truncate()
430 .text_size(px(12.))
431 .text_color(theme::text_muted())
432 .child(format!("in {}", message.conversation)),
433 )
434 .child(div().flex_1())
435 .child(
436 div()
437 .flex_none()
438 .text_size(px(11.))
439 .text_color(theme::text_muted())
440 .child(message.date.clone()),
441 ),
442 )
443 .child(
444 div()
445 .truncate()
446 .text_size(px(12.5))
447 .text_color(theme::text_soft())
448 .child(
449 StyledText::new(message.snippet.clone())
450 .with_highlights(marks),
451 ),
452 ),
453 )
454 .on_click(cx.listener(move |_, _, _, cx| {
455 cx.emit(SwitcherEvent::PickMessage {
456 selection: selection.clone(),
457 message_id: message_id.clone(),
458 });
459 }))
460 .into_any_element(),
461 );
462 }
463 let footer = h_flex()
464 .h(px(32.))
465 .px(px(12.))
466 .gap(px(16.))
467 .items_center()
468 .text_size(px(11.))
469 .text_color(theme::text_muted())
470 .child("Enter to open")
471 .child("Arrows to select")
472 .child("Esc to close");
473 div()
474 .id("switcher-backdrop")
475 .absolute()
476 .size_full()
477 .top_0()
478 .left_0()
479 .bg(theme::background().opacity(0.6))
480 .flex()
481 .justify_center()
482 .items_start()
483 .pt(px(72.))
484 .on_click(cx.listener(|_, _, _, cx| cx.emit(SwitcherEvent::Close)))
485 .child(
486 v_flex()
487 .id("switcher-card")
488 .w(px(CARD_WIDTH))
489 .max_h(px(640.))
490 .rounded(px(10.))
491 .bg(theme::popup())
492 .overflow_hidden()
493 .on_click(|_, _, cx| cx.stop_propagation())
494 .on_key_down(cx.listener(Self::on_key_down))
495 .child(
496 div()
497 .p(px(8.))
498 .child(Input::new(&self.input).appearance(false).bordered(false)),
499 )
500 .child(v_flex().w_full().py_1().children(rows))
501 .child(footer),
502 )
503 }
504}
505
506#[cfg(test)]
507mod tests {
508 use super::{clamp_highlight, parse_snippet};
509 use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
510
511 #[test]
512 fn snippet_markers_become_ranges() {
513 let raw = format!("a {HIGHLIGHT_START}Build{HIGHLIGHT_END} 42\nok");
514 let (text, matches) = parse_snippet(&raw);
515 assert_eq!(text, "a Build 42 ok");
516 assert_eq!(matches, vec![2..7]);
517 }
518
519 #[test]
520 fn unterminated_or_empty_markers_are_ignored() {
521 let raw = format!("{HIGHLIGHT_START}{HIGHLIGHT_END}x{HIGHLIGHT_START}y");
522 assert_eq!(parse_snippet(&raw), ("xy".to_owned(), Vec::new()));
523 }
524
525 #[test]
526 fn highlight_stays_inside_the_list() {
527 assert_eq!(clamp_highlight(0, -1, 3), 0);
528 assert_eq!(clamp_highlight(2, 1, 3), 2);
529 assert_eq!(clamp_highlight(1, 1, 3), 2);
530 assert_eq!(clamp_highlight(0, 1, 0), 0);
531 }
532}