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
367
368 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
369 match &self.org {
370 OrgState::Ready(emojis) => org_emojis::filter(emojis, &self.query)
371 .into_iter()
372 .cloned()
373 .collect(),
374 _ => Vec::new(),
375 }
376 }
377
378 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
379 if tab == self.tab {
380 return;
381 }
382 self.tab = tab;
383 let placeholder = if tab == Tab::Org {
384 tr("reaction_picker.search.org")
385 } else {
386 "Search emoji".to_owned()
387 };
388 self.input.update(cx, |state, cx| {
389 state.set_placeholder(placeholder, window, cx);
390 state.focus(window, cx);
391 });
392 if tab == Tab::Org {
393 self.load_org_emojis(cx);
394 }
395 cx.notify();
396 }
397
398 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
399 if matches!(self.org, OrgState::Ready(_)) {
400 return;
401 }
402 self.org_generation += 1;
403 let generation = self.org_generation;
404 self.org = OrgState::Loading;
405 let (demo, engine) = {
406 let state = self.app.read(cx);
407 (state.mode.demo, state.engine.clone())
408 };
409 self.org_task = Some(cx.spawn(async move |this, cx| {
410 let outcome = org_emojis::list(engine, demo, false)
411 .await
412 .unwrap_or(Err(OrgEmojiError::Failed));
413 this.update(cx, |this, cx| {
414 if this.org_generation != generation {
415 return;
416 }
417 this.org = match outcome {
418 Ok(emojis) => OrgState::Ready(emojis),
419 Err(_) => OrgState::Failed,
420 };
421 cx.notify();
422 })
423 .ok();
424 }));
425 }
426
427 fn tab_button(&self, tab: Tab, label_key: &str, cx: &mut Context<Self>) -> Stateful<Div> {
428 let selected = tab == self.tab;
429 div()
430 .id(("reaction-picker-tab", tab as usize))
431 .h(px(26.))
432 .px(px(8.))
433 .flex()
434 .items_center()
435 .cursor_pointer()
436 .text_size(px(12.))
437 .font_weight(FontWeight::SEMIBOLD)
438 .border_b_2()
439 .border_color(if selected {
440 theme::accent()
441 } else {
442 transparent_black()
443 })
444 .text_color(if selected {
445 theme::accent_text()
446 } else {
447 theme::text_muted()
448 })
449 .hover(|button| button.text_color(theme::text_strong()))
450 .child(tr(label_key))
451 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
452 }
453
454 fn org_cell(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
455 let key = emoji.key();
456 let name = emoji.name.clone();
457 let selected = self.selected.contains(&key);
458 div()
459 .id(("reaction-picker-org", index))
460 .size(px(CELL_SIZE))
461 .flex_none()
462 .p(px(3.))
463 .rounded(px(6.))
464 .cursor_pointer()
465 .when(selected, |cell| cell.bg(theme::reaction_on_own()))
466 .hover(|cell| cell.bg(theme::popup_hover()))
467 .child(
468 img(bounded(image_source(&emoji.image_url())))
469 .size_full()
470 .object_fit(ObjectFit::Contain),
471 )
472 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
473 .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| {
474 this.pick(&key, event.modifiers().shift, window, cx)
475 }))
476 .into_any_element()
477 }
478
479 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
480 match &self.org {
481 OrgState::Loading => div()
482 .text_size(px(11.))
483 .text_color(theme::text_muted())
484 .child("…")
485 .into_any_element(),
486 OrgState::Failed => div()
487 .text_size(px(11.))
488 .text_color(theme::text_muted())
489 .child(tr("fun_picker.org.failed"))
490 .into_any_element(),
491 OrgState::Ready(_) => {
492 let visible = self.visible_org_emojis();
493 if visible.is_empty() {
494 return div()
495 .text_size(px(11.))
496 .text_color(theme::text_muted())
497 .child(org_empty_message(&self.query))
498 .into_any_element();
499 }
500 let mut rows = Vec::new();
501 let mut row = Vec::new();
502 for (index, emoji) in visible.iter().enumerate() {
503 row.push(self.org_cell(emoji, index, cx));
504 if row.len() == ORG_COLUMNS {
505 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
506 }
507 }
508 if !row.is_empty() {
509 rows.push(h_flex().gap(px(2.)).children(row));
510 }
511 v_flex().gap(px(2.)).children(rows).into_any_element()
512 }
513 }
514 }
515
516
517impl Render for ReactionPicker {
518 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
519 let results = self.results(cx);
520 let label = if self.query.is_empty() {
521 "Recently used"
522 } else if results.is_empty() {
523 "No emoji found"
524 } else {
525 "Results"
526 };
527 let quick = PICKER_QUICK
528 .iter()
529 .enumerate()
530 .map(|(index, glyph)| self.cell((*glyph).to_owned(), 1000 + index, false, cx))
531 .collect::<Vec<_>>();
532 let mut rows = Vec::new();
533 let mut row = Vec::new();
534 for (index, glyph) in results.into_iter().enumerate() {
535 row.push(self.cell(glyph, index, true, cx));
536 if row.len() == GRID_COLUMNS {
537 rows.push(h_flex().gap(px(2.)).children(std::mem::take(&mut row)));
538 }
539 }
540 if !row.is_empty() {
541 rows.push(h_flex().gap(px(2.)).children(row));
542 }
543 let tabs = (!self.customizing).then(|| {
544 h_flex()
545 .flex_none()
546 .gap(px(2.))
547 .child(self.tab_button(Tab::Emoji, "reaction_picker.tab.emoji", cx))
548 .child(self.tab_button(Tab::Org, "reaction_picker.tab.org", cx))
549 });
550 let body = if self.tab == Tab::Org && !self.customizing {
551 self.render_org(cx)
552 } else {
553 v_flex()
554 .gap(px(2.))
555 .child(
556 div()
557 .text_size(px(11.))
558 .text_color(theme::text_muted())
559 .child(label),
560 )
561 .child(v_flex().gap(px(2.)).children(rows))
562 .into_any_element()
563 };
564 v_flex()
565 .w(px(PICKER_WIDTH))
566 .gap(px(8.))
567 .p(px(8.))
568 .children(tabs)
569 .when(self.tab != Tab::Org || self.customizing, |picker| {
570 picker.child(h_flex().gap(px(2.)).children(quick))
571 })
572 .child(
573 h_flex()
574 .gap(px(4.))
575 .items_center()
576 .child(
577 div()
578 .flex_1()
579 .h(px(32.))
580 .px(px(8.))
581 .flex()
582 .items_center()
583 .rounded(px(8.))
584 .bg(theme::popup_hover())
585 .child(Input::new(&self.input).appearance(false).bordered(false)),
586 )
587 .children(self.customize_button(cx)),
588 )
589 .child(body)
590 .children(self.tone_menu(cx))
591 }
592}