Messaging · Stickers and GIFs: a sticker picker and a GIF picker

StickerPicker shows stickers a pack at a time, chosen above with a
segmented control; a search spans every pack and keeps the stickers
whose names hold it. Arrows move, Enter or a press picks. It reuses the
glyph grid, now forms::picks, which takes its columns and cell size and
titles from the host, so emoji, icons and stickers share one searchable
grid; forms::glyphs keeps the emoji and icon pickers.

GifPicker packs host GIFs in two columns, each moving, under a search
it owns; the host hears the trimmed words only when they change, and
categories fill the search while it is empty. Waiting, it shows tiles
in GIF shapes; finding nothing, it says so. Each GIF is a Tab stop that
a press, Enter or Space picks.

The share toggle now shows its state, as the microphone and camera do.
The gallery ships line-drawn stickers and small GIFs made from its own
pictures.
This commit is contained in:
ZacharyZhang-NY committed 2026-09-26 23:00:15 -04:00
1 parent dd465fedb7
commit 1700a72753
27 files changed
+1212 -288

No files matched your search

+1 -1
View File
@@ -108,7 +108,7 @@ impl RenderOnce for CallControls {
),
toggle(
"share",
(IconName::ScreenShareOff, IconName::ScreenShare),
(IconName::ScreenShare, IconName::ScreenShareOff),
"Share screen",
self.share,
),
+266
View File
@@ -0,0 +1,266 @@
use std::rc::Rc;
use gpui::{
App, Context, ElementId, Entity, ImageSource, InteractiveElement, IntoElement, MouseButton,
ParentElement, RenderOnce, SharedString, StatefulInteractiveElement, Styled, Subscription,
Window, div, prelude::*, rems,
};
use crate::{
buttons::{Button, ButtonVariant},
forms::{Input, InputEvent, OnValue, TextInput},
layout::{Masonry, on_axis},
motion::Skeleton,
primitives::{FocusRing, Icon, IconName, Image, Tooltip, checked_ratio, framed},
theme::{ActiveTheme, ControlSize, IconSize, Radius, TextSize},
};
/// Shapes the loading tiles take, so the wait looks like GIFs.
const WAITING: [f32; 6] = [1.5, 1.0, 1.8, 1.25, 1.6, 1.1];
/// A GIF: its key, its title, its picture, and its width over its height.
#[derive(Clone)]
pub struct Gif {
pub key: SharedString,
pub title: SharedString,
pub picture: ImageSource,
pub ratio: f32,
}
impl Gif {
pub fn new(
key: impl Into<SharedString>,
title: impl Into<SharedString>,
picture: impl Into<ImageSource>,
ratio: f32,
) -> Self {
Self {
key: key.into(),
title: title.into(),
picture: picture.into(),
ratio: checked_ratio(ratio),
}
}
}
/// Where a GIF search stands: waiting on the host, or what it found.
#[derive(Clone)]
pub enum Gifs {
Loading,
Found(Vec<Gif>),
}
/// The search field, the words last reported, and who gets them.
struct Search {
input: Entity<TextInput>,
words: SharedString,
on_query: Option<OnValue>,
_changes: Subscription,
}
/// GIFs from the host in two columns packed tight, under a search the host answers; while it is empty, categories fill it. Each GIF is a Tab stop, picked by a press, Enter or Space.
#[derive(IntoElement)]
pub struct GifPicker {
id: ElementId,
gifs: Gifs,
categories: Vec<SharedString>,
on_query: Option<OnValue>,
on_pick: Option<OnValue>,
}
impl GifPicker {
pub fn new(id: impl Into<ElementId>, gifs: Gifs) -> Self {
if let Gifs::Found(found) = &gifs {
for (ix, gif) in found.iter().enumerate() {
let twice = found[..ix].iter().any(|other| other.key == gif.key);
assert!(!twice, "gif {} twice", gif.key);
}
}
Self {
id: id.into(),
gifs,
categories: Vec::new(),
on_query: None,
on_pick: None,
}
}
/// Searches offered while the field is empty; a press puts one in it.
pub fn categories(
mut self,
categories: impl IntoIterator<Item = impl Into<SharedString>>,
) -> Self {
self.categories = categories.into_iter().map(Into::into).collect();
self
}
/// Gets the search's words, trimmed, each time they change.
pub fn on_query(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_query = Some(Rc::new(handler));
self
}
/// Gets the key of the GIF picked.
pub fn on_pick(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_pick = Some(Rc::new(handler));
self
}
}
impl RenderOnce for GifPicker {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let search = window.use_keyed_state(
(self.id.clone(), "search"),
cx,
|window, cx: &mut Context<Search>| {
let input = cx.new(|cx| TextInput::new(window, cx).placeholder("Search GIFs"));
let changes =
cx.subscribe_in(&input, window, |search, input, event, window, cx| {
if *event != InputEvent::Changed {
return;
}
let query = SharedString::from(input.read(cx).text().trim().to_string());
if query == search.words {
return;
}
search.words = query.clone();
log::info!("gif picker: search {query:?}");
if let Some(on_query) = search.on_query.clone() {
on_query(&query, window, cx);
}
cx.notify();
});
Search {
input,
words: SharedString::default(),
on_query: None,
_changes: changes,
}
},
);
search.update(cx, |search, _| search.on_query = self.on_query.clone());
let input = search.read(cx).input.clone();
let empty = input.read(cx).text().trim().is_empty();
let theme = cx.theme();
let colors = &theme.colors;
let round = theme.radius(Radius::Md);
let gap = rems(0.5).to_pixels(window.rem_size());
let categories = (empty && !self.categories.is_empty()).then(|| {
div()
.flex()
.flex_wrap()
.gap_1()
.children(self.categories.iter().map(|category| {
let (field, words) = (input.clone(), category.clone());
Button::new(
(self.id.clone(), format!("category-{category}")),
category.clone(),
)
.variant(ButtonVariant::Subtle)
.size(ControlSize::Sm)
.on_click(move |_, _, cx| {
log::info!("gif picker: category {words}");
let words = words.clone();
field.update(cx, |input, cx| input.set_text(words.to_string(), cx));
})
}))
});
let tiles: Vec<gpui::AnyElement> = match self.gifs {
Gifs::Loading => WAITING
.iter()
.enumerate()
.map(|(ix, ratio)| {
framed(*ratio, cx)
.rounded(round)
.child(
Skeleton::new((self.id.clone(), format!("waiting-{ix}"))).size_full(),
)
.into_any_element()
})
.collect(),
Gifs::Found(found) => found
.into_iter()
.map(|gif| {
let (key, on_pick, owner) =
(gif.key.clone(), self.on_pick.clone(), self.id.clone());
div()
.id((self.id.clone(), format!("gif-{}", gif.key)))
.rounded(round)
.border_1()
.border_color(gpui::transparent_black())
.tab_index(0)
.focus_ring(cx)
.cursor_pointer()
.tooltip(Tooltip::text(gif.title.clone()))
.on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
.on_click(move |_, window, cx| {
log::info!("gif picker {owner}: {key}");
if let Some(on_pick) = &on_pick {
on_pick(&key, window, cx);
}
})
.child(
framed(gif.ratio, cx).rounded(round).child(
Image::new(
(self.id.clone(), format!("picture-{}", gif.key)),
gif.picture,
)
.size_full()
.rounded(round),
),
)
.into_any_element()
})
.collect(),
};
let none = tiles.is_empty().then(|| {
div()
.debug_selector(|| "gifs-none".into())
.py_6()
.flex()
.flex_col()
.items_center()
.gap_2()
.text_size(theme.text_size(TextSize::Sm))
.text_color(colors.fg_muted)
.child(
Icon::new(IconName::SearchX)
.size(IconSize::Lg)
.color(colors.fg_subtle),
)
.child("No GIFs match")
});
let masonry = (!tiles.is_empty())
.then(|| Masonry::new((self.id.clone(), "gifs"), 2, gap).children(tiles));
div()
.debug_selector(|| "gif-picker".into())
.w_full()
.flex()
.flex_col()
.gap_2()
.child(
Input::new(&input).prefix(
Icon::new(IconName::Search)
.size(IconSize::Sm)
.color(colors.fg_subtle),
),
)
.children(categories)
.child(
on_axis(
div()
.id((self.id.clone(), "results"))
.max_h(theme.list_max_height())
.overflow_y_scroll(),
)
.children(none)
.children(masonry),
)
}
}
+4
View File
@@ -1,5 +1,6 @@
mod call;
mod channels;
mod gifs;
mod header;
mod incoming;
mod members;
@@ -8,6 +9,7 @@ mod people;
mod pins;
mod receipt;
mod status;
mod stickers;
mod thread;
mod tiles;
@@ -16,6 +18,7 @@ mod tests;
pub use call::{CallControls, HuddleIndicator, VoiceCallBar};
pub use channels::{ChannelItem, ChannelList, ChatRow, DirectMessageItem};
pub use gifs::{Gif, GifPicker, Gifs};
pub use header::ChannelHeader;
pub use incoming::IncomingCallDialog;
pub use members::{Member, MemberList};
@@ -24,5 +27,6 @@ pub use people::{OnlineStatus, UserProfileCard};
pub use pins::{PinnedMessage, PinnedMessages};
pub use receipt::{Delivery, ReadReceipt};
pub use status::{ClearAfter, Status, StatusSetter};
pub use stickers::{Sticker, StickerPack, StickerPicker};
pub use thread::{MessageThread, ThreadPanel};
pub use tiles::{ParticipantTile, ScreenShareView, VideoCallGrid};
+179
View File
@@ -0,0 +1,179 @@
use std::rc::Rc;
use gpui::{
App, ElementId, ImageSource, InteractiveElement, IntoElement, ObjectFit, ParentElement,
RenderOnce, SharedString, Styled, Window, div,
};
use crate::{
buttons::SegmentedControl,
forms::{Grid, OnValue, finder, grid, rows},
primitives::Image,
theme::{ActiveTheme, ControlSize},
};
/// Stickers across a picker's row, so it fits a narrow window.
const COLUMNS: usize = 4;
/// A sticker: its key, its name, and its square picture.
#[derive(Clone)]
pub struct Sticker {
pub key: SharedString,
pub name: SharedString,
pub picture: ImageSource,
}
impl Sticker {
pub fn new(
key: impl Into<SharedString>,
name: impl Into<SharedString>,
picture: impl Into<ImageSource>,
) -> Self {
Self {
key: key.into(),
name: name.into(),
picture: picture.into(),
}
}
}
/// Stickers under their pack's name.
#[derive(Clone)]
pub struct StickerPack {
pub name: SharedString,
pub stickers: Vec<Sticker>,
}
impl StickerPack {
pub fn new(name: impl Into<SharedString>, stickers: impl IntoIterator<Item = Sticker>) -> Self {
Self {
name: name.into(),
stickers: stickers.into_iter().collect(),
}
}
}
/// Stickers in a grid, a pack at a time, chosen above; a search spans every pack and keeps the stickers whose names hold it. Arrows move, and Enter or a press picks.
#[derive(IntoElement)]
pub struct StickerPicker {
id: ElementId,
packs: Vec<StickerPack>,
on_pick: Option<OnValue>,
}
impl StickerPicker {
pub fn new(id: impl Into<ElementId>, packs: impl IntoIterator<Item = StickerPack>) -> Self {
let packs: Vec<StickerPack> = packs.into_iter().collect();
assert!(!packs.is_empty(), "a sticker picker holds a pack");
for (ix, pack) in packs.iter().enumerate() {
let twice = packs[..ix].iter().any(|other| other.name == pack.name);
assert!(!twice, "pack {} twice", pack.name);
}
let keys: Vec<&SharedString> = packs
.iter()
.flat_map(|pack| pack.stickers.iter().map(|sticker| &sticker.key))
.collect();
for (ix, key) in keys.iter().enumerate() {
assert!(!keys[..ix].contains(key), "sticker {key} twice");
}
Self {
id: id.into(),
packs,
on_pick: None,
}
}
/// Gets the key of the sticker picked.
pub fn on_pick(
mut self,
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
) -> Self {
self.on_pick = Some(Rc::new(handler));
self
}
}
impl RenderOnce for StickerPicker {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let first = self.packs[0].name.clone();
let chosen = window.use_keyed_state((self.id.clone(), "pack"), cx, |_, _| first.clone());
if !self.packs.iter().any(|pack| pack.name == *chosen.read(cx)) {
log::info!("sticker picker {}: pack gone, showing {first}", self.id);
chosen.update(cx, |chosen, _| *chosen = first);
}
let pack = chosen.read(cx).clone();
let finder = finder(&self.id, "Search stickers", window, cx);
let query = finder.read(cx).query.clone();
let packs = (self.packs.len() > 1).then(|| {
let (id, choose) = (self.id.clone(), chosen.clone());
self.packs
.iter()
.fold(
SegmentedControl::new((self.id.clone(), "packs"), pack.clone()),
|packs, each| packs.segment(each.name.clone(), each.name.clone(), None),
)
.size(ControlSize::Sm)
.on_change(move |name, _, cx| {
log::info!("sticker picker {id}: pack {name}");
choose.update(cx, |chosen, cx| {
*chosen = name.clone();
cx.notify();
})
})
});
let found: Rc<Vec<Sticker>> = Rc::new(
self.packs
.into_iter()
.filter(|each| !query.is_empty() || each.name == pack)
.flat_map(|each| each.stickers)
.filter(|sticker| sticker.name.to_lowercase().contains(&query))
.collect(),
);
let (painted, picked) = (found.clone(), found.clone());
let (id, owner, on_pick) = (self.id.clone(), self.id.clone(), self.on_pick);
let stickers = grid(
Grid {
id: self.id,
names: Rc::new(found.iter().map(|sticker| sticker.name.clone()).collect()),
rows: Rc::new(rows([(None, found.len())], COLUMNS)),
selected: None,
draw: Rc::new(move |ix, _| {
let sticker = &painted[ix];
div()
.size_full()
.p_1()
.child(
Image::new(
(owner.clone(), format!("sticker-{}", sticker.key)),
sticker.picture.clone(),
)
.fit(ObjectFit::Contain)
.size_full(),
)
.into_any_element()
}),
pick: Rc::new(move |ix, window, cx| {
let key = &picked[ix].key;
log::info!("sticker picker {id}: {key}");
if let Some(on_pick) = &on_pick {
on_pick(key, window, cx);
}
}),
none: "No stickers match",
columns: COLUMNS,
cell: cx.theme().messaging().sticker,
},
&finder,
window,
cx,
);
div()
.debug_selector(|| "sticker-picker".into())
.flex_none()
.flex()
.flex_col()
.gap_2()
.children(packs)
.child(stickers)
}
}
+1
View File
@@ -12,6 +12,7 @@ use crate::{data_display::Presence, primitives::FocusNext, theme::Theme};
mod calls;
mod messages;
mod people;
mod pickers;
fn setup(cx: &mut TestAppContext) {
cx.update(|cx| {
+200
View File
@@ -0,0 +1,200 @@
use std::path::Path;
use gpui::{
Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled, TestAppContext,
VisualTestContext, Window, div, px,
};
use super::{press, settle, setup, tab_to};
use crate::{
forms,
messaging::{Gif, GifPicker, Gifs, Sticker, StickerPack, StickerPicker},
};
fn sticker(key: &'static str, name: &'static str) -> Sticker {
Sticker::new(key, name, Path::new("/nowhere.png"))
}
fn packs() -> [StickerPack; 2] {
[
StickerPack::new(
"Atrium",
[
sticker("arch", "Arch"),
sticker("stair", "Stair"),
sticker("column", "Column"),
],
),
StickerPack::new(
"Garden",
[sticker("olive", "Olive"), sticker("stone", "Stone")],
),
]
}
/// A picker and what it picked.
struct Stickers {
picked: Vec<SharedString>,
}
impl Render for Stickers {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let owner = cx.entity();
StickerPicker::new("stickers", packs())
.on_pick(move |key, _, cx| owner.update(cx, |host, _| host.picked.push(key.clone())))
}
}
fn stickering(cx: &mut TestAppContext) -> (Entity<Stickers>, &mut VisualTestContext) {
setup(cx);
cx.update(forms::bind_keys);
let (host, cx) = cx.add_window_view(|_, _| Stickers { picked: Vec::new() });
cx.update(|window, _| window.activate_window());
settle(cx);
(host, cx)
}
fn picked(host: &Entity<Stickers>, cx: &mut VisualTestContext) -> Vec<SharedString> {
host.read_with(cx, |host, _| host.picked.clone())
}
#[gpui::test]
fn a_search_spans_every_pack(cx: &mut TestAppContext) {
let (host, cx) = stickering(cx);
tab_to(3, cx);
cx.simulate_input("st");
settle(cx);
cx.simulate_keystrokes("down right enter");
settle(cx);
assert_eq!(
picked(&host, cx),
["stone"],
"Stair and Stone sit side by side, a pack apart"
);
}
#[gpui::test]
fn the_chosen_pack_fills_the_grid(cx: &mut TestAppContext) {
let (host, cx) = stickering(cx);
tab_to(4, cx);
press("enter", cx);
tab_to(2, cx);
press("space", cx);
tab_to(4, cx);
press("enter", cx);
assert_eq!(picked(&host, cx), ["arch", "olive"]);
}
#[test]
#[should_panic(expected = "pack Atrium twice")]
fn a_pack_is_named_once() {
let _ = StickerPicker::new(
"stickers",
[
StickerPack::new("Atrium", [sticker("arch", "Arch")]),
StickerPack::new("Atrium", [sticker("stair", "Stair")]),
],
);
}
#[test]
#[should_panic(expected = "sticker arch twice")]
fn a_sticker_is_listed_once() {
let _ = StickerPicker::new(
"stickers",
[
StickerPack::new("A", [sticker("arch", "Arch")]),
StickerPack::new("B", [sticker("arch", "Arch again")]),
],
);
}
fn gif(key: &'static str) -> Gif {
Gif::new(key, key, Path::new("/nowhere.gif"), 1.5)
}
/// A GIF picker showing `gifs`, and what it heard.
struct Gifing {
gifs: Gifs,
heard: Vec<String>,
}
impl Render for Gifing {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (query, pick) = (cx.entity(), cx.entity());
div().w(px(360.0)).child(
GifPicker::new("gifs", self.gifs.clone())
.categories(["Dunes", "Stairs"])
.on_query(move |words, _, cx| {
query.update(cx, |host, _| host.heard.push(format!("query {words}")))
})
.on_pick(move |key, _, cx| {
pick.update(cx, |host, _| host.heard.push(format!("pick {key}")))
}),
)
}
}
fn gifing(gifs: Gifs, cx: &mut TestAppContext) -> (Entity<Gifing>, &mut VisualTestContext) {
setup(cx);
cx.update(forms::bind_keys);
let (host, cx) = cx.add_window_view(|_, _| Gifing {
gifs,
heard: Vec::new(),
});
cx.update(|window, _| window.activate_window());
settle(cx);
(host, cx)
}
fn heard(host: &Entity<Gifing>, cx: &mut VisualTestContext) -> Vec<String> {
host.read_with(cx, |host, _| host.heard.clone())
}
#[gpui::test]
fn typed_words_and_a_category_reach_the_host(cx: &mut TestAppContext) {
let (host, cx) = gifing(Gifs::Found(vec![gif("a")]), cx);
tab_to(3, cx);
press("space", cx);
tab_to(1, cx);
cx.simulate_input(" more");
settle(cx);
assert_eq!(
heard(&host, cx),
[
"query Stairs",
"query Stairs m",
"query Stairs mo",
"query Stairs mor",
"query Stairs more"
],
"the second category fills the field, typing goes on from it, and a space alone asks nothing"
);
}
#[gpui::test]
fn a_gif_is_a_tab_stop_that_space_picks(cx: &mut TestAppContext) {
let (host, cx) = gifing(Gifs::Found(vec![gif("a"), gif("b")]), cx);
tab_to(5, cx);
press("space", cx);
assert_eq!(heard(&host, cx), ["pick b"]);
}
#[gpui::test]
fn nothing_found_says_so(cx: &mut TestAppContext) {
let (_, cx) = gifing(Gifs::Found(Vec::new()), cx);
assert!(cx.debug_bounds("gifs-none").is_some());
}
#[gpui::test]
fn a_search_under_way_waits_without_saying_nothing(cx: &mut TestAppContext) {
let (_, cx) = gifing(Gifs::Loading, cx);
assert!(cx.debug_bounds("gif-picker").is_some());
assert!(cx.debug_bounds("gifs-none").is_none());
}
#[test]
#[should_panic(expected = "gif a twice")]
fn a_gif_is_listed_once() {
let _ = GifPicker::new("gifs", Gifs::Found(vec![gif("a"), gif("a")]));
}