BlueGit

ict rusty-teams

Files

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

fun_picker.rs

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