Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
f7437ce
feat(emoji): rank colon suggestions by shared picker usage
kalvinnchau Nov 20, 2026
5dbae17
fix(emoji): keep fuzzy matches and picker defaults out of usage ranking
kalvinnchau Nov 20, 2026
430df28
fix(emoji): seed one default row and treat malformed stores as empty
kalvinnchau Nov 20, 2026
2e5eef7
fix(emoji): widen a seeded default row and reseed array stores
kalvinnchau Nov 21, 2026
0462146
fix(emoji): reseed a seeded default row at any other picker width
kalvinnchau Nov 21, 2026
643c236
fix(emoji): own usage history so windows and tone prompts count corre…
kalvinnchau Nov 22, 2026
929af5e
fix(emoji): count only applied choices and keep literal shortcodes first
kalvinnchau Nov 22, 2026
804dede
test(emoji): replace the draft after a picker pick with select-all keys
kalvinnchau Nov 22, 2026
26f4be7
fix(emoji): count a reaction picker choice only when it adds
kalvinnchau Nov 23, 2026
9c8479e
test(emoji): drop frequency browser checks covered elsewhere
kalvinnchau Nov 23, 2026
bbe3972
test(emoji): cover the inline reaction picker and document select res…
kalvinnchau Nov 23, 2026
87a8deb
test(emoji): cover both reaction picker removals and pin keyword matches
kalvinnchau Nov 23, 2026
4f4df8c
fix(emoji): remove mart seeded defaults from stored usage once
kalvinnchau Nov 23, 2026
8bd85fe
fix(emoji): keep reaction select meaning success and onselect bundled
kalvinnchau Nov 23, 2026
b9e455e
fix(emoji): record the seed removal marker before rewriting counts
kalvinnchau Nov 23, 2026
5cb445b
fix(emoji): start buzz usage history from mart without its defaults
kalvinnchau Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/bundled/emoji/EmojiCompletion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
searchCustomEmoji,
type EmojiMatch,
} from "./emoji-search";
import { emojiUsage, recordEmojiUsage } from "./emoji-usage";

const OPTICAL_SAMPLE_SIZE = 64;
const OPTICAL_CANVAS_SIZE = 128;
Expand Down Expand Up @@ -105,6 +106,7 @@ function NativeEmojiPreview({ emoji }: { emoji: string }) {

export function EmojiCompletion({
session,
scope,
query,
publish,
}: ComposerCompletionProps) {
Expand All @@ -122,6 +124,7 @@ export function EmojiCompletion({
let live = true;
let withdraw: (() => void) | false = false;
const custom = catalog.entries.filter((item) => !!session.media(item.url));
const uses = emojiUsage(scope);
const items = (matches: readonly EmojiMatch[]) => {
const counts = new Map<string, number>();
for (const item of matches)
Expand All @@ -141,6 +144,7 @@ export function EmojiCompletion({
<NativeEmojiPreview emoji={item.text} />
),
edit: { text: item.text },
onSelect: () => recordEmojiUsage(scope, item.id),
}));
};
// Suggestions may be partial; automatic replacement needs both catalogs.
Expand All @@ -149,10 +153,10 @@ export function EmojiCompletion({
if (catalog.status === "error") void session.emoji.refresh();
};
withdraw = publish({
items: items(searchCustomEmoji(query.query, custom)),
items: items(searchCustomEmoji(query.query, custom, uses)),
status: "Searching emoji…",
});
void searchEmoji(query.query, custom)
void searchEmoji(query.query, custom, uses)
.then((matches) => {
if (!live) return;
if (withdraw) withdraw();
Expand All @@ -173,7 +177,7 @@ export function EmojiCompletion({
if (!live) return;
if (withdraw) withdraw();
withdraw = publish({
items: items(searchCustomEmoji(query.query, custom)),
items: items(searchCustomEmoji(query.query, custom, uses)),
status: "Unicode emoji unavailable. Custom matches shown.",
retry: retrySearch,
});
Expand All @@ -187,6 +191,6 @@ export function EmojiCompletion({
unsubscribe();
if (withdraw) withdraw();
};
}, [session, query.query, publish, catalog, attempt]);
}, [session, scope, query.query, publish, catalog, attempt]);
return null;
}
6 changes: 4 additions & 2 deletions src/bundled/emoji/EmojiPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ export function EmojiPicker({
addEmoji?: Pick<AddEmoji, "snapshot" | "subscribe"> | undefined;
scope: string;
disabled: boolean;
insert(value: string): void;
/** Return false when the choice is rejected or must not count as a use. */
insert(value: string): unknown;
reaction?: boolean;
gifRequests?: GifRequests | undefined;
externalTrigger?: {
Expand Down Expand Up @@ -306,9 +307,10 @@ export function EmojiPicker({
entries,
media: session.media,
select: (value) => {
onInsert.current(value);
const inserted = onInsert.current(value);
accepted.current = true;
setOpen(false);
return inserted;
},
close: () => setOpen(false),
skinToneChange: (tone, menuOpen) =>
Expand Down
7 changes: 6 additions & 1 deletion src/bundled/emoji/ReactionPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export function createReactionPicker(addEmoji?: AddEmoji) {
scope,
disabled,
select,
reacted,
}: ReactionToolProps) {
const [open, setOpen] = useState(false);
const trigger = useRef<HTMLButtonElement>(null);
Expand Down Expand Up @@ -64,7 +65,11 @@ export function createReactionPicker(addEmoji?: AddEmoji) {
session={session}
scope={scope}
disabled={disabled}
insert={select}
// Removing an existing reaction succeeds but is not a use.
insert={(emoji) => {
const removes = reacted?.(emoji) === true;
return select(emoji) && !removes;
}}
addEmoji={addEmoji}
reaction
externalTrigger={{
Expand Down
45 changes: 28 additions & 17 deletions src/bundled/emoji/emoji-mart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import { pickerIcons } from "../../shared/design-system/icons/svg";
// Emoji Mart config adapted from block/buzz's shared picker; see NOTICE.md.
import data from "@emoji-mart/data";
import english from "@emoji-mart/data/i18n/en.json";
import { Data, Picker, SearchIndex } from "emoji-mart";
import { Data, FrequentlyUsed, Picker, SearchIndex } from "emoji-mart";
import type { CustomEmoji } from "../../features/relay/emoji";
import { rankShortcodes } from "./emoji-search";
import { addEmojiUsage, customEmojiId, frequentEmoji } from "./emoji-usage";
import { PREVIEW_ACTION_SLOT } from "./add-emoji";
import {
SKIN_TONE_SLOT,
Expand All @@ -32,10 +33,24 @@ function checkMartPropTimer(picker: HTMLElement) {
"emoji-mart no longer exposes component.nextStateTimer; dispose() cannot cancel its deferred re-render",
);
}
// Buzz owns usage history. Mart caches its copy per window, overwriting other
// windows' choices, and counts a pick before the tone prompt confirms it.
Object.assign(FrequentlyUsed, {
add() {},
get(props: { maxFrequentRows: number; perLine: number }) {
// Mart fills this row last, after dropping from the other categories what
// this client cannot render or this picker does not offer.
const shown = new Set<string>();
for (const category of Data?.categories ?? [])
if (category.id !== "frequent")
for (const emoji of category.emojis)
shown.add(typeof emoji === "string" ? emoji : emoji.id);
return frequentEmoji(props, FrequentlyUsed.DEFAULTS, (id) => shown.has(id));
},
});
const resolvedTheme = (value: unknown): "light" | "dark" =>
value === "dark" ? "dark" : "light";

const prefix = "buzz-custom/";
// Idle and with no matches, the footer shows only its actions; the empty grid
// under the query already says nothing matched.
const previewStrings = {
Expand Down Expand Up @@ -113,7 +128,8 @@ export function mountEmojiMart({
searchChange(value: string): void;
entries: readonly CustomEmoji[];
media(url: string): string | undefined;
select(value: string, customEmoji?: string): void;
/** Return false when the host rejects the insertion; it then does not count. */
select(value: string, customEmoji?: string): unknown;
close(): void;
/** With `preview`, the footer's skin-tone action renders the saved tone (1–6). */
skinToneChange?(tone: number, open: boolean): void;
Expand All @@ -124,7 +140,7 @@ export function mountEmojiMart({
const emojis = entries.flatMap(({ shortcode, url }) => {
const src = media(url);
if (!src) return [];
const id = `${prefix}${encodeURIComponent(scope)}/${shortcode}`;
const id = customEmojiId(scope, shortcode);
const literal = `:${shortcode}:`;
values.set(id, { literal, shortcode });
// Match Mart's first-hyphen query normalization as well as individual words.
Expand All @@ -145,15 +161,6 @@ export function mountEmojiMart({
},
];
});
// Restore Mart's default Frequent row if storage contains a poisoned empty map.
try {
if (localStorage.getItem("emoji-mart.frequently") === "{}") {
localStorage.removeItem("emoji-mart.frequently");
localStorage.removeItem("emoji-mart.last");
}
} catch {
/* Like Mart, selection works without localStorage. */
}
const picker = new Picker({
data,
custom: emojis.length
Expand Down Expand Up @@ -190,12 +197,16 @@ export function mountEmojiMart({
),
onEmojiSelect: (emoji: { native?: string; id?: string }) => {
if (disposed) return;
if (!emoji.id) return;
if (emoji.native) {
if (!promptSkinTone(emoji.id)) select(emoji.native);
if (promptSkinTone(emoji.id)) return;
if (select(emoji.native) !== false) addEmojiUsage(emoji.id);
Comment thread
kalvinnchau marked this conversation as resolved.
Resolved
return;
}
const custom = values.get(emoji.id ?? "");
if (custom) select(custom.literal, custom.shortcode);
const custom = values.get(emoji.id);
if (!custom) return;
if (select(custom.literal, custom.shortcode) !== false)
addEmojiUsage(emoji.id);
},
}) as unknown as HTMLElement;
// The documented web-component attribute updates in place: do not recreate the
Expand Down Expand Up @@ -676,7 +687,7 @@ ${[1, 2, 3, 4, 5, 6].map((tone) => ` .menu .skin-tone-${tone}::before { conte
const tone = chosenTone;
const native = tone && Data?.emojis[id]?.skins[tone - 1]?.native;
if (!native || disposed) return false;
select(native);
if (select(native) !== false) addEmojiUsage(id);
return true;
};
// Mart clears the preview whenever the pointer leaves an emoji, so crossing
Expand Down
59 changes: 55 additions & 4 deletions src/bundled/emoji/emoji-search.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ it("returns every match by default while retaining an explicit limit", async ()
expect(
(await searchEmoji("smile", custom)).filter((item) => item.url),
).toHaveLength(75);
expect(searchCustomEmoji("smile", custom, 12)).toHaveLength(12);
expect(searchCustomEmoji("smile", custom, undefined, 12)).toHaveLength(12);
expect(await searchEmoji("", [])).toEqual([]);
});
it("keeps semantic results ahead of loose shortcode matches", async () => {
Expand Down Expand Up @@ -137,18 +137,69 @@ it("copies native primitives even when Mart previously mutated the shared dictio
});

it("Unicode completions use the picker's saved default skin tone", async () => {
const [hand] = await searchEmoji("call_me_hand", [], 1, 4);
const [hand] = await searchEmoji("call_me_hand", [], undefined, 1, 4);
expect(hand?.text).toBe("🤙🏽");
vi.stubGlobal("localStorage", {
getItem: (key: string) => (key === "emoji-mart.skin" ? "6" : null),
});
try {
const [saved] = await searchEmoji("call_me_hand", [], 1);
const [saved] = await searchEmoji("call_me_hand", [], undefined, 1);
expect(saved?.text).toBe("🤙🏿");
// Emoji without tones keep their only form.
const [rocket] = await searchEmoji("rocket", [], 1);
const [rocket] = await searchEmoji("rocket", [], undefined, 1);
expect(rocket?.text).toBe("🚀");
} finally {
vi.unstubAllGlobals();
}
});

it("keeps alias and keyword matches ahead of often chosen fuzzy matches", async () => {
const first = async (query: string, uses?: (id: string) => number) =>
(await searchEmoji(query, [], uses))[0]?.shortcode;
// `hate` and `poop` are a keyword of 😡 and an alias of 💩, and only
// subsequences of the chosen shortcodes.
for (const [query, fuzzy, match] of [
["hate", "unicode/heart_eyes", "rage"],
["poop", "unicode/person_in_lotus_position", "hankey"],
] as const) {
expect(await first(query)).toBe(match);
expect(await first(query, (id) => (id === fuzzy ? 8 : 0))).toBe(match);
}
});

it("puts often chosen emoji first within exact, prefix and other matches", async () => {
const shortcodes = async (query: string, uses?: (id: string) => number) =>
(await searchEmoji(query, [], uses)).map((item) => item.shortcode);
const usage = (counts: Record<string, number>) => (id: string) =>
counts[id] ?? 0;
const plain = await shortcodes("sm");
const smirk = await shortcodes("sm", usage({ "unicode/smirk": 2 }));
expect(smirk[0]).toBe("smirk");
expect(smirk.slice(1)).toEqual(plain.filter((name) => name !== "smirk"));
// A strong use cannot lift a weaker match over a prefix match.
const sweat = await shortcodes("sm", usage({ "unicode/sweat_smile": 99 }));
expect(sweat.indexOf("sweat_smile")).toBeGreaterThan(sweat.indexOf("smiley"));
// The exact name stays first; equal counts keep the query order.
expect(
(await shortcodes("smile", usage({ "unicode/smiley": 5 }))).slice(0, 2),
).toEqual(["smile", "smiley"]);
// The typed shortcode leads a separator-insensitive namesake used more.
expect(
(await shortcodes("icecream", usage({ "unicode/ice_cream": 9 })))[0],
).toBe("icecream");
expect(
(await shortcodes("ice_cream", usage({ "unicode/icecream": 9 })))[0],
).toBe("ice_cream");
expect(
await shortcodes("sm", usage({ "unicode/smile": 1, "unicode/smirk": 1 })),
).toEqual(plain);
const custom = [
{ shortcode: "party", url: "https://a.test/party.png" },
{ shortcode: "parrot", url: "https://a.test/parrot.png" },
];
expect(
searchCustomEmoji("par", custom, usage({ "custom/party": 1 })).map(
(item) => item.shortcode,
),
).toEqual(["party", "parrot"]);
});
30 changes: 24 additions & 6 deletions src/bundled/emoji/emoji-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type Standard = EmojiMatch & {
};
const normalize = (value: string) => value.toLowerCase().replace(/[-_\s]/g, "");
let standard: Promise<readonly Standard[]> | undefined;
/** Times a match ID was chosen, from the shared emoji usage store. */
type Uses = (id: string) => number;
const unused: Uses = () => 0;

type ShortcodeScore = Readonly<{ tier: number; score: number }>;

Expand Down Expand Up @@ -128,18 +131,20 @@ function semanticScore(query: string, terms: readonly string[]) {
export async function searchEmoji(
query: string,
custom: readonly CustomEmoji[],
uses: Uses = unused,
limit = Number.POSITIVE_INFINITY,
tone = defaultSkinTone(),
): Promise<readonly EmojiMatch[]> {
const native = await loadStandard();
return rankEmoji(query, native, custom, limit, tone);
return rankEmoji(query, native, custom, limit, tone, uses);
}
export function searchCustomEmoji(
query: string,
custom: readonly CustomEmoji[],
uses: Uses = unused,
limit = Number.POSITIVE_INFINITY,
): readonly EmojiMatch[] {
return rankEmoji(query, [], custom, limit, 1);
return rankEmoji(query, [], custom, limit, 1, uses);
}
/** The one match whose shortcode is the typed name; separator-insensitive ranking
* ties (`:1:` for `-1`) and community/Unicode namesakes are not exact. */
Expand All @@ -154,6 +159,7 @@ function rankEmoji(
custom: readonly CustomEmoji[],
limit: number,
tone: number,
uses: Uses,
): readonly EmojiMatch[] {
if (!normalize(query)) return [];
const customCandidates: Standard[] = custom.map(({ shortcode, url }) => ({
Expand Down Expand Up @@ -181,14 +187,26 @@ function rankEmoji(
.map(({ item }) => item)
.filter((item) => !semanticIds.has(item.id)),
];
const literal = query.toLowerCase();
const strong = rank(combined)
.filter(({ tier }) => tier <= 1)
.map(({ item }) => item);
const promoted = new Set(strong.map((item) => item.id));
// The typed shortcode itself leads its separator-insensitive namesakes.
.map((match) =>
match.item.shortcode.toLowerCase() === literal
? { ...match, tier: -1 }
: match,
);
const promoted = new Set(strong.map(({ item }) => item.id));
const ranked = [
...strong,
...combined.filter((item) => !promoted.has(item.id)),
];
...combined
.filter((item) => !promoted.has(item.id))
.map((item) => ({ item, tier: semanticIds.has(item.id) ? 2 : 3 })),
]
// Within literal, exact, prefix, name or keyword, and fuzzy matches, the more often
// chosen emoji comes first; ties and unused emoji keep their query order.
.sort((a, b) => a.tier - b.tier || uses(b.item.id) - uses(a.item.id))
Comment thread
kalvinnchau marked this conversation as resolved.
Resolved
.map(({ item }) => item);
const bounded = Number.isFinite(limit)
? ranked.slice(0, Math.max(0, limit))
: ranked;
Expand Down
Loading
Loading