BlueGit

ict rusty-teams

Files

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

fun_picker.rs

fun_picker.rs 33.8 KiB Download Raw
1use crate::views::image_memory::bounded;
2use std::rc::Rc;
3use std::time::Duration;
4
5use gpui_kit::base::PopoverState;
6use gpui_kit::component::scroll::ScrollableElement as _;
7use gpui_kit::component::{
8 h_flex,
9 input::{Input, InputEvent, InputState},
10 v_flex,
11};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14use gpui_kit::component::tooltip::Tooltip;
15use std::collections::HashMap;
16use teams_core::{Gif, OrgEmoji};
17
18use super::skin_tone_choices::{tone_badge, tone_choices};
19use crate::app_state::AppState;
20use crate::emoji;
21use crate::emoticons;
22use crate::gifs::{self, GifError};
23use crate::i18n::{tr, tr_args};
24use crate::org_emojis::{self, OrgEmojiError};
25use crate::remote_image::{RemoteImage, image_source};
26use crate::stickers::{self, Sticker};
27use crate::theme;
28
29const TAB_KEY: &str = "fun_picker_tab";
30const WIDTH: f32 = 360.;
31const HEIGHT: f32 = 380.;
32const PADDING: f32 = 8.;
33const CONTENT_WIDTH: f32 = WIDTH - 2. * PADDING;
34const EMOJI_COLUMNS: usize = 10;
35const EMOJI_CELL: f32 =
36 (CONTENT_WIDTH - EMOJI_GAP * (EMOJI_COLUMNS - 1) as f32) / EMOJI_COLUMNS as f32;
37const EMOJI_GAP: f32 = 2.;
38const EMOJI_SEARCH_LIMIT: usize = 240;
39const GIF_COLUMNS: usize = 3;
40const GIF_GAP: f32 = 6.;
41const GIF_DEBOUNCE: Duration = Duration::from_millis(300);
42const GIF_MIN_HEIGHT: f32 = 48.;
43const GIF_MAX_HEIGHT: f32 = 200.;
44const GIF_PLACEHOLDER_HEIGHTS: [f32; 9] = [90., 70., 110., 80., 100., 70., 100., 90., 80.];
45const STICKER_COLUMNS: usize = 4;
46const ORG_COLUMNS: usize = 8;
47const ORG_GAP: f32 = 4.;
48const ORG_CELL: f32 =
49 (CONTENT_WIDTH - ORG_GAP * (ORG_COLUMNS - 1) as f32) / ORG_COLUMNS as f32;
50const STICKER_GAP: f32 = 6.;
51const POPULAR_LABEL: &str = "Beliebt";
52const TILE_RADIUS: f32 = 6.;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum Tab {
56 Emoji,
57 Gif,
58 Sticker,
59 Org,
60}
61
62impl Tab {
63 const ALL: [Tab; 4] = [Tab::Emoji, Tab::Gif, Tab::Sticker, Tab::Org];
64
65 fn key(self) -> &'static str {
66 match self {
67 Tab::Emoji => "emoji",
68 Tab::Gif => "gif",
69 Tab::Sticker => "sticker",
70 Tab::Org => "org",
71 }
72 }
73
74 fn from_key(key: &str) -> Option<Tab> {
75 Tab::ALL.into_iter().find(|tab| tab.key() == key)
76 }
77
78 fn label(self) -> String {
79 tr(match self {
80 Tab::Emoji => "fun_picker.tab.emoji",
81 Tab::Gif => "fun_picker.tab.gif",
82 Tab::Sticker => "fun_picker.tab.sticker",
83 Tab::Org => "fun_picker.tab.org",
84 })
85 }
86
87 fn placeholder(self) -> String {
88 tr(match self {
89 Tab::Emoji => "fun_picker.search.emoji",
90 Tab::Gif => "fun_picker.search.gif",
91 Tab::Sticker => "fun_picker.search.sticker",
92 Tab::Org => "fun_picker.search.org",
93 })
94 }
95}
96
97enum OrgState {
98 Loading,
99 Ready(Vec<OrgEmoji>),
100 Failed,
101}
102
103fn org_empty_message(query: &str) -> String {
104 if query.is_empty() {
105 tr("fun_picker.org.empty")
106 } else {
107 let mut args = HashMap::new();
108 args.insert("query".into(), query.to_owned());
109 tr_args("fun_picker.org.empty_query", &args)
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114enum StickerChip {
115 Popular,
116 Category(&'static str),
117}
118
119enum GifState {
120 Loading,
121 Ready(Vec<Gif>),
122 Failed,
123 Disabled,
124}
125
126enum EmojiRow {
127 Header(&'static str),
128 Cells(Vec<String>),
129}
130
131pub enum FunPickerEvent {
132 Emoji(String),
133 Image(RemoteImage),
134}
135
136pub struct FunPicker {
137 app: Entity<AppState>,
138 input: Entity<InputState>,
139 tab: Tab,
140 query: String,
141 recent: emoji::Recent,
142 popover: Option<WeakEntity<PopoverState>>,
143 skin_tone: u8,
144 tone_menu: Option<(String, Point<Pixels>)>,
145 emoji_rows: Vec<EmojiRow>,
146 emoji_scroll: UniformListScrollHandle,
147 gifs: GifState,
148 gif_generation: u64,
149 gif_task: Option<Task<()>>,
150 chip: StickerChip,
151 sticker_rows: Vec<Vec<&'static Sticker>>,
152 sticker_scroll: UniformListScrollHandle,
153 org: OrgState,
154 org_generation: u64,
155 org_task: Option<Task<()>>,
156 org_scroll: UniformListScrollHandle,
157 _subscription: Subscription,
158}
159
160impl EventEmitter<FunPickerEvent> for FunPicker {}
161
162fn emoji_rows(query: &str, recent: &[String]) -> Vec<EmojiRow> {
163 let chunked = |glyphs: Vec<String>| -> Vec<EmojiRow> {
164 glyphs
165 .chunks(EMOJI_COLUMNS)
166 .map(|chunk| EmojiRow::Cells(chunk.to_vec()))
167 .collect()
168 };
169 if !query.is_empty() {
170 let found = emoji::search(query, recent, EMOJI_SEARCH_LIMIT)
171 .into_iter()
172 .map(|found| found.glyph.to_owned())
173 .collect();
174 return chunked(found);
175 }
176 let mut rows = Vec::new();
177 if !recent.is_empty() {
178 rows.push(EmojiRow::Header("Zuletzt verwendet"));
179 rows.extend(chunked(recent.to_vec()));
180 }
181 rows.push(EmojiRow::Header("Alle Emojis"));
182 rows.extend(chunked(emoji::glyphs().map(str::to_owned).collect()));
183 rows
184}
185
186fn sticker_rows(query: &str, chip: StickerChip) -> Vec<Vec<&'static Sticker>> {
187 let stickers = if !query.is_empty() {
188 stickers::search(query)
189 } else {
190 match chip {
191 StickerChip::Popular => stickers::popular(),
192 StickerChip::Category(category) => stickers::in_category(category),
193 }
194 };
195 stickers
196 .chunks(STICKER_COLUMNS)
197 .map(<[&Sticker]>::to_vec)
198 .collect()
199}
200
201/// Indices per column; each item goes to the currently shortest column.
202fn masonry(heights: &[f32], columns: usize) -> Vec<Vec<usize>> {
203 let mut layout: Vec<Vec<usize>> = vec![Vec::new(); columns];
204 let mut totals = vec![0_f32; columns];
205 for (index, height) in heights.iter().enumerate() {
206 let shortest = totals
207 .iter()
208 .enumerate()
209 .min_by(|left, right| left.1.total_cmp(right.1))
210 .map_or(0, |(column, _)| column);
211 layout[shortest].push(index);
212 totals[shortest] += height + GIF_GAP;
213 }
214 layout
215}
216
217fn gif_tile_width() -> f32 {
218 (CONTENT_WIDTH - GIF_GAP * (GIF_COLUMNS - 1) as f32) / GIF_COLUMNS as f32
219}
220
221fn gif_tile_height(gif: &Gif) -> f32 {
222 let ratio = gif.preview_height as f32 / gif.preview_width.max(1) as f32;
223 (gif_tile_width() * ratio).clamp(GIF_MIN_HEIGHT, GIF_MAX_HEIGHT)
224}
225
226fn sticker_tile_size() -> f32 {
227 (CONTENT_WIDTH - STICKER_GAP * (STICKER_COLUMNS - 1) as f32) / STICKER_COLUMNS as f32
228}
229
230impl FunPicker {
231 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
232 let input = cx.new(|cx| InputState::new(window, cx).placeholder(Tab::Emoji.placeholder()));
233 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
234 let recent = emoji::Recent::load(&app.read(cx).store);
235 let skin_tone = teams_core::skin_tone(&app.read(cx).store);
236 FunPicker {
237 app,
238 input,
239 tab: Tab::Emoji,
240 query: String::new(),
241 emoji_rows: emoji_rows("", &recent.glyphs()),
242 recent,
243 popover: None,
244 skin_tone,
245 tone_menu: None,
246 emoji_scroll: UniformListScrollHandle::new(),
247 gifs: GifState::Loading,
248 gif_generation: 0,
249 gif_task: None,
250 chip: StickerChip::Popular,
251 sticker_rows: sticker_rows("", StickerChip::Popular),
252 sticker_scroll: UniformListScrollHandle::new(),
253 org: OrgState::Loading,
254 org_generation: 0,
255 org_task: None,
256 org_scroll: UniformListScrollHandle::new(),
257 _subscription: subscription,
258 }
259 }
260
261 pub fn set_popover(&mut self, popover: WeakEntity<PopoverState>) {
262 self.popover = Some(popover);
263 }
264
265 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
266 let store = self.app.read(cx).store.clone();
267 self.recent.reload(&store);
268 self.skin_tone = teams_core::skin_tone(&store);
269 self.tone_menu = None;
270 self.tab = store
271 .meta(TAB_KEY)
272 .ok()
273 .flatten()
274 .and_then(|key| Tab::from_key(&key))
275 .unwrap_or(Tab::Emoji);
276 self.show_tab(window, cx);
277 }
278
279 fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
280 if tab == self.tab {
281 return;
282 }
283 self.tab = tab;
284 let _ = self.app.read(cx).store.set_meta(TAB_KEY, tab.key());
285 self.show_tab(window, cx);
286 }
287
288 fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
289 self.query.clear();
290 let placeholder = self.tab.placeholder();
291 self.input.update(cx, |state, cx| {
292 state.set_value("", window, cx);
293 state.set_placeholder(placeholder, window, cx);
294 state.focus(window, cx);
295 });
296 self.refresh(false, cx);
297 }
298
299 fn refresh(&mut self, debounce: bool, cx: &mut Context<Self>) {
300 match self.tab {
301 Tab::Emoji => {
302 self.emoji_rows = emoji_rows(&self.query, &self.recent.glyphs());
303 self.emoji_scroll.scroll_to_item(0, ScrollStrategy::Top);
304 }
305 Tab::Gif => self.search_gifs(debounce, cx),
306 Tab::Sticker => {
307 self.sticker_rows = sticker_rows(&self.query, self.chip);
308 self.sticker_scroll.scroll_to_item(0, ScrollStrategy::Top);
309 }
310 Tab::Org => self.load_org_emojis(cx),
311 }
312 cx.notify();
313 }
314
315 fn on_input_event(
316 &mut self,
317 input: &Entity<InputState>,
318 event: &InputEvent,
319 window: &mut Window,
320 cx: &mut Context<Self>,
321 ) {
322 match event {
323 InputEvent::Change => {
324 let query = input.read(cx).value().trim().to_owned();
325 if query != self.query {
326 self.query = query;
327 self.refresh(true, cx);
328 }
329 }
330 InputEvent::PressEnter { .. } if self.tab == Tab::Emoji => {
331 let first = self.emoji_rows.iter().find_map(|row| match row {
332 EmojiRow::Cells(glyphs) => glyphs.first().cloned(),
333 EmojiRow::Header(_) => None,
334 });
335 if let Some(glyph) = first.filter(|_| !self.query.is_empty()) {
336 self.pick_emoji(&glyph, cx);
337 }
338 }
339 InputEvent::PressEnter { .. } if self.tab == Tab::Org => {
340 if let Some(emoji) = self.visible_org_emojis().first().cloned() {
341 let image = RemoteImage::custom_emoji(&emoji);
342 self.pick_image(image, window, cx);
343 }
344 }
345 _ => {}
346 }
347 }
348
349 fn search_gifs(&mut self, debounce: bool, cx: &mut Context<Self>) {
350 self.gif_generation += 1;
351 let generation = self.gif_generation;
352 self.gifs = GifState::Loading;
353 let query = self.query.clone();
354 let (demo, engine) = {
355 let state = self.app.read(cx);
356 (state.mode.demo, state.engine.clone())
357 };
358 self.gif_task = Some(cx.spawn(async move |this, cx| {
359 if debounce {
360 cx.background_executor().timer(GIF_DEBOUNCE).await;
361 }
362 let outcome = gifs::search(engine, demo, query)
363 .await
364 .unwrap_or(Err(GifError::Failed));
365 this.update(cx, |this, cx| {
366 if this.gif_generation != generation {
367 return;
368 }
369 this.gifs = match outcome {
370 Ok(found) => GifState::Ready(found),
371 Err(GifError::Disabled) => GifState::Disabled,
372 Err(GifError::Failed) => GifState::Failed,
373 };
374 cx.notify();
375 })
376 .ok();
377 }));
378 }
379
380 fn pick_emoji(&mut self, glyph: &str, cx: &mut Context<Self>) {
381 self.tone_menu = None;
382 self.recent.push(&emoticons::without_tone(glyph));
383 self.refresh(false, cx);
384 cx.emit(FunPickerEvent::Emoji(glyph.to_owned()));
385 }
386
387 fn pick_tone(&mut self, glyph: &str, tone: u8, cx: &mut Context<Self>) {
388 self.skin_tone = tone;
389 self.app
390 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
391 self.pick_emoji(&emoticons::with_tone(glyph, tone), cx);
392 }
393
394 fn render_tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
395 let (glyph, position) = self.tone_menu.clone()?;
396 let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
397 Some(tone_choices(
398 "fun-picker-tones",
399 position,
400 &glyph.clone(),
401 self.skin_tone,
402 Rc::new(move |tone, _, cx| {
403 pick_view
404 .update(cx, |this, cx| this.pick_tone(&glyph, tone, cx))
405 .ok();
406 }),
407 Rc::new(move |_, cx| {
408 dismiss_view
409 .update(cx, |this, cx| {
410 this.tone_menu = None;
411 cx.notify();
412 })
413 .ok();
414 }),
415 ))
416 }
417
418 fn pick_image(&mut self, image: RemoteImage, window: &mut Window, cx: &mut Context<Self>) {
419 if let Some(popover) = &self.popover {
420 popover
421 .update(cx, |state, cx| state.dismiss(window, cx))
422 .ok();
423 }
424 cx.emit(FunPickerEvent::Image(image));
425 }
426
427 fn select_chip(&mut self, chip: StickerChip, cx: &mut Context<Self>) {
428 self.chip = chip;
429 self.refresh(false, cx);
430 }
431
432 fn tab_button(&self, tab: Tab, cx: &mut Context<Self>) -> Stateful<Div> {
433 let selected = tab == self.tab;
434 div()
435 .id(("fun-picker-tab", tab as usize))
436 .h(px(32.))
437 .px(px(8.))
438 .flex()
439 .items_center()
440 .cursor_pointer()
441 .text_size(px(12.))
442 .font_weight(FontWeight::SEMIBOLD)
443 .border_b_2()
444 .border_color(if selected {
445 theme::accent()
446 } else {
447 transparent_black()
448 })
449 .text_color(if selected {
450 theme::accent_text()
451 } else {
452 theme::text_muted()
453 })
454 .hover(|button| button.text_color(theme::text_strong()))
455 .child(tab.label())
456 .on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
457 }
458
459 fn search_field(&self) -> Div {
460 div()
461 .h(px(32.))
462 .px(px(8.))
463 .flex()
464 .flex_none()
465 .items_center()
466 .rounded(px(8.))
467 .bg(theme::popup_hover())
468 .child(Input::new(&self.input).appearance(false).bordered(false))
469 }
470
471 fn message(text: String) -> Div {
472 div()
473 .size_full()
474 .flex()
475 .flex_col()
476 .gap(px(8.))
477 .items_center()
478 .justify_center()
479 .text_size(px(12.5))
480 .text_color(theme::text_muted())
481 .child(text)
482 }
483
484 fn emoji_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
485 let row = match &self.emoji_rows[index] {
486 EmojiRow::Header(title) => {
487 return div()
488 .h(px(EMOJI_CELL + EMOJI_GAP))
489 .flex()
490 .items_end()
491 .pb(px(4.))
492 .text_size(px(11.))
493 .text_color(theme::text_muted())
494 .child(*title)
495 .into_any_element();
496 }
497 EmojiRow::Cells(glyphs) => glyphs,
498 };
499 let cells = row.iter().enumerate().map(|(column, glyph)| {
500 let cell_id = index * EMOJI_COLUMNS + column;
501 let toneable = emoticons::is_toneable(glyph);
502 let shown = emoticons::with_tone(glyph, self.skin_tone);
503 let picked = shown.clone();
504 div()
505 .id(("fun-picker-emoji", cell_id))
506 .relative()
507 .size(px(EMOJI_CELL))
508 .flex_none()
509 .flex()
510 .items_center()
511 .justify_center()
512 .rounded(px(6.))
513 .text_size(px(20.))
514 .font_family(theme::EMOJI_FONT_FAMILY)
515 .cursor_pointer()
516 .hover(|cell| cell.bg(theme::popup_hover()))
517 .child(shown)
518 .when(toneable, |cell| {
519 let base = glyph.clone();
520 cell.child(tone_badge()).on_mouse_down(
521 MouseButton::Right,
522 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
523 cx.stop_propagation();
524 this.tone_menu = Some((base.clone(), event.position));
525 cx.notify();
526 }),
527 )
528 })
529 .on_click(cx.listener(move |this, _, _, cx| this.pick_emoji(&picked, cx)))
530 });
531 h_flex()
532 .h(px(EMOJI_CELL + EMOJI_GAP))
533 .gap(px(EMOJI_GAP))
534 .children(cells)
535 .into_any_element()
536 }
537
538 fn render_emoji(&self, cx: &mut Context<Self>) -> AnyElement {
539 if self.emoji_rows.is_empty() {
540 return Self::message(format!("Keine Emojis zu \"{}\"", self.query)).into_any_element();
541 }
542 uniform_list(
543 "fun-picker-emoji-list",
544 self.emoji_rows.len(),
545 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
546 range
547 .map(|index| this.emoji_row(index, cx))
548 .collect::<Vec<_>>()
549 }),
550 )
551 .track_scroll(&self.emoji_scroll)
552 .size_full()
553 .into_any_element()
554 }
555
556 fn gif_tile(&self, gif: &Gif, index: usize, cx: &mut Context<Self>) -> AnyElement {
557 let picked = RemoteImage::gif(gif);
558 div()
559 .id(("fun-picker-gif", index))
560 .w(px(gif_tile_width()))
561 .h(px(gif_tile_height(gif)))
562 .flex_none()
563 .rounded(px(TILE_RADIUS))
564 .overflow_hidden()
565 .bg(theme::surface_raised())
566 .cursor_pointer()
567 .hover(|tile| tile.opacity(0.85))
568 .child(
569 img(bounded(image_source(&gif.preview_url)))
570 .id(("fun-picker-gif-image", index))
571 .size_full()
572 .object_fit(ObjectFit::Cover),
573 )
574 .on_click(
575 cx.listener(move |this, _, window, cx| this.pick_image(picked.clone(), window, cx)),
576 )
577 .into_any_element()
578 }
579
580 fn gif_columns(columns: Vec<Vec<AnyElement>>) -> AnyElement {
581 h_flex()
582 .w_full()
583 .items_start()
584 .gap(px(GIF_GAP))
585 .children(
586 columns
587 .into_iter()
588 .map(|column| v_flex().gap(px(GIF_GAP)).children(column)),
589 )
590 .into_any_element()
591 }
592
593 fn render_gifs(&self, cx: &mut Context<Self>) -> AnyElement {
594 let body = match &self.gifs {
595 GifState::Loading => {
596 let layout = masonry(&GIF_PLACEHOLDER_HEIGHTS, GIF_COLUMNS);
597 Self::gif_columns(
598 layout
599 .into_iter()
600 .map(|column| {
601 column
602 .into_iter()
603 .map(|index| {
604 div()
605 .w(px(gif_tile_width()))
606 .h(px(GIF_PLACEHOLDER_HEIGHTS[index]))
607 .flex_none()
608 .rounded(px(TILE_RADIUS))
609 .bg(theme::surface_raised())
610 .into_any_element()
611 })
612 .collect()
613 })
614 .collect(),
615 )
616 }
617 GifState::Ready(found) if found.is_empty() => {
618 let text = if self.query.is_empty() {
619 "Keine GIFs gefunden".to_owned()
620 } else {
621 format!("Keine GIFs zu \"{}\"", self.query)
622 };
623 return Self::message(text).into_any_element();
624 }
625 GifState::Ready(found) => {
626 let heights: Vec<f32> = found.iter().map(gif_tile_height).collect();
627 let layout = masonry(&heights, GIF_COLUMNS);
628 Self::gif_columns(
629 layout
630 .into_iter()
631 .map(|column| {
632 column
633 .into_iter()
634 .map(|index| self.gif_tile(&found[index], index, cx))
635 .collect()
636 })
637 .collect(),
638 )
639 }
640 GifState::Failed => {
641 return Self::message("GIFs konnten nicht geladen werden.".to_owned())
642 .child(
643 div()
644 .id("fun-picker-gif-retry")
645 .h(px(28.))
646 .px(px(12.))
647 .flex()
648 .items_center()
649 .rounded(px(6.))
650 .bg(theme::popup_hover())
651 .text_color(theme::text())
652 .cursor_pointer()
653 .hover(|button| button.bg(theme::border_strong()))
654 .child("Erneut versuchen")
655 .on_click(cx.listener(|this, _, _, cx| this.refresh(false, cx))),
656 )
657 .into_any_element();
658 }
659 GifState::Disabled => {
660 return Self::message("GIFs sind in deiner Organisation deaktiviert.".to_owned())
661 .into_any_element();
662 }
663 };
664 div()
665 .id("fun-picker-gifs")
666 .size_full()
667 .overflow_y_scrollbar()
668 .child(body)
669 .into_any_element()
670 }
671
672 fn sticker_row(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
673 let size = sticker_tile_size();
674 let tiles = self.sticker_rows[index]
675 .iter()
676 .enumerate()
677 .map(|(column, sticker)| {
678 let picked = RemoteImage::sticker(sticker);
679 div()
680 .id(("fun-picker-sticker", index * STICKER_COLUMNS + column))
681 .size(px(size))
682 .flex_none()
683 .p(px(4.))
684 .rounded(px(TILE_RADIUS))
685 .bg(theme::popup_hover())
686 .cursor_pointer()
687 .hover(|tile| tile.bg(theme::border_strong()))
688 .child(
689 img(bounded(image_source(&sticker.url())))
690 .size_full()
691 .object_fit(ObjectFit::Contain),
692 )
693 .on_click(cx.listener(move |this, _, window, cx| {
694 this.pick_image(picked.clone(), window, cx)
695 }))
696 });
697 h_flex()
698 .h(px(size + STICKER_GAP))
699 .gap(px(STICKER_GAP))
700 .children(tiles)
701 .into_any_element()
702 }
703
704 fn chip_button(&self, chip: StickerChip, cx: &mut Context<Self>) -> Stateful<Div> {
705 let (label, id) = match chip {
706 StickerChip::Popular => (POPULAR_LABEL.to_owned(), "popular"),
707 StickerChip::Category(category) => (stickers::category_label(category), category),
708 };
709 let selected = self.query.is_empty() && chip == self.chip;
710 div()
711 .id(ElementId::Name(format!("fun-picker-chip-{id}").into()))
712 .h(px(26.))
713 .px(px(10.))
714 .flex_none()
715 .flex()
716 .items_center()
717 .rounded_full()
718 .cursor_pointer()
719 .text_size(px(12.))
720 .when(selected, |button| {
721 button
722 .bg(theme::accent_soft())
723 .text_color(theme::accent_text())
724 })
725 .when(!selected, |button| {
726 button
727 .bg(theme::surface_raised())
728 .text_color(theme::text_muted())
729 .hover(|button| button.text_color(theme::text_strong()))
730 })
731 .child(label)
732 .on_click(cx.listener(move |this, _, _, cx| this.select_chip(chip, cx)))
733 }
734
735 fn render_stickers(&self, cx: &mut Context<Self>) -> AnyElement {
736 let chips = std::iter::once(StickerChip::Popular)
737 .chain(
738 stickers::categories()
739 .into_iter()
740 .map(StickerChip::Category),
741 )
742 .map(|chip| self.chip_button(chip, cx))
743 .collect::<Vec<_>>();
744 let grid = if self.sticker_rows.is_empty() {
745 Self::message(format!("Keine Sticker zu \"{}\"", self.query)).into_any_element()
746 } else {
747 uniform_list(
748 "fun-picker-sticker-list",
749 self.sticker_rows.len(),
750 cx.processor(|this, range: std::ops::Range<usize>, _, cx| {
751 range
752 .map(|index| this.sticker_row(index, cx))
753 .collect::<Vec<_>>()
754 }),
755 )
756 .track_scroll(&self.sticker_scroll)
757 .size_full()
758 .into_any_element()
759 };
760 v_flex()
761 .size_full()
762 .gap(px(8.))
763 .child(
764 h_flex()
765 .id("fun-picker-chips")
766 .w_full()
767 .flex_none()
768 .gap(px(6.))
769 .overflow_x_scroll()
770 .children(chips),
771 )
772 .child(div().flex_1().min_h_0().child(grid))
773 .into_any_element()
774 }
775}
776
777
778 fn visible_org_emojis(&self) -> Vec<OrgEmoji> {
779 match &self.org {
780 OrgState::Ready(emojis) => org_emojis::filter(emojis, &self.query)
781 .into_iter()
782 .cloned()
783 .collect(),
784 _ => Vec::new(),
785 }
786 }
787
788 fn load_org_emojis(&mut self, cx: &mut Context<Self>) {
789 if matches!(self.org, OrgState::Ready(_)) {
790 self.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
791 return;
792 }
793 self.org_generation += 1;
794 let generation = self.org_generation;
795 self.org = OrgState::Loading;
796 let (demo, engine) = {
797 let state = self.app.read(cx);
798 (state.mode.demo, state.engine.clone())
799 };
800 self.org_task = Some(cx.spawn(async move |this, cx| {
801 let outcome = org_emojis::list(engine, demo, false)
802 .await
803 .unwrap_or(Err(OrgEmojiError::Failed));
804 this.update(cx, |this, cx| {
805 if this.org_generation != generation {
806 return;
807 }
808 this.org = match outcome {
809 Ok(emojis) => OrgState::Ready(emojis),
810 Err(_) => OrgState::Failed,
811 };
812 this.org_scroll.scroll_to_item(0, ScrollStrategy::Top);
813 cx.notify();
814 })
815 .ok();
816 }));
817 }
818
819 fn reload_org_emojis(&mut self, cx: &mut Context<Self>) {
820 self.org = OrgState::Loading;
821 self.load_org_emojis(cx);
822 }
823
824 fn org_tile(&self, emoji: &OrgEmoji, index: usize, cx: &mut Context<Self>) -> AnyElement {
825 let picked = RemoteImage::custom_emoji(emoji);
826 let name = emoji.name.clone();
827 div()
828 .id(("fun-picker-org", index))
829 .size(px(ORG_CELL))
830 .flex_none()
831 .p(px(4.))
832 .rounded(px(TILE_RADIUS))
833 .cursor_pointer()
834 .hover(|tile| tile.bg(theme::popup_hover()))
835 .child(
836 img(bounded(image_source(&emoji.image_url())))
837 .size_full()
838 .object_fit(ObjectFit::Contain),
839 )
840 .tooltip(move |window, cx| Tooltip::new(name.clone()).build(window, cx))
841 .on_click(cx.listener(move |this, _, window, cx| {
842 this.pick_image(picked.clone(), window, cx)
843 }))
844 .into_any_element()
845 }
846
847 fn render_org(&self, cx: &mut Context<Self>) -> AnyElement {
848 match &self.org {
849 OrgState::Loading => Self::message(String::new())
850 .child(
851 div()
852 .size_full()
853 .flex()
854 .items_center()
855 .justify_center()
856 .text_color(theme::text_muted())
857 .child("…"),
858 )
859 .into_any_element(),
860 OrgState::Failed => Self::message(tr("fun_picker.org.failed"))
861 .child(
862 div()
863 .id("fun-picker-org-retry")
864 .h(px(28.))
865 .px(px(12.))
866 .flex()
867 .items_center()
868 .rounded(px(6.))
869 .bg(theme::popup_hover())
870 .text_color(theme::text())
871 .cursor_pointer()
872 .hover(|button| button.bg(theme::border_strong()))
873 .child(tr("fun_picker.org.retry"))
874 .on_click(cx.listener(|this, _, _, cx| this.reload_org_emojis(cx))),
875 )
876 .into_any_element(),
877 OrgState::Ready(emojis) => {
878 let visible = org_emojis::filter(emojis, &self.query);
879 if visible.is_empty() {
880 return Self::message(org_empty_message(&self.query)).into_any_element();
881 }
882 let rows: Vec<Vec<OrgEmoji>> = visible
883 .into_iter()
884 .cloned()
885 .collect::<Vec<_>>()
886 .chunks(ORG_COLUMNS)
887 .map(|chunk| chunk.to_vec())
888 .collect();
889 uniform_list(
890 "fun-picker-org-list",
891 rows.len(),
892 cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
893 range
894 .map(|index| {
895 let tiles = rows[index].iter().enumerate().map(|(column, emoji)| {
896 this.org_tile(emoji, index * ORG_COLUMNS + column, cx)
897 });
898 h_flex()
899 .h(px(ORG_CELL + ORG_GAP))
900 .gap(px(ORG_GAP))
901 .children(tiles)
902 .into_any_element()
903 })
904 .collect::<Vec<_>>()
905 }),
906 )
907 .track_scroll(&self.org_scroll)
908 .size_full()
909 .into_any_element()
910 }
911 }
912 }
913
914impl Render for FunPicker {
915 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
916 let tabs = Tab::ALL.map(|tab| self.tab_button(tab, cx));
917 let body = match self.tab {
918 Tab::Emoji => self.render_emoji(cx),
919 Tab::Gif => self.render_gifs(cx),
920 Tab::Sticker => self.render_stickers(cx),
921 Tab::Org => self.render_org(cx),
922 };
923 v_flex()
924 .w(px(WIDTH))
925 .h(px(HEIGHT))
926 .gap(px(8.))
927 .p(px(PADDING))
928 .child(h_flex().flex_none().gap(px(2.)).children(tabs))
929 .child(self.search_field())
930 .child(div().flex_1().min_h_0().child(body))
931 .children(self.render_tone_menu(cx))
932 .when(self.tab == Tab::Gif, |picker| {
933 picker.child(
934 div()
935 .flex_none()
936 .flex()
937 .justify_end()
938 .text_size(px(10.5))
939 .text_color(theme::text_faint())
940 .child("Powered by GIPHY"),
941 )
942 })
943 }
944}
945
946#[cfg(test)]
947mod tests {
948 use super::{EmojiRow, STICKER_COLUMNS, StickerChip, Tab, emoji_rows, masonry, sticker_rows};
949
950 #[test]
951 fn tabs_round_trip_through_their_keys() {
952 for tab in Tab::ALL {
953 assert_eq!(Tab::from_key(tab.key()), Some(tab));
954 }
955 assert_eq!(Tab::from_key("unknown"), None);
956 }
957
958 #[test]
959 fn masonry_fills_the_shortest_column() {
960 let layout = masonry(&[100., 50., 50., 50.], 2);
961 assert_eq!(layout, vec![vec![0, 3], vec![1, 2]]);
962 }
963
964 #[test]
965 fn emoji_rows_lead_with_recent_and_filter_by_query() {
966 let recent = vec!["\u{1F44D}".to_owned()];
967 let rows = emoji_rows("", &recent);
968 assert!(matches!(rows[0], EmojiRow::Header("Zuletzt verwendet")));
969 assert!(matches!(&rows[1], EmojiRow::Cells(cells) if cells == &recent));
970 let found = emoji_rows("thumbs", &recent);
971 assert!(!found.is_empty());
972 assert!(found.iter().all(|row| matches!(row, EmojiRow::Cells(_))));
973 }
974
975 #[test]
976 fn sticker_rows_hold_four_and_search_spans_categories() {
977 let popular = sticker_rows("", StickerChip::Popular);
978 assert_eq!(popular.len(), 2);
979 assert_eq!(popular[0].len(), STICKER_COLUMNS);
980 let found = sticker_rows("coffee", StickerChip::Category("Clippy"));
981 assert!(
982 found
983 .iter()
984 .flatten()
985 .any(|sticker| sticker.id == "Octocorn_Coffee")
986 );
987 }
988}