BlueGit

ict rusty-teams

Files

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

reaction_picker.rs

reaction_picker.rs 18.5 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::rc::Rc;
3
4use gpui_kit::base::PopoverState;
5use gpui_kit::component::{
6 h_flex,
7 input::{Input, InputEvent, InputState},
8 v_flex,
9};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12
13use gpui_kit::assets::IconName;
14use gpui_kit::component::tooltip::Tooltip;
15
16use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};
17use super::skin_tone_choices::{tone_badge, tone_choices};
18use super::widgets::icon;
19use crate::app_state::AppState;
20use crate::emoji;
21use crate::emoticons;
22use crate::rows::reaction_glyph;
23use crate::theme;
24use crate::i18n::{tr, tr_args};
25use crate::org_emojis::{self, OrgEmojiError};
26use crate::remote_image::image_source;
27use crate::views::image_memory::bounded;
28use teams_core::OrgEmoji;
29
30const PICKER_QUICK: [&str; 6] = [
31 "\u{1F44D}",
32 "\u{2764}",
33 "\u{1F602}",
34 "\u{1F62E}",
35 "\u{1F622}",
36 "\u{1F64F}",
37];
38const FALLBACK_RECENT: [&str; 16] = [
39 "\u{1F389}",
40 "\u{1F525}",
41 "\u{1F440}",
42 "\u{2705}",
43 "\u{1F4AF}",
44 "\u{1F680}",
45 "\u{1F605}",
46 "\u{1F914}",
47 "\u{1F44F}",
48 "\u{1F64C}",
49 "\u{1F60A}",
50 "\u{1F4A1}",
51 "\u{1F4CC}",
52 "\u{1F41E}",
53 "\u{1F9EA}",
54 "\u{2615}",
55];
56const PICKER_WIDTH: f32 = 296.;
57const CELL_SIZE: f32 = 32.;
58const GRID_COLUMNS: usize = 8;
59const GRID_LIMIT: usize = 32;
60const ORG_COLUMNS: usize = 8;
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63enum Tab {
64 Emoji,
65 Org,
66}
67
68enum OrgState {
69 Loading,
70 Ready(Vec<OrgEmoji>),
71 Failed,
72}
73
74fn org_empty_message(query: &str) -> String {
75 if query.is_empty() {
76 tr("reaction_picker.org.empty")
77 } else {
78 let mut args = HashMap::new();
79 args.insert("query".into(), query.to_owned());
80 tr_args("reaction_picker.org.empty_query", &args)
81 }
82}
83
84
85pub type PickHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
86pub type DoneHandler = Rc<dyn Fn(&mut Window, &mut App)>;
87
88#[derive(Clone)]
89struct PickTarget {
90 on_pick: PickHandler,
91 on_done: DoneHandler,
92 popover: WeakEntity<PopoverState>,
93}
94
95pub struct ReactionPicker {
96 app: Entity<AppState>,
97 input: Entity<InputState>,
98 query: String,
99 recent: Entity<emoji::Recent>,
100 selected: HashSet<String>,
101 target: Option<PickTarget>,
102 skin_tone: u8,
103 tone_menu: Option<(String, Point<Pixels>)>,
104 customizing: bool,
105 tab: Tab,
106 org: OrgState,
107 org_generation: u64,
108 org_task: Option<Task<()>>,
109 _subscription: Subscription,
110}
111
112impl ReactionPicker {
113 pub fn new(
114 app: Entity<AppState>,
115 recent: Entity<emoji::Recent>,
116 window: &mut Window,
117 cx: &mut Context<Self>,
118 ) -> Self {
119 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search emoji"));
120 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
121 ReactionPicker {
122 app,
123 input,
124 query: String::new(),
125 recent,
126 selected: HashSet::new(),
127 target: None,
128 skin_tone: 0,
129 tone_menu: None,
130 customizing: false,
131 tab: Tab::Emoji,
132 org: OrgState::Loading,
133 org_generation: 0,
134 org_task: None,
135 _subscription: subscription,
136 }
137 }
138
139 pub fn for_customizing(mut self) -> Self {
140 self.customizing = true;
141 self
142 }
143
144 pub fn set_target(
145 &mut self,
146 on_pick: PickHandler,
147 on_done: DoneHandler,
148 popover: WeakEntity<PopoverState>,
149 selected: HashSet<String>,
150 ) {
151 self.target = Some(PickTarget {
152 on_pick,
153 on_done,
154 popover,
155 });
156 self.selected = selected
157 .iter()
158 .map(|glyph| emoticons::without_tone(glyph))
159 .collect();
160 }
161
162 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
163 let store = self.app.read(cx).store.clone();
164 self.skin_tone = teams_core::skin_tone(&store);
165 self.tone_menu = None;
166 self.recent.update(cx, |recent, cx| {
167 recent.reload(&store);
168 cx.notify();
169 });
170 self.query.clear();
171 self.tab = Tab::Emoji;
172 self.input.update(cx, |state, cx| {
173 state.set_value("", window, cx);
174 state.set_placeholder("Search emoji", window, cx);
175 state.focus(window, cx);
176 });
177 if !self.customizing {
178 self.load_org_emojis(cx);
179 }
180 cx.notify();
181 }
182
183 fn on_input_event(
184 &mut self,
185 input: &Entity<InputState>,
186 event: &InputEvent,
187 window: &mut Window,
188 cx: &mut Context<Self>,
189 ) {
190 match event {
191 InputEvent::Change => {
192 self.query = input.read(cx).value().trim().to_owned();
193 cx.notify();
194 }
195 InputEvent::PressEnter { .. } => {
196 let first = if self.tab == Tab::Org {
197 self.visible_org_emojis().first().map(|emoji| emoji.key())
198 } else {
199 self.results(cx).first().cloned()
200 };
201 if let Some(first) = first {
202 self.pick(&first, false, window, cx);
203 }
204 }
205 _ => {}
206 }
207 }
208
209 fn results(&self, cx: &App) -> Vec<String> {
210 let recent = self.recent.read(cx).glyphs();
211 if self.query.is_empty() {
212 let fill = FALLBACK_RECENT
213 .iter()
214 .map(|glyph| (*glyph).to_owned())
215 .filter(|glyph| !recent.contains(glyph));
216 return recent
217 .iter()
218 .cloned()
219 .chain(fill)
220 .take(GRID_LIMIT)
221 .collect();
222 }
223 emoji::search(&self.query, &recent, GRID_LIMIT)
224 .into_iter()
225 .map(|found| found.glyph.to_owned())
226 .collect()
227 }
228
229 fn pick(&mut self, glyph: &str, keep_open: bool, window: &mut Window, cx: &mut Context<Self>) {
230 let target = if keep_open {
231 self.target.clone()
232 } else {
233 self.target.take()
234 };
235 let Some(target) = target else {
236 return;
237 };
238 self.tone_menu = None;
239 let normalized = emoticons::without_tone(&reaction_glyph(glyph));
240 if !self.selected.remove(&normalized) {
241 self.selected.insert(normalized);
242 }
243 (target.on_pick)(glyph, window, cx);
244 if keep_open {
245 cx.notify();
246 return;
247 }
248 target
249 .popover
250 .update(cx, |state, cx| state.dismiss(window, cx))
251 .ok();
252 (target.on_done)(window, cx);
253 }
254
255 fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
256 self.skin_tone = tone;
257 if !self.customizing {
258 self.app
259 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
260 }
261 self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
262 }
263
264 fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {
265 if let Some(target) = self.target.take() {
266 target
267 .popover
268 .update(cx, |state, cx| state.dismiss(window, cx))
269 .ok();
270 (target.on_done)(window, cx);
271 }
272 open_customize_reactions(self.app.clone(), window, cx);
273 }
274
275 fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
276 (!self.customizing).then(|| {
277 div()
278 .id("customize-reactions-trigger")
279 .size(px(CELL_SIZE))
280 .flex_none()
281 .flex()
282 .items_center()
283 .justify_center()
284 .rounded(px(8.))
285 .cursor_pointer()
286 .hover(|button| button.bg(theme::popup_hover()))
287 .child(icon(IconName::Settings, 16., theme::text_soft()))
288 .tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))
289 .on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))
290 .into_any_element()
291 })
292 }
293
294 fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
295 let (base, position) = self.tone_menu.clone()?;
296 let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
297 let glyph = base.clone();
298 Some(tone_choices(
299 "reaction-picker-tones",
300 position,
301 &glyph,
302 self.skin_tone,
303 Rc::new(move |tone, window, cx| {
304 pick_view
305 .update(cx, |this, cx| this.pick_tone(&base, tone, window, cx))
306 .ok();
307 }),
308 Rc::new(move |_, cx| {
309 dismiss_view
310 .update(cx, |this, cx| {
311 this.tone_menu = None;
312 cx.notify();
313 })
314 .ok();
315 }),
316 ))
317 }
318
319 fn cell(
320 &self,
321 glyph: String,
322 index: usize,
323 toned: bool,
324 cx: &mut Context<Self>,
325 ) -> Stateful<Div> {
326 let toneable = toned && emoticons::is_toneable(&glyph);
327 let shown = if toneable {
328 emoticons::with_tone(&glyph, self.skin_tone)
329 } else {
330 glyph.clone()
331 };
332 let picked = shown.clone();
333 let selected = self
334 .selected
335 .contains(&emoticons::without_tone(&reaction_glyph(&glyph)));
336 div()
337 .id(("reaction-picker-cell", index))
338 .relative()
339 .size(px(CELL_SIZE))
340 .flex()
341 .items_center()
342 .justify_center()
343 .rounded(px(6.))
344 .text_size(px(20.))
345 .font_family(theme::EMOJI_FONT_FAMILY)
346 .cursor_pointer()
347 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
348 .hover(|cell| cell.bg(theme::popup_hover()))
349 .child(shown)
350 .when(toneable, |cell| {
351 let base = glyph.clone();
352 cell.child(tone_badge()).on_mouse_down(
353 MouseButton::Right,
354 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
355 cx.stop_propagation();
356 this.tone_menu = Some((base.clone(), event.position));
357 cx.notify();
358 }),
359 )
360 })
361 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
362 this.pick(&picked, event.modifiers().shift, window, cx)
363 }))
364 }
365
366 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
367 match &self.org {
368 OrgState::Ready(emojis) => org_emojis::filter(emojis.as_slice(), &self.query)
369 .into_iter()
370 .cloned()
371 .collect(),
372 _ => Vec::new(),
373 }
374 }
375
376 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
377 if tab == self.tab {
378 return;
379 }
380 self.tab = tab;
381 let placeholder = if tab == Tab::Org {
382 tr("reaction_picker.search.org")
383 } else {
384 "Search emoji".to_owned()
385 };
386 self.input.update(cx, |state, cx| {
387 state.set_placeholder(placeholder, window, cx);
388 state.focus(window, cx);
389 });
390 if tab == Tab::Org {
391 self.load_org_emojis(cx);
392 }
393 cx.notify();
394 }
395
396 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
397 if matches!(self.org, OrgState::Ready(_)) {
398 return;
399 }
400 self.org_generation += 1;
401 let generation = self.org_generation;
402 self.org = OrgState::Loading;
403 let (demo, engine) = {
404 let state = self.app.read(cx);
405 (state.mode.demo, state.engine.clone())
406 };
407 self.org_task = Some(cx.spawn(async move |this, cx| {
408 let outcome = org_emojis::list(engine, demo, false)
409 .await
410 .unwrap_or(Err(OrgEmojiError::Failed));
411 this.update(cx, |this, cx| {
412 if this.org_generation != generation {
413 return;
414 }
415 this.org = match outcome {
416 Ok(emojis) => OrgState::Ready(emojis),
417 Err(_) => OrgState::Failed,
418 };
419 cx.notify();
420 })
421 .ok();
422 }));
423 }
424
425 fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
426 let selected = tab == self.tab;
427 div()
428 .id(("reaction-picker-tab", tab as usize))
429 .h(px(26.))
430 .px(px(8.))
431 .flex()
432 .items_center()
433 .cursor_pointer()
434 .text_size(px(12.))
435 .font_weight(FontWeight::SEMIBOLD)
436 .border_b_2()
437 .border_color(if selected {
438 theme::accent()
439 } else {
440 transparent_black()
441 })
442 .text_color(if selected {
443 theme::accent_text()
444 } else {
445 theme::text_muted()
446 })
447 .hover(|button| button.text_color(theme::text_strong()))
448 .child(tr(label_key))
449 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
450 }
451
452 fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
453 let key = emoji.key();
454 let name = emoji.name.clone();
455 let selected = self.selected.contains(&key);
456 div()
457 .id(("reaction-picker-org", index))
458 .size(px(CELL_SIZE))
459 .flex_none()
460 .p(px(3.))
461 .rounded(px(6.))
462 .cursor_pointer()
463 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
464 .hover(|cell| cell.bg(theme::popup_hover()))
465 .child(
466 img(bounded(image_source(&emoji.image_url())))
467 .size_full()
468 .object_fit(ObjectFit::Contain),
469 )
470 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
471 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
472 this.pick(&key, event.modifiers().shift, window, cx)
473 }))
474 .into_any_element()
475 }
476
477 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
478 match &self.org {
479 OrgState::Loading => div()
480 .text_size(px(11.))
481 .text_color(theme::text_muted())
482 .child("…")
483 .into_any_element(),
484 OrgState::Failed => div()
485 .text_size(px(11.))
486 .text_color(theme::text_muted())
487 .child(tr("fun_picker.org.failed"))
488 .into_any_element(),
489 OrgState::Ready(_) => {
490 let visible = self.visible_org_emojis();
491 if visible.is_empty() {
492 return div()
493 .text_size(px(11.))
494 .text_color(theme::text_muted())
495 .child(org_empty_message(&self.query))
496 .into_any_element();
497 }
498 let mut rows = Vec::new();
499 let mut row = Vec::new();
500 for (index, emoji) in visible.iter().enumerate() {
501 row.push(self.org_cell(emoji, index, cx));
502 if row.len() == ORG_COLUMNS {
503 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
504 }
505 }
506 if !row.is_empty() {
507 rows.push(h_flex().gap(px(2.)).children(row));
508 }
509 v_flex().gap(px(2.)).children(rows).into_any_element()
510 }
511 }
512 }
513}
514
515impl Render for ReactionPicker {
516 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
517 let results = self.results(cx);
518 let label = if self.query.is_empty() {
519 "Recently used"
520 } else if results.is_empty() {
521 "No emoji found"
522 } else {
523 "Results"
524 };
525 let quick = PICKER_QUICK
526 .iter()
527 .enumerate()
528 .map(|(index, glyph)| self.cell((*glyph).to_owned(), 1000 + index, false, cx))
529 .collect::<Vec<_>>();
530 let mut rows = Vec::new();
531 let mut row = Vec::new();
532 for (index, glyph) in results.into_iter().enumerate() {
533 row.push(self.cell(glyph, index, true, cx));
534 if row.len() == GRID_COLUMNS {
535 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
536 }
537 }
538 if !row.is_empty() {
539 rows.push(h_flex().gap(px(2.)).children(row));
540 }
541 let tabs = (!self.customizing).then(|| {
542 h_flex()
543 .flex_none()
544 .gap(px(2.))
545 .child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
546 .child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
547 });
548 let body = if self.tab == Tab::Org && !self.customizing {
549 self.render_org(cx)
550 } else {
551 v_flex()
552 .gap(px(2.))
553 .child(
554 div()
555 .text_size(px(11.))
556 .text_color(theme::text_muted())
557 .child(label),
558 )
559 .child(v_flex().gap(px(2.)).children(rows))
560 .into_any_element()
561 };
562 v_flex()
563 .w(px(PICKER_WIDTH))
564 .gap(px(8.))
565 .p(px(8.))
566 .children(tabs)
567 .when(self.tab != Tab::Org || self.customizing, |picker| {
568 picker.child(h_flex().gap(px(2.)).children(quick))
569 })
570 .child(
571 h_flex()
572 .gap(px(4.))
573 .items_center()
574 .child(
575 div()
576 .flex_1()
577 .h(px(32.))
578 .px(px(8.))
579 .flex()
580 .items_center()
581 .rounded(px(8.))
582 .bg(theme::popup_hover())
583 .child(Input::new(&self.input).appearance(false).bordered(false)),
584 )
585 .children(self.customize_button(cx)),
586 )
587 .child(body)
588 .children(self.tone_menu(cx))
589 }
590}