BlueGit

ict rusty-teams

Files

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

fun_picker.rs

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