BlueGit

ict rusty-teams

Files

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

fun_picker.rs

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