BlueGit

ict rusty-teams

Files

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

switcher.rs

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