BlueGit

ict rusty-teams

Files

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

fun_picker.rs

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