From f7437ce6e5d4942deca6a2d57b18175411f936cc Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Fri, 20 Nov 2026 15:24:24 -0800 Subject: [PATCH 01/16] feat(emoji): rank colon suggestions by shared picker usage colon suggestions read emoji mart's frequently used counts, the store the picker already maintains, and order more-used emoji first within exact, prefix and other matches. ties and new users keep the query order. accepted suggestions record through emoji mart's own frequentlyused.add, so the picker's cached counts and frequently used row include them. completion suggestions gain an optional onselect that the host calls once after a successful insertion (click, tab, enter or terminator), never on highlight. custom emoji share the picker's scoped id helper. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiCompletion.tsx | 12 ++- src/bundled/emoji/emoji-mart.ts | 4 +- src/bundled/emoji/emoji-search.test.ts | 38 ++++++- src/bundled/emoji/emoji-search.ts | 26 +++-- src/bundled/emoji/emoji-usage.test.ts | 44 ++++++++ src/bundled/emoji/emoji-usage.ts | 43 ++++++++ .../conversation/ComposerCompletions.test.tsx | 18 ++++ .../conversation/ComposerCompletions.tsx | 9 +- src/features/conversation/completion.ts | 3 + src/features/conversation/contracts.ts | 2 + tests/browser/emoji-frequency.spec.mjs | 101 ++++++++++++++++++ 11 files changed, 281 insertions(+), 19 deletions(-) create mode 100644 src/bundled/emoji/emoji-usage.test.ts create mode 100644 src/bundled/emoji/emoji-usage.ts create mode 100644 tests/browser/emoji-frequency.spec.mjs diff --git a/src/bundled/emoji/EmojiCompletion.tsx b/src/bundled/emoji/EmojiCompletion.tsx index 9d9f30c9d3..367f48e44a 100644 --- a/src/bundled/emoji/EmojiCompletion.tsx +++ b/src/bundled/emoji/EmojiCompletion.tsx @@ -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; @@ -105,6 +106,7 @@ function NativeEmojiPreview({ emoji }: { emoji: string }) { export function EmojiCompletion({ session, + scope, query, publish, }: ComposerCompletionProps) { @@ -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(); for (const item of matches) @@ -141,6 +144,7 @@ export function EmojiCompletion({ ), edit: { text: item.text }, + onSelect: () => recordEmojiUsage(scope, item.id), })); }; // Suggestions may be partial; automatic replacement needs both catalogs. @@ -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(); @@ -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, }); @@ -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; } diff --git a/src/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index 3db240fb45..5bcf487b41 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -8,6 +8,7 @@ import english from "@emoji-mart/data/i18n/en.json"; import { Data, Picker, SearchIndex } from "emoji-mart"; import type { CustomEmoji } from "../../features/relay/emoji"; import { rankShortcodes } from "./emoji-search"; +import { customEmojiId } from "./emoji-usage"; import { PREVIEW_ACTION_SLOT } from "./add-emoji"; import { SKIN_TONE_SLOT, @@ -35,7 +36,6 @@ function checkMartPropTimer(picker: HTMLElement) { 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 = { @@ -124,7 +124,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. diff --git a/src/bundled/emoji/emoji-search.test.ts b/src/bundled/emoji/emoji-search.test.ts index 72a7a4ef34..c2a7f86504 100644 --- a/src/bundled/emoji/emoji-search.test.ts +++ b/src/bundled/emoji/emoji-search.test.ts @@ -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 () => { @@ -137,18 +137,48 @@ 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("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) => (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"]); + 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"]); +}); diff --git a/src/bundled/emoji/emoji-search.ts b/src/bundled/emoji/emoji-search.ts index ea52cebacf..8b1fbdadf0 100644 --- a/src/bundled/emoji/emoji-search.ts +++ b/src/bundled/emoji/emoji-search.ts @@ -16,6 +16,9 @@ type Standard = EmojiMatch & { }; const normalize = (value: string) => value.toLowerCase().replace(/[-_\s]/g, ""); let standard: Promise | 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 }>; @@ -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 { 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. */ @@ -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 }) => ({ @@ -181,14 +187,18 @@ function rankEmoji( .map(({ item }) => item) .filter((item) => !semanticIds.has(item.id)), ]; - const strong = rank(combined) - .filter(({ tier }) => tier <= 1) - .map(({ item }) => item); - const promoted = new Set(strong.map((item) => item.id)); + const strong = rank(combined).filter(({ tier }) => tier <= 1); + 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: 2 })), + ] + // Within exact, prefix and other 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)) + .map(({ item }) => item); const bounded = Number.isFinite(limit) ? ranked.slice(0, Math.max(0, limit)) : ranked; diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts new file mode 100644 index 0000000000..6aca0b06b4 --- /dev/null +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -0,0 +1,44 @@ +// @vitest-environment jsdom +import { FrequentlyUsed } from "emoji-mart"; +import { afterEach, expect, it } from "vitest"; +import { customEmojiId, emojiUsage, recordEmojiUsage } from "./emoji-usage"; + +const stored = () => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"); +afterEach(() => localStorage.clear()); + +it("reads the picker's counts for Unicode and community suggestions", () => { + localStorage.setItem( + "emoji-mart.frequently", + JSON.stringify({ + smile: 3, + [customEmojiId("wss://relay.test/a", "party")]: 2, + odd: "4", + }), + ); + const uses = emojiUsage("wss://relay.test/a"); + expect(uses("unicode/smile")).toBe(3); + expect(uses("custom/party")).toBe(2); + expect(emojiUsage("wss://relay.test/b")("custom/party")).toBe(0); + expect(uses("unicode/odd")).toBe(0); + expect(uses("unicode/constructor")).toBe(0); + localStorage.setItem("emoji-mart.frequently", "not json"); + expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); +}); + +it("records through Mart so picker and suggestion choices share one history", async () => { + FrequentlyUsed.add({ id: "joy" }); // a picker choice + recordEmojiUsage("wss://relay.test/a", "unicode/joy"); + recordEmojiUsage("wss://relay.test/a", "custom/party"); + recordEmojiUsage("wss://relay.test/a", "other/joy"); + await expect.poll(stored).toEqual({ + joy: 2, + [customEmojiId("wss://relay.test/a", "party")]: 1, + }); + // A later picker save rewrites Mart's cached counts, keeping both sources. + FrequentlyUsed.add({ id: "joy" }); + expect(stored()).toEqual({ + joy: 3, + [customEmojiId("wss://relay.test/a", "party")]: 1, + }); +}); diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts new file mode 100644 index 0000000000..aaad1512d5 --- /dev/null +++ b/src/bundled/emoji/emoji-usage.ts @@ -0,0 +1,43 @@ +// Picker and autocomplete share Emoji Mart's usage store: its Frequently used +// row and the counts that rank colon suggestions. +const STORE = "emoji-mart.frequently"; + +/** The picker's ID for a community emoji, scoped like its catalog. */ +export const customEmojiId = (scope: string, shortcode: string) => + `buzz-custom/${encodeURIComponent(scope)}/${shortcode}`; + +/** Mart's usage ID for a suggestion ID: the base emoji across skin tones. */ +function usageId(scope: string, id: string) { + if (id.startsWith("unicode/")) return id.slice("unicode/".length); + if (id.startsWith("custom/")) + return customEmojiId(scope, id.slice("custom/".length)); + return undefined; +} + +/** How often each suggestion was chosen; 0 when unknown or unreadable. */ +export function emojiUsage(scope: string): (id: string) => number { + let counts: Record = {}; + try { + const stored: unknown = JSON.parse(localStorage.getItem(STORE) ?? "{}"); + if (stored && typeof stored === "object") + counts = stored as Record; + } catch { + /* Without storage, suggestions keep their query order. */ + } + return (id) => { + const key = usageId(scope, id); + const count = key && Object.hasOwn(counts, key) ? counts[key] : 0; + return typeof count === "number" && count > 0 ? count : 0; + }; +} + +/** Record through Mart itself: it caches the counts and rewrites them whole. */ +export function recordEmojiUsage(scope: string, id: string) { + const key = usageId(scope, id); + if (!key) return; + void import("emoji-mart") + .then(({ FrequentlyUsed }) => FrequentlyUsed.add({ id: key })) + .catch(() => { + /* Insertion already happened; usage is best effort, like Mart's own. */ + }); +} diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 60684f4e03..dc693a6508 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -289,6 +289,24 @@ it("ignores the agent flag from providers outside the bundled people providers", }); const folder = { kind: "folder", id: "/notes", label: "@notes" }; +it.each([true, false])( + "tells the provider once about an accepted choice, never a rejected one (accepted: %s)", + async (accepted) => { + const onSelect = vi.fn(); + mountPeople("test.plugin", { + replace: () => accepted, + items: [ + { id: "first", label: "First", edit: { text: "1" }, onSelect }, + { id: "second", label: "Second", edit: { text: "2" } }, + ], + }); + const option = await screen.findByRole("option", { name: "First" }); + fireEvent.pointerMove(option); + expect(onSelect).not.toHaveBeenCalled(); + fireEvent.click(option); + expect(onSelect).toHaveBeenCalledTimes(accepted ? 1 : 0); + }, +); it.each([true, false])( "hands a chip edit to the composer only from a bundled provider (bundled: %s)", async (bundled) => { diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index ae99a21aa8..2f9d3a624c 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -547,7 +547,14 @@ function OwnedCompletion({ const accepted = withHumanMentionSelection(event, () => current.current.replace(item.edit, source.query, observation, key), ); - if (accepted) current.current.editor.invalidate(); + if (accepted) { + current.current.editor.invalidate(); + try { + item.onSelect?.(); + } catch { + /* A provider callback cannot undo the accepted edit. */ + } + } return accepted; } useLayoutEffect(() => { diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index dbb2c13c90..2e07d7716d 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -183,6 +183,9 @@ export function completionResult( ...(typeof item.canSelect === "function" ? { canSelect: item.canSelect } : {}), + ...(typeof item.onSelect === "function" + ? { onSelect: item.onSelect } + : {}), edit: host ? edit : Object.freeze( diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 91bfd95caa..bd6cde7f7c 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -444,6 +444,8 @@ export type CompletionSuggestion = Readonly<{ disabled?: string | undefined; /** Final synchronous evidence check; false never falls through to sending. */ canSelect?: ((key: string) => boolean) | undefined; + /** Called once after the host inserts this choice; never for highlighting. */ + onSelect?: (() => void) | undefined; }>; export type CompletionResult = Readonly<{ items: readonly CompletionSuggestion[]; diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs new file mode 100644 index 0000000000..3c1d919488 --- /dev/null +++ b/tests/browser/emoji-frequency.spec.mjs @@ -0,0 +1,101 @@ +import { test, expect } from "./source-fixture.mjs"; +import { watchPageErrors } from "./page-errors.mjs"; + +// Picker and colon suggestions learn from one usage history that survives reload. +test("emoji chosen in the picker or suggestions rise in both, after reload too", async ({ + page, +}) => { + const errors = watchPageErrors(page); + await page.route("**/emoji-media/**", (route) => + route.fulfill({ + contentType: "image/svg+xml", + body: '', + }), + ); + await page.goto("/tests/fixtures/emoji.html"); + const input = page.getByRole("textbox", { name: "Message #general" }); + const choices = page.getByRole("option"); + const labels = () => + choices.locator("[data-completion-label]").allTextContents(); + const search = page.getByRole("searchbox", { name: "Search emoji" }); + const frequent = page.locator( + 'em-emoji-picker .category[data-id="frequent"] button', + ); + const openPicker = async () => { + await page + .getByRole("button", { name: "Emoji and GIFS", exact: true }) + .click(); + await expect(search).toBeVisible(); + }; + const openFrequent = async () => { + await openPicker(); + await search.fill(""); + await expect(frequent.first()).toBeVisible(); + }; + const closePicker = async () => { + await page.keyboard.press("Escape"); + await expect(search).toHaveCount(0); + }; + + // New users get the query order. + await input.fill(":sm"); + await expect(choices.first()).toHaveText(/:smile:/); + await input.fill(":party-p"); + await expect.poll(labels).toEqual([":party-parrot:", ":party-parrot-wave:"]); + // Highlighting a suggestion is not choosing it. + await input.press("ArrowDown"); + await expect(choices.nth(1)).toHaveAttribute("aria-selected", "true"); + await input.press("Escape"); + await input.fill(":party-p"); + await expect.poll(labels).toEqual([":party-parrot:", ":party-parrot-wave:"]); + + // A picker choice ranks first among its prefix matches. + await input.fill(""); + await openPicker(); + await search.fill("smirk"); + await expect( + page.locator('em-emoji-picker .category button[aria-label="😏"]').first(), + ).toBeVisible(); + await page.keyboard.press("Enter"); + await expect(input).toHaveJSProperty("value", "😏 "); + await input.fill(":sm"); + await expect(choices.first()).toHaveText(/:smirk:/); + await input.press("Tab"); + await expect(input).toHaveJSProperty("value", "😏 "); + + // A keyboard suggestion choice of a community emoji teaches suggestions and + // the picker's Frequently used row, once. + await input.fill(":party-p"); + await expect.poll(labels).toEqual([":party-parrot:", ":party-parrot-wave:"]); + await input.press("ArrowDown"); + await input.press("Enter"); + await expect(input).toHaveJSProperty("value", ":party-parrot-wave: "); + await input.fill(":party-p"); + await expect.poll(labels).toEqual([":party-parrot-wave:", ":party-parrot:"]); + await input.press("Escape"); + await input.fill(""); + const counts = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ); + expect(await counts()).toMatchObject({ + smirk: 2, + "buzz-custom/a/party-parrot-wave": 1, + }); + await openFrequent(); + await expect(frequent.locator('img[src*="wave.png"]')).toHaveCount(1); + await expect(frequent.and(page.locator('[aria-label="😏"]'))).toHaveCount(1); + await closePicker(); + + await page.reload(); + await input.fill(":sm"); + await expect(choices.first()).toHaveText(/:smirk:/); + await input.fill(":party-p"); + await expect.poll(labels).toEqual([":party-parrot-wave:", ":party-parrot:"]); + await input.press("Escape"); + await input.fill(""); + await openFrequent(); + await expect(frequent.locator('img[src*="wave.png"]')).toHaveCount(1); + await closePicker(); + expect(errors.unexplained()).toEqual([]); +}); From 5dbae17dbdd5bf47cb5801906ebbd193022e2d20 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Fri, 20 Nov 2026 15:39:23 -0800 Subject: [PATCH 02/16] fix(emoji): keep fuzzy matches and picker defaults out of usage ranking fuzzy-only matches get their own lowest relevance group, so a frequent subsequence match cannot outrank an alias or keyword match. buzz seeds emoji mart's default frequently used row with weights below one choice before mart reads an empty store, from the picker or a suggestion, and usage counts only whole choices. defaults keep filling the picker row without ranking as picks. help notes the bounded history. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-mart.ts | 15 ++---- src/bundled/emoji/emoji-search.test.ts | 14 ++++++ src/bundled/emoji/emoji-search.ts | 6 +-- src/bundled/emoji/emoji-usage.test.ts | 67 ++++++++++++++++++++------ src/bundled/emoji/emoji-usage.ts | 34 +++++++++++-- tests/browser/emoji-frequency.spec.mjs | 17 ++++++- 6 files changed, 117 insertions(+), 36 deletions(-) diff --git a/src/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index 5bcf487b41..299bb02ac6 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -5,10 +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 { customEmojiId } from "./emoji-usage"; +import { customEmojiId, seedEmojiUsage } from "./emoji-usage"; import { PREVIEW_ACTION_SLOT } from "./add-emoji"; import { SKIN_TONE_SLOT, @@ -145,15 +145,8 @@ 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. */ - } + // Also restores the default row if storage contains a poisoned empty map. + seedEmojiUsage(FrequentlyUsed.DEFAULTS); const picker = new Picker({ data, custom: emojis.length diff --git a/src/bundled/emoji/emoji-search.test.ts b/src/bundled/emoji/emoji-search.test.ts index c2a7f86504..6113ea7051 100644 --- a/src/bundled/emoji/emoji-search.test.ts +++ b/src/bundled/emoji/emoji-search.test.ts @@ -153,6 +153,20 @@ it("Unicode completions use the picker's saved default skin tone", async () => { } }); +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] of [ + ["hate", "unicode/heart_eyes"], + ["poop", "unicode/person_in_lotus_position"], + ] as const) { + const plain = await first(query); + expect(await first(query, (id) => (id === fuzzy ? 8 : 0))).toBe(plain); + } +}); + 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); diff --git a/src/bundled/emoji/emoji-search.ts b/src/bundled/emoji/emoji-search.ts index 8b1fbdadf0..bac06addd6 100644 --- a/src/bundled/emoji/emoji-search.ts +++ b/src/bundled/emoji/emoji-search.ts @@ -193,10 +193,10 @@ function rankEmoji( ...strong, ...combined .filter((item) => !promoted.has(item.id)) - .map((item) => ({ item, tier: 2 })), + .map((item) => ({ item, tier: semanticIds.has(item.id) ? 2 : 3 })), ] - // Within exact, prefix and other matches, the more often chosen emoji - // comes first; ties and unused emoji keep their query order. + // Within 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)) .map(({ item }) => item); const bounded = Number.isFinite(limit) diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 6aca0b06b4..b4f4ae6f75 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -1,18 +1,23 @@ // @vitest-environment jsdom import { FrequentlyUsed } from "emoji-mart"; import { afterEach, expect, it } from "vitest"; -import { customEmojiId, emojiUsage, recordEmojiUsage } from "./emoji-usage"; +import { + customEmojiId, + emojiUsage, + recordEmojiUsage, + seedEmojiUsage, +} from "./emoji-usage"; -const stored = () => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"); +const party = customEmojiId("wss://relay.test/a", "party"); afterEach(() => localStorage.clear()); -it("reads the picker's counts for Unicode and community suggestions", () => { +it("reads whole choices from the picker's counts for Unicode and community suggestions", () => { localStorage.setItem( "emoji-mart.frequently", JSON.stringify({ smile: 3, - [customEmojiId("wss://relay.test/a", "party")]: 2, + [party]: 2.5, + seeded: 0.9, odd: "4", }), ); @@ -20,25 +25,55 @@ it("reads the picker's counts for Unicode and community suggestions", () => { expect(uses("unicode/smile")).toBe(3); expect(uses("custom/party")).toBe(2); expect(emojiUsage("wss://relay.test/b")("custom/party")).toBe(0); + expect(uses("unicode/seeded")).toBe(0); expect(uses("unicode/odd")).toBe(0); expect(uses("unicode/constructor")).toBe(0); + // JSON parses an out-of-range count as Infinity. + localStorage.setItem("emoji-mart.frequently", '{"huge":1e400}'); + expect(emojiUsage("s")("unicode/huge")).toBe(0); localStorage.setItem("emoji-mart.frequently", "not json"); expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); -it("records through Mart so picker and suggestion choices share one history", async () => { - FrequentlyUsed.add({ id: "joy" }); // a picker choice - recordEmojiUsage("wss://relay.test/a", "unicode/joy"); +it("seeds the default row below one choice, only into an empty store", () => { + seedEmojiUsage(["+1", "grinning"]); + const seeded = JSON.parse( + localStorage.getItem("emoji-mart.frequently") ?? "", + ); + expect(seeded["+1"]).toBeGreaterThan(seeded.grinning); + expect(seeded["+1"]).toBeLessThan(1); + expect(emojiUsage("s")("unicode/+1")).toBe(0); + localStorage.setItem("emoji-mart.frequently", '{"smile":1}'); + seedEmojiUsage(["+1"]); + expect(localStorage.getItem("emoji-mart.frequently")).toBe('{"smile":1}'); + // A poisoned empty map gets the default row back. + localStorage.setItem("emoji-mart.frequently", "{}"); + seedEmojiUsage(["+1"]); + expect(emojiUsage("s")("unicode/+1")).toBe(0); + expect(localStorage.getItem("emoji-mart.frequently")).not.toBe("{}"); +}); + +// Mart caches its counts for the module's lifetime, so this runs as one story. +it("records through Mart so picker and suggestion choices share one seeded history", async () => { + // The first choice, from suggestions, still seeds Mart's default row. recordEmojiUsage("wss://relay.test/a", "custom/party"); recordEmojiUsage("wss://relay.test/a", "other/joy"); - await expect.poll(stored).toEqual({ - joy: 2, - [customEmojiId("wss://relay.test/a", "party")]: 1, - }); + const uses = () => emojiUsage("wss://relay.test/a"); + await expect.poll(() => uses()("custom/party")).toBe(1); + const stored = JSON.parse( + localStorage.getItem("emoji-mart.frequently") ?? "", + ); + expect(Object.keys(stored)).toEqual( + expect.arrayContaining([...FrequentlyUsed.DEFAULTS, party]), + ); + expect(uses()("unicode/joy")).toBe(0); + // A picker choice of a default and a suggestion choice add whole choices. + FrequentlyUsed.add({ id: "joy" }); + recordEmojiUsage("wss://relay.test/a", "unicode/joy"); + await expect.poll(() => uses()("unicode/joy")).toBe(2); // A later picker save rewrites Mart's cached counts, keeping both sources. FrequentlyUsed.add({ id: "joy" }); - expect(stored()).toEqual({ - joy: 3, - [customEmojiId("wss://relay.test/a", "party")]: 1, - }); + expect(uses()("unicode/joy")).toBe(3); + expect(uses()("custom/party")).toBe(1); + expect(uses()("unicode/+1")).toBe(0); }); diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index aaad1512d5..2cad680878 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -1,5 +1,6 @@ // Picker and autocomplete share Emoji Mart's usage store: its Frequently used -// row and the counts that rank colon suggestions. +// row and the counts that rank colon suggestions. Mart keeps at most the +// picker's two rows, plus the latest choice, whenever a picker opens. const STORE = "emoji-mart.frequently"; /** The picker's ID for a community emoji, scoped like its catalog. */ @@ -14,7 +15,26 @@ function usageId(scope: string, id: string) { return undefined; } -/** How often each suggestion was chosen; 0 when unknown or unreadable. */ +/** Seed Mart's default row with weights below one choice before Mart reads + * an empty store; Mart's own seed would save its defaults as whole choices. */ +export function seedEmojiUsage(defaults: readonly string[]) { + try { + const stored = localStorage.getItem(STORE); + if (stored !== null && stored !== "{}") return; + const seed = Object.fromEntries( + defaults.map((id, index) => [ + id, + (defaults.length - index) / (defaults.length + 1), + ]), + ); + localStorage.setItem(STORE, JSON.stringify(seed)); + localStorage.removeItem("emoji-mart.last"); + } catch { + /* Like Mart, selection works without localStorage. */ + } +} + +/** How many times each suggestion was chosen; 0 when unknown or unreadable. */ export function emojiUsage(scope: string): (id: string) => number { let counts: Record = {}; try { @@ -27,7 +47,10 @@ export function emojiUsage(scope: string): (id: string) => number { return (id) => { const key = usageId(scope, id); const count = key && Object.hasOwn(counts, key) ? counts[key] : 0; - return typeof count === "number" && count > 0 ? count : 0; + // Whole choices only: default seeds stay below one. + return typeof count === "number" && Number.isFinite(count) && count >= 1 + ? Math.floor(count) + : 0; }; } @@ -36,7 +59,10 @@ export function recordEmojiUsage(scope: string, id: string) { const key = usageId(scope, id); if (!key) return; void import("emoji-mart") - .then(({ FrequentlyUsed }) => FrequentlyUsed.add({ id: key })) + .then(({ FrequentlyUsed }) => { + seedEmojiUsage(FrequentlyUsed.DEFAULTS); + FrequentlyUsed.add({ id: key }); + }) .catch(() => { /* Insertion already happened; usage is best effort, like Mart's own. */ }); diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 3c1d919488..13e6cd542d 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -40,6 +40,8 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", // New users get the query order. await input.fill(":sm"); await expect(choices.first()).toHaveText(/:smile:/); + await input.fill(":hate"); + await expect(choices.first()).toHaveText(/:rage:/); await input.fill(":party-p"); await expect.poll(labels).toEqual([":party-parrot:", ":party-parrot-wave:"]); // Highlighting a suggestion is not choosing it. @@ -62,6 +64,15 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await expect(choices.first()).toHaveText(/:smirk:/); await input.press("Tab"); await expect(input).toHaveJSProperty("value", "😏 "); + // The closing colon chooses the exact name too. + await input.fill(":smirk"); + await expect(choices.first()).toHaveText(/:smirk:/); + await input.press(":"); + await expect(input).toHaveJSProperty("value", "😏 "); + // The picker's default row is not usage: never-chosen 😍 stays behind + // the keyword match for `hate`. + await input.fill(":hate"); + await expect(choices.first()).toHaveText(/:rage:/); // A keyboard suggestion choice of a community emoji teaches suggestions and // the picker's Frequently used row, once. @@ -78,10 +89,12 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", page.evaluate(() => JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), ); - expect(await counts()).toMatchObject({ - smirk: 2, + const stored = await counts(); + expect(stored).toMatchObject({ + smirk: 3, "buzz-custom/a/party-parrot-wave": 1, }); + expect(stored.heart_eyes).toBeLessThan(1); await openFrequent(); await expect(frequent.locator('img[src*="wave.png"]')).toHaveCount(1); await expect(frequent.and(page.locator('[aria-label="😏"]'))).toHaveCount(1); From 430df28de19bdeb63910072c38952a8941cb1d26 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Fri, 20 Nov 2026 15:49:55 -0800 Subject: [PATCH 03/16] fix(emoji): seed one default row and treat malformed stores as empty the default row seed is one picker row wide, as emoji mart seeds it. a first suggestion choice, which has no picker width, seeds the widest picker row. stores emoji mart cannot read as counts are seeded as empty. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-mart.ts | 2 +- src/bundled/emoji/emoji-usage.test.ts | 36 +++++++++++----------- src/bundled/emoji/emoji-usage.ts | 30 ++++++++++++------- tests/browser/emoji-frequency.spec.mjs | 41 +++++++++++++++++++++++--- 4 files changed, 77 insertions(+), 32 deletions(-) diff --git a/src/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index 299bb02ac6..fd7a916efd 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -146,7 +146,7 @@ export function mountEmojiMart({ ]; }); // Also restores the default row if storage contains a poisoned empty map. - seedEmojiUsage(FrequentlyUsed.DEFAULTS); + seedEmojiUsage(FrequentlyUsed.DEFAULTS, perLine); const picker = new Picker({ data, custom: emojis.length diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index b4f4ae6f75..b2329e5a30 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -35,22 +35,23 @@ it("reads whole choices from the picker's counts for Unicode and community sugge expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); -it("seeds the default row below one choice, only into an empty store", () => { - seedEmojiUsage(["+1", "grinning"]); - const seeded = JSON.parse( - localStorage.getItem("emoji-mart.frequently") ?? "", - ); - expect(seeded["+1"]).toBeGreaterThan(seeded.grinning); - expect(seeded["+1"]).toBeLessThan(1); - expect(emojiUsage("s")("unicode/+1")).toBe(0); - localStorage.setItem("emoji-mart.frequently", '{"smile":1}'); - seedEmojiUsage(["+1"]); - expect(localStorage.getItem("emoji-mart.frequently")).toBe('{"smile":1}'); - // A poisoned empty map gets the default row back. - localStorage.setItem("emoji-mart.frequently", "{}"); - seedEmojiUsage(["+1"]); +it("seeds one default row below one choice, only into a store Mart treats as empty", () => { + const stored = () => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? ""); + seedEmojiUsage(["+1", "grinning", "kissing_heart"], 2); + expect(Object.keys(stored())).toEqual(["+1", "grinning"]); + expect(stored()["+1"]).toBeGreaterThan(stored().grinning); + expect(stored()["+1"]).toBeLessThan(1); expect(emojiUsage("s")("unicode/+1")).toBe(0); - expect(localStorage.getItem("emoji-mart.frequently")).not.toBe("{}"); + localStorage.setItem("emoji-mart.frequently", JSON.stringify({ smile: 1 })); + seedEmojiUsage(["+1"], 1); + expect(stored()).toEqual({ smile: 1 }); + // Empty and malformed stores get the default row back. + for (const value of ["{}", "[]", "null", "", "0", "false", "garbage"]) { + localStorage.setItem("emoji-mart.frequently", value); + seedEmojiUsage(["+1"], 1); + expect(Object.keys(stored())).toEqual(["+1"]); + } }); // Mart caches its counts for the module's lifetime, so this runs as one story. @@ -63,8 +64,9 @@ it("records through Mart so picker and suggestion choices share one seeded histo const stored = JSON.parse( localStorage.getItem("emoji-mart.frequently") ?? "", ); - expect(Object.keys(stored)).toEqual( - expect.arrayContaining([...FrequentlyUsed.DEFAULTS, party]), + // Without a picker width, the seed is the widest picker row. + expect(Object.keys(stored).sort()).toEqual( + [...FrequentlyUsed.DEFAULTS.slice(0, 8), party].sort(), ); expect(uses()("unicode/joy")).toBe(0); // A picker choice of a default and a suggestion choice add whole choices. diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index 2cad680878..5b5289e6f7 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -2,6 +2,8 @@ // row and the counts that rank colon suggestions. Mart keeps at most the // picker's two rows, plus the latest choice, whenever a picker opens. const STORE = "emoji-mart.frequently"; +/** The composer picker's most columns. */ +const WIDEST_ROW = 8; /** The picker's ID for a community emoji, scoped like its catalog. */ export const customEmojiId = (scope: string, shortcode: string) => @@ -15,17 +17,15 @@ function usageId(scope: string, id: string) { return undefined; } -/** Seed Mart's default row with weights below one choice before Mart reads - * an empty store; Mart's own seed would save its defaults as whole choices. */ -export function seedEmojiUsage(defaults: readonly string[]) { +/** Seed Mart's one default row, `perLine` wide, with weights below one choice + * before Mart reads a store it treats as empty; Mart's own seed would save its + * defaults as whole choices. */ +export function seedEmojiUsage(defaults: readonly string[], perLine: number) { try { - const stored = localStorage.getItem(STORE); - if (stored !== null && stored !== "{}") return; + if (!emptyStore(localStorage.getItem(STORE))) return; + const row = defaults.slice(0, perLine); const seed = Object.fromEntries( - defaults.map((id, index) => [ - id, - (defaults.length - index) / (defaults.length + 1), - ]), + row.map((id, index) => [id, (row.length - index) / (row.length + 1)]), ); localStorage.setItem(STORE, JSON.stringify(seed)); localStorage.removeItem("emoji-mart.last"); @@ -34,6 +34,15 @@ export function seedEmojiUsage(defaults: readonly string[]) { } } +function emptyStore(stored: string | null) { + try { + const counts: unknown = JSON.parse(stored || "null"); + return !counts || typeof counts !== "object" || !Object.keys(counts).length; + } catch { + return true; + } +} + /** How many times each suggestion was chosen; 0 when unknown or unreadable. */ export function emojiUsage(scope: string): (id: string) => number { let counts: Record = {}; @@ -60,7 +69,8 @@ export function recordEmojiUsage(scope: string, id: string) { if (!key) return; void import("emoji-mart") .then(({ FrequentlyUsed }) => { - seedEmojiUsage(FrequentlyUsed.DEFAULTS); + // Without a picker width, seed the widest picker row. + seedEmojiUsage(FrequentlyUsed.DEFAULTS, WIDEST_ROW); FrequentlyUsed.add({ id: key }); }) .catch(() => { diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 13e6cd542d..270d809234 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -32,6 +32,10 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await search.fill(""); await expect(frequent.first()).toBeVisible(); }; + const counts = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ); const closePicker = async () => { await page.keyboard.press("Escape"); await expect(search).toHaveCount(0); @@ -54,6 +58,8 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", // A picker choice ranks first among its prefix matches. await input.fill(""); await openPicker(); + // A fresh picker shows one row of defaults, as Emoji Mart seeds it. + await expect(frequent).toHaveCount(8); await search.fill("smirk"); await expect( page.locator('em-emoji-picker .category button[aria-label="😏"]').first(), @@ -81,14 +87,14 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await input.press("ArrowDown"); await input.press("Enter"); await expect(input).toHaveJSProperty("value", ":party-parrot-wave: "); + // Recording finishes once Emoji Mart's module resolves. + await expect.poll(counts).toMatchObject({ + "buzz-custom/a/party-parrot-wave": 1, + }); await input.fill(":party-p"); await expect.poll(labels).toEqual([":party-parrot-wave:", ":party-parrot:"]); await input.press("Escape"); await input.fill(""); - const counts = () => - page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), - ); const stored = await counts(); expect(stored).toMatchObject({ smirk: 3, @@ -112,3 +118,30 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await closePicker(); expect(errors.unexplained()).toEqual([]); }); + +test("a first suggestion choice in a narrow window seeds at most one wide row", async ({ + page, +}) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.goto("/tests/fixtures/emoji.html"); + const input = page.getByRole("textbox", { name: "Message #general" }); + await input.fill(":smirk"); + await expect(page.getByRole("option").first()).toHaveText(/:smirk:/); + await input.press(":"); + await expect(input).toHaveJSProperty("value", "😏 "); + await expect + .poll(() => + page.evaluate(() => localStorage.getItem("emoji-mart.frequently")), + ) + .toContain("smirk"); + await page + .getByRole("button", { name: "Emoji and GIFS", exact: true }) + .click(); + const frequent = page.locator( + 'em-emoji-picker .category[data-id="frequent"] button', + ); + await expect(frequent.first()).toBeVisible(); + // Without the picker width, the choice joins the widest row of defaults, + // which wraps here: no more than that. + await expect(frequent).toHaveCount(9); +}); From 2e5eef7e57bccd9e5f084b05f927cdc6ea007677 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Fri, 20 Nov 2026 16:01:00 -0800 Subject: [PATCH 04/16] fix(emoji): widen a seeded default row and reseed array stores a store holding only defaults seeded for a narrower picker row is reseeded at the wider width, as emoji mart regrows its in-memory defaults. array stores are treated as empty. the picker's maximum row width is one shared constant. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiPicker.tsx | 3 +-- src/bundled/emoji/emoji-usage.test.ts | 26 ++++++++++++++++-- src/bundled/emoji/emoji-usage.ts | 23 ++++++++++------ src/bundled/emoji/picker-layout.ts | 2 ++ tests/browser/emoji-frequency.spec.mjs | 37 ++++++++++++-------------- 5 files changed, 59 insertions(+), 32 deletions(-) diff --git a/src/bundled/emoji/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 54ef7e00c9..3c773517da 100644 --- a/src/bundled/emoji/EmojiPicker.tsx +++ b/src/bundled/emoji/EmojiPicker.tsx @@ -38,7 +38,7 @@ import { GifPicker } from "./GifPicker"; import type { EmojiSearchSelection } from "./emoji-mart"; import { PREVIEW_ACTION_SLOT, type AddEmoji } from "./add-emoji"; import { SKIN_TONE_SLOT, defaultSkinTone, toneHand } from "./skin-tone"; -import { rootFontSize, spaciousGrid } from "./picker-layout"; +import { MAX_PER_LINE, rootFontSize, spaciousGrid } from "./picker-layout"; const NO_ADD_EMOJI = { snapshot: () => undefined, subscribe: () => () => {}, @@ -48,7 +48,6 @@ const NO_ADD_EMOJI = { // text-size preferences scale them. Fallbacks are their 1rem values. const EMOJI_SIZE = "--size-emoji-picker"; const EMOJI_SLOT = "--size-control"; -const MAX_PER_LINE = 8; const PICKER_COLUMN_CHROME = 44; // Two balanced scrollbar lanes plus the gaps between fixed-size slots. const PICKER_CHROME = 72; diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index b2329e5a30..9c32bef3a1 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -35,7 +35,7 @@ it("reads whole choices from the picker's counts for Unicode and community sugge expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); -it("seeds one default row below one choice, only into a store Mart treats as empty", () => { +it("seeds one default row below one choice, only into a store without choices", () => { const stored = () => JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? ""); seedEmojiUsage(["+1", "grinning", "kissing_heart"], 2); @@ -46,8 +46,30 @@ it("seeds one default row below one choice, only into a store Mart treats as emp localStorage.setItem("emoji-mart.frequently", JSON.stringify({ smile: 1 })); seedEmojiUsage(["+1"], 1); expect(stored()).toEqual({ smile: 1 }); + // A wider picker widens a seeded row, never a row with choices. + localStorage.clear(); + seedEmojiUsage(["+1", "grinning"], 1); + seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); + expect(Object.keys(stored())).toEqual(["+1", "grinning", "kissing_heart"]); + seedEmojiUsage(["+1"], 1); + expect(Object.keys(stored())).toHaveLength(3); + localStorage.setItem( + "emoji-mart.frequently", + JSON.stringify({ smile: 1, "+1": 0.5 }), + ); + seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); + expect(stored()).toEqual({ smile: 1, "+1": 0.5 }); // Empty and malformed stores get the default row back. - for (const value of ["{}", "[]", "null", "", "0", "false", "garbage"]) { + for (const value of [ + "{}", + "[]", + "[1,2]", + "null", + "", + "0", + "false", + "garbage", + ]) { localStorage.setItem("emoji-mart.frequently", value); seedEmojiUsage(["+1"], 1); expect(Object.keys(stored())).toEqual(["+1"]); diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index 5b5289e6f7..d61b318e75 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -1,9 +1,9 @@ // Picker and autocomplete share Emoji Mart's usage store: its Frequently used // row and the counts that rank colon suggestions. Mart keeps at most the // picker's two rows, plus the latest choice, whenever a picker opens. +import { MAX_PER_LINE } from "./picker-layout"; + const STORE = "emoji-mart.frequently"; -/** The composer picker's most columns. */ -const WIDEST_ROW = 8; /** The picker's ID for a community emoji, scoped like its catalog. */ export const customEmojiId = (scope: string, shortcode: string) => @@ -18,11 +18,11 @@ function usageId(scope: string, id: string) { } /** Seed Mart's one default row, `perLine` wide, with weights below one choice - * before Mart reads a store it treats as empty; Mart's own seed would save its - * defaults as whole choices. */ + * before Mart reads a store without choices; Mart's own seed would save its + * defaults as whole choices. A wider picker widens a narrower seeded row. */ export function seedEmojiUsage(defaults: readonly string[], perLine: number) { try { - if (!emptyStore(localStorage.getItem(STORE))) return; + if (!unchosen(localStorage.getItem(STORE), perLine)) return; const row = defaults.slice(0, perLine); const seed = Object.fromEntries( row.map((id, index) => [id, (row.length - index) / (row.length + 1)]), @@ -34,10 +34,17 @@ export function seedEmojiUsage(defaults: readonly string[], perLine: number) { } } -function emptyStore(stored: string | null) { +/** Unreadable, or only defaults seeded for a narrower row. */ +function unchosen(stored: string | null, perLine: number) { try { const counts: unknown = JSON.parse(stored || "null"); - return !counts || typeof counts !== "object" || !Object.keys(counts).length; + if (!counts || typeof counts !== "object" || Array.isArray(counts)) + return true; + const weights = Object.values(counts); + return ( + weights.length < perLine && + weights.every((weight) => typeof weight === "number" && weight < 1) + ); } catch { return true; } @@ -70,7 +77,7 @@ export function recordEmojiUsage(scope: string, id: string) { void import("emoji-mart") .then(({ FrequentlyUsed }) => { // Without a picker width, seed the widest picker row. - seedEmojiUsage(FrequentlyUsed.DEFAULTS, WIDEST_ROW); + seedEmojiUsage(FrequentlyUsed.DEFAULTS, MAX_PER_LINE); FrequentlyUsed.add({ id: key }); }) .catch(() => { diff --git a/src/bundled/emoji/picker-layout.ts b/src/bundled/emoji/picker-layout.ts index d2be3e2d59..26df0ecd28 100644 --- a/src/bundled/emoji/picker-layout.ts +++ b/src/bundled/emoji/picker-layout.ts @@ -1,6 +1,8 @@ /** Below this grid width (in rem) the category bar and labelled actions do * not fit, so the picker drops the bar and shows Add emoji as an icon. */ const SPACIOUS_GRID_REM = 18; +/** The composer picker's most columns. */ +export const MAX_PER_LINE = 8; export const spaciousGrid = (gridWidth: number, rootFontSize: number) => gridWidth >= SPACIOUS_GRID_REM * rootFontSize; diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 270d809234..3d2dc3d008 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -119,29 +119,26 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", expect(errors.unexplained()).toEqual([]); }); -test("a first suggestion choice in a narrow window seeds at most one wide row", async ({ +test("a default row first seen in a narrow window fills a wider picker later", async ({ page, }) => { - await page.setViewportSize({ width: 390, height: 844 }); - await page.goto("/tests/fixtures/emoji.html"); - const input = page.getByRole("textbox", { name: "Message #general" }); - await input.fill(":smirk"); - await expect(page.getByRole("option").first()).toHaveText(/:smirk:/); - await input.press(":"); - await expect(input).toHaveJSProperty("value", "😏 "); - await expect - .poll(() => - page.evaluate(() => localStorage.getItem("emoji-mart.frequently")), - ) - .toContain("smirk"); - await page - .getByRole("button", { name: "Emoji and GIFS", exact: true }) - .click(); + const errors = watchPageErrors(page); const frequent = page.locator( 'em-emoji-picker .category[data-id="frequent"] button', ); - await expect(frequent.first()).toBeVisible(); - // Without the picker width, the choice joins the widest row of defaults, - // which wraps here: no more than that. - await expect(frequent).toHaveCount(9); + const openPicker = async () => { + await page + .getByRole("button", { name: "Emoji and GIFS", exact: true }) + .click(); + await expect(frequent.first()).toBeVisible(); + }; + await page.setViewportSize({ width: 240, height: 844 }); + await page.goto("/tests/fixtures/emoji.html"); + await openPicker(); + await expect(frequent).toHaveCount(4); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.reload(); + await openPicker(); + await expect(frequent).toHaveCount(8); + expect(errors.unexplained()).toEqual([]); }); From 0462146f1698ab1d0073116cd0c2ad42626f5277 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Fri, 20 Nov 2026 16:08:56 -0800 Subject: [PATCH 05/16] fix(emoji): reseed a seeded default row at any other picker width a store holding only defaults is reseeded when its row differs from the picker width, so a narrower picker shows one row like emoji mart. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-usage.test.ts | 10 +++++++--- src/bundled/emoji/emoji-usage.ts | 10 +++++----- tests/browser/emoji-frequency.spec.mjs | 6 +++++- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 9c32bef3a1..367d73dded 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -46,13 +46,17 @@ it("seeds one default row below one choice, only into a store without choices", localStorage.setItem("emoji-mart.frequently", JSON.stringify({ smile: 1 })); seedEmojiUsage(["+1"], 1); expect(stored()).toEqual({ smile: 1 }); - // A wider picker widens a seeded row, never a row with choices. + // A seeded row follows the picker's width; a row with choices never does. localStorage.clear(); seedEmojiUsage(["+1", "grinning"], 1); seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); expect(Object.keys(stored())).toEqual(["+1", "grinning", "kissing_heart"]); - seedEmojiUsage(["+1"], 1); - expect(Object.keys(stored())).toHaveLength(3); + seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); + expect(localStorage.getItem("emoji-mart.frequently")).toBe( + JSON.stringify({ "+1": 0.75, grinning: 0.5, kissing_heart: 0.25 }), + ); + seedEmojiUsage(["+1", "grinning"], 1); + expect(Object.keys(stored())).toEqual(["+1"]); localStorage.setItem( "emoji-mart.frequently", JSON.stringify({ smile: 1, "+1": 0.5 }), diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index d61b318e75..3f03c0983e 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -19,11 +19,11 @@ function usageId(scope: string, id: string) { /** Seed Mart's one default row, `perLine` wide, with weights below one choice * before Mart reads a store without choices; Mart's own seed would save its - * defaults as whole choices. A wider picker widens a narrower seeded row. */ + * defaults as whole choices. A seeded row follows the picker's width. */ export function seedEmojiUsage(defaults: readonly string[], perLine: number) { try { - if (!unchosen(localStorage.getItem(STORE), perLine)) return; const row = defaults.slice(0, perLine); + if (!unchosen(localStorage.getItem(STORE), row.length)) return; const seed = Object.fromEntries( row.map((id, index) => [id, (row.length - index) / (row.length + 1)]), ); @@ -34,15 +34,15 @@ export function seedEmojiUsage(defaults: readonly string[], perLine: number) { } } -/** Unreadable, or only defaults seeded for a narrower row. */ -function unchosen(stored: string | null, perLine: number) { +/** Unreadable, or only defaults seeded for another row width. */ +function unchosen(stored: string | null, width: number) { try { const counts: unknown = JSON.parse(stored || "null"); if (!counts || typeof counts !== "object" || Array.isArray(counts)) return true; const weights = Object.values(counts); return ( - weights.length < perLine && + weights.length !== width && weights.every((weight) => typeof weight === "number" && weight < 1) ); } catch { diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 3d2dc3d008..a2c64b031a 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -119,7 +119,7 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", expect(errors.unexplained()).toEqual([]); }); -test("a default row first seen in a narrow window fills a wider picker later", async ({ +test("the default row follows the picker's width across reloads", async ({ page, }) => { const errors = watchPageErrors(page); @@ -140,5 +140,9 @@ test("a default row first seen in a narrow window fills a wider picker later", a await page.reload(); await openPicker(); await expect(frequent).toHaveCount(8); + await page.setViewportSize({ width: 240, height: 844 }); + await page.reload(); + await openPicker(); + await expect(frequent).toHaveCount(4); expect(errors.unexplained()).toEqual([]); }); From 643c236a7026412324f3c331129af24263e2c550 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Sun, 22 Nov 2026 08:41:16 -0800 Subject: [PATCH 06/16] fix(emoji): own usage history so windows and tone prompts count correctly emoji mart caches usage history per window and saves that copy whole, so a choice in one window dropped choices made in another. its picker also counted an emoji before the first-pick tone prompt was confirmed. buzz now replaces mart's frequently used add and get. history is read from storage on every use, a choice counts when buzz inserts it, and the frequently used row fills an unused first row with mart's defaults without storing them. this removes the fractional default seeding. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiPicker.tsx | 3 +- src/bundled/emoji/emoji-mart.ts | 23 +++-- src/bundled/emoji/emoji-usage.test.ts | 113 +++++++++++------------- src/bundled/emoji/emoji-usage.ts | 115 +++++++++++++------------ src/bundled/emoji/picker-layout.ts | 2 - tests/browser/emoji-frequency.spec.mjs | 41 +++++++-- tests/browser/emoji.spec.mjs | 7 ++ 7 files changed, 172 insertions(+), 132 deletions(-) diff --git a/src/bundled/emoji/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 3c773517da..54ef7e00c9 100644 --- a/src/bundled/emoji/EmojiPicker.tsx +++ b/src/bundled/emoji/EmojiPicker.tsx @@ -38,7 +38,7 @@ import { GifPicker } from "./GifPicker"; import type { EmojiSearchSelection } from "./emoji-mart"; import { PREVIEW_ACTION_SLOT, type AddEmoji } from "./add-emoji"; import { SKIN_TONE_SLOT, defaultSkinTone, toneHand } from "./skin-tone"; -import { MAX_PER_LINE, rootFontSize, spaciousGrid } from "./picker-layout"; +import { rootFontSize, spaciousGrid } from "./picker-layout"; const NO_ADD_EMOJI = { snapshot: () => undefined, subscribe: () => () => {}, @@ -48,6 +48,7 @@ const NO_ADD_EMOJI = { // text-size preferences scale them. Fallbacks are their 1rem values. const EMOJI_SIZE = "--size-emoji-picker"; const EMOJI_SLOT = "--size-control"; +const MAX_PER_LINE = 8; const PICKER_COLUMN_CHROME = 44; // Two balanced scrollbar lanes plus the gaps between fixed-size slots. const PICKER_CHROME = 72; diff --git a/src/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index fd7a916efd..3f5f5d423a 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -8,7 +8,7 @@ import english from "@emoji-mart/data/i18n/en.json"; import { Data, FrequentlyUsed, Picker, SearchIndex } from "emoji-mart"; import type { CustomEmoji } from "../../features/relay/emoji"; import { rankShortcodes } from "./emoji-search"; -import { customEmojiId, seedEmojiUsage } from "./emoji-usage"; +import { addEmojiUsage, customEmojiId, frequentEmoji } from "./emoji-usage"; import { PREVIEW_ACTION_SLOT } from "./add-emoji"; import { SKIN_TONE_SLOT, @@ -33,6 +33,13 @@ 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 }) => + frequentEmoji(props, FrequentlyUsed.DEFAULTS, (id) => !!Data?.emojis[id]), +}); const resolvedTheme = (value: unknown): "light" | "dark" => value === "dark" ? "dark" : "light"; @@ -145,8 +152,6 @@ export function mountEmojiMart({ }, ]; }); - // Also restores the default row if storage contains a poisoned empty map. - seedEmojiUsage(FrequentlyUsed.DEFAULTS, perLine); const picker = new Picker({ data, custom: emojis.length @@ -183,12 +188,17 @@ 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; + addEmojiUsage(emoji.id); + select(emoji.native); return; } - const custom = values.get(emoji.id ?? ""); - if (custom) select(custom.literal, custom.shortcode); + const custom = values.get(emoji.id); + if (!custom) return; + addEmojiUsage(emoji.id); + select(custom.literal, custom.shortcode); }, }) as unknown as HTMLElement; // The documented web-component attribute updates in place: do not recreate the @@ -669,6 +679,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; + addEmojiUsage(id); select(native); return true; }; diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 367d73dded..638394fdd9 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -1,14 +1,19 @@ // @vitest-environment jsdom -import { FrequentlyUsed } from "emoji-mart"; +import data from "@emoji-mart/data"; +import { FrequentlyUsed, init } from "emoji-mart"; import { afterEach, expect, it } from "vitest"; +import "./emoji-mart"; import { + addEmojiUsage, customEmojiId, emojiUsage, + frequentEmoji, recordEmojiUsage, - seedEmojiUsage, } from "./emoji-usage"; const party = customEmojiId("wss://relay.test/a", "party"); +const stored = () => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "null"); afterEach(() => localStorage.clear()); it("reads whole choices from the picker's counts for Unicode and community suggestions", () => { @@ -35,73 +40,55 @@ it("reads whole choices from the picker's counts for Unicode and community sugge expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); -it("seeds one default row below one choice, only into a store without choices", () => { - const stored = () => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? ""); - seedEmojiUsage(["+1", "grinning", "kissing_heart"], 2); - expect(Object.keys(stored())).toEqual(["+1", "grinning"]); - expect(stored()["+1"]).toBeGreaterThan(stored().grinning); - expect(stored()["+1"]).toBeLessThan(1); - expect(emojiUsage("s")("unicode/+1")).toBe(0); - localStorage.setItem("emoji-mart.frequently", JSON.stringify({ smile: 1 })); - seedEmojiUsage(["+1"], 1); - expect(stored()).toEqual({ smile: 1 }); - // A seeded row follows the picker's width; a row with choices never does. - localStorage.clear(); - seedEmojiUsage(["+1", "grinning"], 1); - seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); - expect(Object.keys(stored())).toEqual(["+1", "grinning", "kissing_heart"]); - seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); - expect(localStorage.getItem("emoji-mart.frequently")).toBe( - JSON.stringify({ "+1": 0.75, grinning: 0.5, kissing_heart: 0.25 }), - ); - seedEmojiUsage(["+1", "grinning"], 1); - expect(Object.keys(stored())).toEqual(["+1"]); +it("counts each choice against the latest history, keeping other windows' choices", () => { + recordEmojiUsage("wss://relay.test/a", "unicode/smirk"); + // Another window chooses from the same storage. localStorage.setItem( "emoji-mart.frequently", - JSON.stringify({ smile: 1, "+1": 0.5 }), + JSON.stringify({ ...stored(), rocket: 1 }), ); - seedEmojiUsage(["+1", "grinning", "kissing_heart"], 3); - expect(stored()).toEqual({ smile: 1, "+1": 0.5 }); - // Empty and malformed stores get the default row back. - for (const value of [ - "{}", - "[]", - "[1,2]", - "null", - "", - "0", - "false", - "garbage", - ]) { + recordEmojiUsage("wss://relay.test/a", "custom/party"); + addEmojiUsage("smirk"); + recordEmojiUsage("wss://relay.test/a", "other/joy"); + expect(stored()).toEqual({ smirk: 2, rocket: 1, [party]: 1 }); + expect(localStorage.getItem("emoji-mart.last")).toBe('"smirk"'); + // Unreadable history starts over rather than blocking choices. + for (const value of ["[1,2]", "null", "garbage"]) { localStorage.setItem("emoji-mart.frequently", value); - seedEmojiUsage(["+1"], 1); - expect(Object.keys(stored())).toEqual(["+1"]); + addEmojiUsage("smirk"); + expect(stored()).toEqual({ smirk: 1 }); } }); -// Mart caches its counts for the module's lifetime, so this runs as one story. -it("records through Mart so picker and suggestion choices share one seeded history", async () => { - // The first choice, from suggestions, still seeds Mart's default row. - recordEmojiUsage("wss://relay.test/a", "custom/party"); - recordEmojiUsage("wss://relay.test/a", "other/joy"); - const uses = () => emojiUsage("wss://relay.test/a"); - await expect.poll(() => uses()("custom/party")).toBe(1); - const stored = JSON.parse( - localStorage.getItem("emoji-mart.frequently") ?? "", - ); - // Without a picker width, the seed is the widest picker row. - expect(Object.keys(stored).sort()).toEqual( - [...FrequentlyUsed.DEFAULTS.slice(0, 8), party].sort(), +it("orders the Frequently used row like Mart, filling a first row with defaults", () => { + const shown = (id: string) => id !== "hidden"; + const row = (perLine: number, maxFrequentRows = 2) => + frequentEmoji( + { maxFrequentRows, perLine }, + ["+1", "grinning", "joy"], + shown, + ); + expect(row(2)).toEqual(["+1", "grinning"]); + expect(row(2, 0)).toEqual([]); + localStorage.setItem( + "emoji-mart.frequently", + JSON.stringify({ b: 2, a: 2, c: 5, hidden: 9, seeded: 0.5, joy: 1 }), ); - expect(uses()("unicode/joy")).toBe(0); - // A picker choice of a default and a suggestion choice add whole choices. - FrequentlyUsed.add({ id: "joy" }); - recordEmojiUsage("wss://relay.test/a", "unicode/joy"); - await expect.poll(() => uses()("unicode/joy")).toBe(2); - // A later picker save rewrites Mart's cached counts, keeping both sources. - FrequentlyUsed.add({ id: "joy" }); - expect(uses()("unicode/joy")).toBe(3); - expect(uses()("custom/party")).toBe(1); - expect(uses()("unicode/+1")).toBe(0); + // Ties sort by ID; unshown and unchosen entries are skipped. + expect(row(4)).toEqual(["c", "a", "b", "joy"]); + expect(row(5)).toEqual(["c", "a", "b", "joy", "+1"]); + // The latest choice stays in a full row. + localStorage.setItem("emoji-mart.last", '"joy"'); + expect(row(1)).toEqual(["c", "joy"]); +}); + +it("keeps Mart's pickers on the shared history", async () => { + await init({ data }); + FrequentlyUsed.add({ id: "smirk" }); + expect(stored()).toBeNull(); + addEmojiUsage("smirk"); + const mart = FrequentlyUsed as unknown as { + get(props: { maxFrequentRows: number; perLine: number }): string[]; + }; + expect(mart.get({ maxFrequentRows: 1, perLine: 2 })).toEqual(["smirk", "+1"]); }); diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index 3f03c0983e..4eac4dc489 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -1,9 +1,8 @@ -// Picker and autocomplete share Emoji Mart's usage store: its Frequently used -// row and the counts that rank colon suggestions. Mart keeps at most the -// picker's two rows, plus the latest choice, whenever a picker opens. -import { MAX_PER_LINE } from "./picker-layout"; - +// Picker and autocomplete share one usage history under Emoji Mart's storage +// key: it fills the picker's Frequently used row and ranks colon suggestions. +// It is read fresh on every use, so each window keeps the others' choices. const STORE = "emoji-mart.frequently"; +const LAST = "emoji-mart.last"; /** The picker's ID for a community emoji, scoped like its catalog. */ export const customEmojiId = (scope: string, shortcode: string) => @@ -17,70 +16,76 @@ function usageId(scope: string, id: string) { return undefined; } -/** Seed Mart's one default row, `perLine` wide, with weights below one choice - * before Mart reads a store without choices; Mart's own seed would save its - * defaults as whole choices. A seeded row follows the picker's width. */ -export function seedEmojiUsage(defaults: readonly string[], perLine: number) { +function readCounts(): Record { try { - const row = defaults.slice(0, perLine); - if (!unchosen(localStorage.getItem(STORE), row.length)) return; - const seed = Object.fromEntries( - row.map((id, index) => [id, (row.length - index) / (row.length + 1)]), - ); - localStorage.setItem(STORE, JSON.stringify(seed)); - localStorage.removeItem("emoji-mart.last"); + const stored: unknown = JSON.parse(localStorage.getItem(STORE) ?? "{}"); + if (stored && typeof stored === "object" && !Array.isArray(stored)) + return stored as Record; } catch { - /* Like Mart, selection works without localStorage. */ + /* Without storage, nothing has been chosen. */ } + return {}; } -/** Unreadable, or only defaults seeded for another row width. */ -function unchosen(stored: string | null, width: number) { - try { - const counts: unknown = JSON.parse(stored || "null"); - if (!counts || typeof counts !== "object" || Array.isArray(counts)) - return true; - const weights = Object.values(counts); - return ( - weights.length !== width && - weights.every((weight) => typeof weight === "number" && weight < 1) - ); - } catch { - return true; - } +function uses(counts: Record, key: string) { + const count = Object.hasOwn(counts, key) ? counts[key] : 0; + return typeof count === "number" && Number.isFinite(count) && count >= 1 + ? Math.floor(count) + : 0; } /** How many times each suggestion was chosen; 0 when unknown or unreadable. */ export function emojiUsage(scope: string): (id: string) => number { - let counts: Record = {}; - try { - const stored: unknown = JSON.parse(localStorage.getItem(STORE) ?? "{}"); - if (stored && typeof stored === "object") - counts = stored as Record; - } catch { - /* Without storage, suggestions keep their query order. */ - } + const counts = readCounts(); return (id) => { const key = usageId(scope, id); - const count = key && Object.hasOwn(counts, key) ? counts[key] : 0; - // Whole choices only: default seeds stay below one. - return typeof count === "number" && Number.isFinite(count) && count >= 1 - ? Math.floor(count) - : 0; + return key ? uses(counts, key) : 0; }; } -/** Record through Mart itself: it caches the counts and rewrites them whole. */ +/** Count one inserted emoji by its picker ID. */ +export function addEmojiUsage(key: string) { + try { + const counts = readCounts(); + counts[key] = uses(counts, key) + 1; + localStorage.setItem(STORE, JSON.stringify(counts)); + localStorage.setItem(LAST, JSON.stringify(key)); + } catch { + /* Insertion already happened; usage is best effort, like Mart's own. */ + } +} + +/** Count one inserted suggestion. */ export function recordEmojiUsage(scope: string, id: string) { const key = usageId(scope, id); - if (!key) return; - void import("emoji-mart") - .then(({ FrequentlyUsed }) => { - // Without a picker width, seed the widest picker row. - seedEmojiUsage(FrequentlyUsed.DEFAULTS, MAX_PER_LINE); - FrequentlyUsed.add({ id: key }); - }) - .catch(() => { - /* Insertion already happened; usage is best effort, like Mart's own. */ - }); + if (key) addEmojiUsage(key); +} + +/** The Frequently used row, as Mart orders it: most chosen first, the latest + * choice always shown, and Mart's defaults filling the rest of a first row. */ +export function frequentEmoji( + { maxFrequentRows, perLine }: { maxFrequentRows: number; perLine: number }, + defaults: readonly string[], + shown: (id: string) => boolean, +) { + if (!maxFrequentRows) return []; + const counts = readCounts(); + const max = maxFrequentRows * perLine; + const ids = Object.keys(counts) + .filter((id) => uses(counts, id) && shown(id)) + .sort((a, b) => uses(counts, b) - uses(counts, a) || a.localeCompare(b)); + let last: unknown; + try { + last = JSON.parse(localStorage.getItem(LAST) ?? "null"); + } catch { + /* No latest choice to keep. */ + } + const row = ids.slice(0, max); + if (typeof last === "string" && ids.indexOf(last) >= max) + row.splice(-1, 1, last); + for (const id of defaults) { + if (row.length >= perLine) break; + if (!row.includes(id) && shown(id)) row.push(id); + } + return row; } diff --git a/src/bundled/emoji/picker-layout.ts b/src/bundled/emoji/picker-layout.ts index 26df0ecd28..d2be3e2d59 100644 --- a/src/bundled/emoji/picker-layout.ts +++ b/src/bundled/emoji/picker-layout.ts @@ -1,8 +1,6 @@ /** Below this grid width (in rem) the category bar and labelled actions do * not fit, so the picker drops the bar and shows Add emoji as an icon. */ const SPACIOUS_GRID_REM = 18; -/** The composer picker's most columns. */ -export const MAX_PER_LINE = 8; export const spaciousGrid = (gridWidth: number, rootFontSize: number) => gridWidth >= SPACIOUS_GRID_REM * rootFontSize; diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index a2c64b031a..6434860e2c 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -87,10 +87,6 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await input.press("ArrowDown"); await input.press("Enter"); await expect(input).toHaveJSProperty("value", ":party-parrot-wave: "); - // Recording finishes once Emoji Mart's module resolves. - await expect.poll(counts).toMatchObject({ - "buzz-custom/a/party-parrot-wave": 1, - }); await input.fill(":party-p"); await expect.poll(labels).toEqual([":party-parrot-wave:", ":party-parrot:"]); await input.press("Escape"); @@ -100,7 +96,7 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", smirk: 3, "buzz-custom/a/party-parrot-wave": 1, }); - expect(stored.heart_eyes).toBeLessThan(1); + expect(stored.heart_eyes).toBeUndefined(); await openFrequent(); await expect(frequent.locator('img[src*="wave.png"]')).toHaveCount(1); await expect(frequent.and(page.locator('[aria-label="😏"]'))).toHaveCount(1); @@ -146,3 +142,38 @@ test("the default row follows the picker's width across reloads", async ({ await expect(frequent).toHaveCount(4); expect(errors.unexplained()).toEqual([]); }); + +test("choices in two windows of one profile keep each other", async ({ + page, + context, +}) => { + const other = await context.newPage(); + const errors = [watchPageErrors(page), watchPageErrors(other)]; + const choose = async (window, query, label, value) => { + const input = window.getByRole("textbox", { name: "Message #general" }); + await input.fill(query); + await expect(window.getByRole("option").first()).toHaveText(label); + await input.press("Tab"); + await expect(input).toHaveJSProperty("value", value); + }; + for (const window of [page, other]) + await window.goto("/tests/fixtures/emoji.html"); + // Each window opens its picker first, so each has loaded Emoji Mart. + for (const window of [page, other]) { + await window + .getByRole("button", { name: "Emoji and GIFS", exact: true }) + .click(); + await window.keyboard.press("Escape"); + } + await choose(page, ":smirk", /:smirk:/, "😏 "); + await choose(other, ":rocket", /:rocket:/, "🚀 "); + await choose(page, ":tada", /:tada:/, "🎉 "); + await expect + .poll(() => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ), + ) + .toEqual({ smirk: 1, rocket: 1, tada: 1 }); + for (const watched of errors) expect(watched.unexplained()).toEqual([]); +}); diff --git a/tests/browser/emoji.spec.mjs b/tests/browser/emoji.spec.mjs index 383619848c..6db4ce1bfb 100644 --- a/tests/browser/emoji.spec.mjs +++ b/tests/browser/emoji.spec.mjs @@ -1354,6 +1354,10 @@ test("the first toned pick asks for a default skin tone", async ({ page }) => { }; const savedTone = () => page.evaluate(() => localStorage.getItem("emoji-mart.skin")); + const usage = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ); const grid = (label) => page .locator(`em-emoji-picker .category button[aria-label="${label}"]`) @@ -1381,6 +1385,8 @@ test("the first toned pick asks for a default skin tone", async ({ page }) => { await expect(toneMenu).toHaveCount(0); await expect(draft).not.toContainText("👍"); expect(await savedTone()).toBeNull(); + // Nor does it count as a use. + expect(await usage()).toEqual({ grinning: 1 }); await page .getByRole("button", { name: "Choose default skin tone" }) .click(); @@ -1396,6 +1402,7 @@ test("the first toned pick asks for a default skin tone", async ({ page }) => { await toneMenu.locator(".option").nth(3).click(); await expect(draft).toContainText("👍🏽"); expect(await savedTone()).toBe("4"); + expect(await usage()).toEqual({ grinning: 1, "+1": 1 }); await draft.fill(""); await openPicker(); await grid("👍🏽").click(); From 929af5e9a3a479a5f4c4893cdcc6daa3486860dc Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Sun, 22 Nov 2026 14:23:33 -0800 Subject: [PATCH 07/16] fix(emoji): count only applied choices and keep literal shortcodes first a literal exact shortcode now ranks ahead of separator-insensitive exact matches before usage, so choosing ice_cream no longer reorders icecream. the composer distinguishes a typed terminator that landed alone from an applied edit. at the length limit the closing colon still lands, but the completion is no longer counted. picker hosts report rejected insertions, and the picker counts only accepted ones, including after a tone prompt. the frequently used row offers only emoji that the picker's other categories still show, so emoji the client cannot render no longer take slots from the default fill. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiPicker.tsx | 6 ++- src/bundled/emoji/emoji-mart.ts | 25 ++++++++----- src/bundled/emoji/emoji-search.test.ts | 7 ++++ src/bundled/emoji/emoji-search.ts | 12 +++++- src/bundled/emoji/emoji-usage.test.ts | 17 ++++++++- .../conversation/ComposerCompletions.test.tsx | 8 ++-- .../conversation/ComposerCompletions.tsx | 12 +++--- src/features/messages/EditableInput.test.tsx | 2 +- src/features/messages/EditableInput.tsx | 3 +- src/features/messages/MessageComposer.tsx | 26 +++++++++---- src/features/messages/composer-dom.ts | 3 +- src/features/profiles/AvatarEditor.tsx | 5 ++- tests/browser/emoji-frequency.spec.mjs | 37 +++++++++++++++++++ 13 files changed, 127 insertions(+), 36 deletions(-) diff --git a/src/bundled/emoji/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 54ef7e00c9..991259e347 100644 --- a/src/bundled/emoji/EmojiPicker.tsx +++ b/src/bundled/emoji/EmojiPicker.tsx @@ -79,7 +79,8 @@ export function EmojiPicker({ addEmoji?: Pick | undefined; scope: string; disabled: boolean; - insert(value: string): void; + /** Return false when the insertion is rejected. */ + insert(value: string): unknown; reaction?: boolean; gifRequests?: GifRequests | undefined; externalTrigger?: { @@ -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) => diff --git a/src/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index 3f5f5d423a..ab3f15cef7 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -37,8 +37,16 @@ function checkMartPropTimer(picker: HTMLElement) { // windows' choices, and counts a pick before the tone prompt confirms it. Object.assign(FrequentlyUsed, { add() {}, - get: (props: { maxFrequentRows: number; perLine: number }) => - frequentEmoji(props, FrequentlyUsed.DEFAULTS, (id) => !!Data?.emojis[id]), + 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(); + 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"; @@ -120,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; @@ -191,14 +200,13 @@ export function mountEmojiMart({ if (!emoji.id) return; if (emoji.native) { if (promptSkinTone(emoji.id)) return; - addEmojiUsage(emoji.id); - select(emoji.native); + if (select(emoji.native) !== false) addEmojiUsage(emoji.id); return; } const custom = values.get(emoji.id); if (!custom) return; - addEmojiUsage(emoji.id); - select(custom.literal, custom.shortcode); + 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 @@ -679,8 +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; - addEmojiUsage(id); - select(native); + if (select(native) !== false) addEmojiUsage(id); return true; }; // Mart clears the preview whenever the pointer leaves an emoji, so crossing diff --git a/src/bundled/emoji/emoji-search.test.ts b/src/bundled/emoji/emoji-search.test.ts index 6113ea7051..8bcc57c4a3 100644 --- a/src/bundled/emoji/emoji-search.test.ts +++ b/src/bundled/emoji/emoji-search.test.ts @@ -183,6 +183,13 @@ it("puts often chosen emoji first within exact, prefix and other matches", async 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); diff --git a/src/bundled/emoji/emoji-search.ts b/src/bundled/emoji/emoji-search.ts index bac06addd6..05c296941a 100644 --- a/src/bundled/emoji/emoji-search.ts +++ b/src/bundled/emoji/emoji-search.ts @@ -187,7 +187,15 @@ function rankEmoji( .map(({ item }) => item) .filter((item) => !semanticIds.has(item.id)), ]; - const strong = rank(combined).filter(({ tier }) => tier <= 1); + const literal = query.toLowerCase(); + const strong = rank(combined) + .filter(({ tier }) => tier <= 1) + // 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, @@ -195,7 +203,7 @@ function rankEmoji( .filter((item) => !promoted.has(item.id)) .map((item) => ({ item, tier: semanticIds.has(item.id) ? 2 : 3 })), ] - // Within exact, prefix, name or keyword, and fuzzy matches, the more often + // 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)) .map(({ item }) => item); diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 638394fdd9..50a3ac65b3 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -1,6 +1,6 @@ // @vitest-environment jsdom import data from "@emoji-mart/data"; -import { FrequentlyUsed, init } from "emoji-mart"; +import { Data, FrequentlyUsed, init } from "emoji-mart"; import { afterEach, expect, it } from "vitest"; import "./emoji-mart"; import { @@ -91,4 +91,19 @@ it("keeps Mart's pickers on the shared history", async () => { get(props: { maxFrequentRows: number; perLine: number }): string[]; }; expect(mart.get({ maxFrequentRows: 1, perLine: 2 })).toEqual(["smirk", "+1"]); + // Mart drops emoji newer than the client renders from their categories + // first; those leave the row to the defaults rather than an empty slot. + const category: { emojis: string[] } = Data.categories.find( + (category: { emojis: string[] }) => category.emojis.includes("smirk"), + ); + const at = category.emojis.indexOf("smirk"); + category.emojis.splice(at, 1); + try { + expect(mart.get({ maxFrequentRows: 1, perLine: 2 })).toEqual([ + "+1", + "grinning", + ]); + } finally { + category.emojis.splice(at, 0, "smirk"); + } }); diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index dc693a6508..0f42bc3d32 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -131,7 +131,7 @@ function mountPeople( }: { items?: readonly object[]; bundled?: boolean; - replace?: () => boolean; + replace?: () => boolean | "typed"; tokens?: readonly { start: number; end: number }[]; identityMarks?: Contribution[]; } = {}, @@ -289,8 +289,8 @@ it("ignores the agent flag from providers outside the bundled people providers", }); const folder = { kind: "folder", id: "/notes", label: "@notes" }; -it.each([true, false])( - "tells the provider once about an accepted choice, never a rejected one (accepted: %s)", +it.each([true, false, "typed"] as const)( + "tells the provider once about an applied choice, never a rejected or typed-only one (accepted: %s)", async (accepted) => { const onSelect = vi.fn(); mountPeople("test.plugin", { @@ -304,7 +304,7 @@ it.each([true, false])( fireEvent.pointerMove(option); expect(onSelect).not.toHaveBeenCalled(); fireEvent.click(option); - expect(onSelect).toHaveBeenCalledTimes(accepted ? 1 : 0); + expect(onSelect).toHaveBeenCalledTimes(accepted === true ? 1 : 0); }, ); it.each([true, false])( diff --git a/src/features/conversation/ComposerCompletions.tsx b/src/features/conversation/ComposerCompletions.tsx index 2f9d3a624c..863dce4aa7 100644 --- a/src/features/conversation/ComposerCompletions.tsx +++ b/src/features/conversation/ComposerCompletions.tsx @@ -189,12 +189,13 @@ export function ComposerCompletions({ pending?: readonly Readonly<{ start: number; end: number }>[] | undefined; tokens?: readonly Readonly<{ start: number; end: number }>[] | undefined; }>; + /** `"typed"`: the key landed literally, but the edit did not. */ replace( edit: HostCompletionEdit, query: CompletionQuery, observation: ComposerObservation, key?: string, - ): boolean; + ): boolean | "typed"; }) { const providers = useSyncExternalStore( registry.subscribe, @@ -342,12 +343,13 @@ function OwnedCompletion({ pointerPosition: RefObject< Pick | undefined >; + /** `"typed"`: the key landed literally, but the edit did not. */ replace( edit: HostCompletionEdit, query: CompletionQuery, observation: ComposerObservation, key?: string, - ): boolean; + ): boolean | "typed"; }) { const id = useId(); const compact = provider.pluginId === "buzz.emoji"; @@ -547,15 +549,15 @@ function OwnedCompletion({ const accepted = withHumanMentionSelection(event, () => current.current.replace(item.edit, source.query, observation, key), ); - if (accepted) { - current.current.editor.invalidate(); + if (accepted) current.current.editor.invalidate(); + if (accepted === true) { try { item.onSelect?.(); } catch { /* A provider callback cannot undo the accepted edit. */ } } - return accepted; + return !!accepted; } useLayoutEffect(() => { const element = input.current; diff --git a/src/features/messages/EditableInput.test.tsx b/src/features/messages/EditableInput.test.tsx index 085eb54886..2820af3478 100644 --- a/src/features/messages/EditableInput.test.tsx +++ b/src/features/messages/EditableInput.test.tsx @@ -186,7 +186,7 @@ it("keeps exactly one typed colon when the conversion exceeds the limit", () => act(() => expect( h.input.insertText("too long", undefined, { start: 0, end: 2 }, ":"), - ).toBe(true), + ).toBe("typed"), ); expect(h.input).toHaveValue(":x:"); expect([h.input.selectionStart, h.input.selectionEnd]).toEqual([3, 3]); diff --git a/src/features/messages/EditableInput.tsx b/src/features/messages/EditableInput.tsx index abf81d5a81..53014f2bd7 100644 --- a/src/features/messages/EditableInput.tsx +++ b/src/features/messages/EditableInput.tsx @@ -1211,7 +1211,8 @@ export function EditableInput({ .length > current.current.maxLength ) { onTooLong?.(); - return !!terminator; // The typed colon landed even if conversion cannot. + // The typed colon landed even if conversion cannot. + return terminator ? "typed" : false; } // Only pastes report overlong text. Pasted identity links become // recipients at once, so they need their chips in this transaction. diff --git a/src/features/messages/MessageComposer.tsx b/src/features/messages/MessageComposer.tsx index 620fb955fd..64d29c027a 100644 --- a/src/features/messages/MessageComposer.tsx +++ b/src/features/messages/MessageComposer.tsx @@ -2166,7 +2166,11 @@ function Composer({ !!input.current?.isConnected && !input.current.disabled && !input.current.readOnly; - function insert( + /** Like `insertTerminated`, counting a typed terminator alone as inserted. */ + function insert(...args: Parameters) { + return !!insertTerminated(...args); + } + function insertTerminated( text: string, recipient?: MentionRecipient, range?: CompletionQuery, @@ -2195,13 +2199,14 @@ function Composer({ } completion.invalidate(); const selected = recipient && editorMention(recipient); - if (!field.insertText(text, selected, range, terminator, focus)) { + const inserted = field.insertText(text, selected, range, terminator, focus); + if (!inserted) { setError("Message is too long to insert text"); return false; } if (recipient) rememberMention(session, channelId, recipient.pubkey); setError(undefined); - return true; + return inserted; } /** Completed and picked emoji are followed by a space, so typing continues * as a new word. A space or tab already at `at` is reused: the caret moves @@ -2219,22 +2224,27 @@ function Composer({ /\d/.test(valueRef.current.text[start - 1] ?? "") ? ` ${text}` : text; - if (!insert(separated ? value : `${value} `, undefined, range, terminator)) - return false; + const inserted = insertTerminated( + separated ? value : `${value} `, + undefined, + range, + terminator, + ); + if (!inserted) return false; const field = input.current; const end = field?.selectionEnd ?? 0; // A typed colon can land without conversion at the length limit; the // caret then stays after the literal colon. if (separated && field?.value.slice(end - text.length, end) === text) field.setSelectionRange(end + 1, end + 1); - return true; + return inserted; } function insertToolText(text: string) { const end = input.current?.selectionEnd; return ( attachGif(text) ?? (end !== undefined && isEmojiOnly(text, emojiCatalog.entries) - ? insertEmoji(text, end) + ? !!insertEmoji(text, end) : insert(text)) ); } @@ -2679,7 +2689,7 @@ function Composer({ const terminator = key === ":" ? key : undefined; return isEmojiOnly(edit.text, emojiCatalog.entries) ? insertEmoji(edit.text, query.end, query, terminator) - : insert(`${edit.text} `, undefined, query, terminator); + : insertTerminated(`${edit.text} `, undefined, query, terminator); } const currentAdmission = () => live.current && diff --git a/src/features/messages/composer-dom.ts b/src/features/messages/composer-dom.ts index 415f040ecb..a04c26dca8 100644 --- a/src/features/messages/composer-dom.ts +++ b/src/features/messages/composer-dom.ts @@ -102,6 +102,7 @@ export type ComposerInputElement = HTMLDivElement & { disabled: boolean; readOnly: boolean; setSelectionRange(start: number, end: number, direction?: string): void; + /** `"typed"`: only the terminator landed; the text did not fit. */ insertText( text: string, recipient?: MentionRecipient | readonly MentionRecipient[], @@ -112,7 +113,7 @@ export type ComposerInputElement = HTMLDivElement & { terminator?: string, /** Automatic edits preserve focus and the current selection. */ focus?: boolean, - ): boolean; + ): boolean | "typed"; replaceRecipients(recipients: readonly MentionRecipient[]): boolean; /** Replace the typed `@name` with a chip the host is still resolving, * followed by the key that ended it (a space by default); the returned id diff --git a/src/features/profiles/AvatarEditor.tsx b/src/features/profiles/AvatarEditor.tsx index 8ae3e20da4..6c54cff696 100644 --- a/src/features/profiles/AvatarEditor.tsx +++ b/src/features/profiles/AvatarEditor.tsx @@ -894,15 +894,16 @@ export function AvatarEmojiPicker({ }) { const host = useRef(null); const pointer = useRef(false); - const callback = useRef<(value: string) => void>(() => {}); + const callback = useRef<(value: string) => boolean>(() => false); callback.current = (value) => { - if (disabled) return; + if (disabled) return false; const fromPointer = pointer.current; pointer.current = false; const animate = fromPointer && !window.matchMedia("(prefers-reduced-motion: reduce)").matches; onSelect(value, animate); + return true; }; const [error, setError] = useState(false); const [{ scale, perLine }, setLayout] = useState({ diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 6434860e2c..50e7813831 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -177,3 +177,40 @@ test("choices in two windows of one profile keep each other", async ({ .toEqual({ smirk: 1, rocket: 1, tada: 1 }); for (const watched of errors) expect(watched.unexplained()).toEqual([]); }); + +test("emoji a full composer cannot insert teach nothing", async ({ page }) => { + const errors = watchPageErrors(page); + await page.goto("/tests/fixtures/emoji.html"); + const input = page.getByRole("textbox", { name: "Message #general" }); + const search = page.getByRole("searchbox", { name: "Search emoji" }); + const counts = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ); + const pickRocket = async () => { + await page + .getByRole("button", { name: "Emoji and GIFS", exact: true }) + .click(); + await search.fill("rocket"); + await page + .locator('em-emoji-picker .category button[aria-label="🚀"]') + .first() + .click(); + }; + // The closing colon fits under the limit; the flag that replaces it does not. + const draft = `${"a".repeat(16000 - 13)} :flag-wales`; + await input.fill(draft); + await expect(page.getByRole("option").first()).toHaveText(/:flag-wales:/); + await input.press(":"); + await expect(input).toHaveJSProperty("value", `${draft}:`); + // A picker choice does not fit the full draft either. + await pickRocket(); + await expect(page.getByRole("alert")).toContainText("too long"); + await expect(input).toHaveJSProperty("value", `${draft}:`); + expect(await counts()).toEqual({}); + await input.fill(""); + await pickRocket(); + await expect(input).toHaveJSProperty("value", "🚀 "); + await expect.poll(counts).toEqual({ rocket: 1 }); + expect(errors.unexplained()).toEqual([]); +}); From 804dedecadfb9493711674a8ba7ed82621825d0c Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Sun, 22 Nov 2026 14:51:48 -0800 Subject: [PATCH 08/16] test(emoji): replace the draft after a picker pick with select-all keys a picker pick focuses the editor, and prosemirror restores its own selection 20 ms after focus when the dom selection differs. playwright's fill selects all with a dom range, so a fill landing in that window was undone and its text appended to the draft. press the composer's own select-all, which updates prosemirror's selection, then insert the text. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- tests/browser/emoji-frequency.spec.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 50e7813831..82bd67ace7 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -66,7 +66,11 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", ).toBeVisible(); await page.keyboard.press("Enter"); await expect(input).toHaveJSProperty("value", "😏 "); - await input.fill(":sm"); + // The pick focused the editor. ProseMirror restores its own selection 20 ms + // after focus, undoing the DOM select-all `fill` makes in that window, so + // replace the draft with the composer's own select-all, as a person would. + await input.press("ControlOrMeta+a"); + await page.keyboard.insertText(":sm"); await expect(choices.first()).toHaveText(/:smirk:/); await input.press("Tab"); await expect(input).toHaveJSProperty("value", "😏 "); From 26f4be7961f90fa06fae81e6335000d39391cb78 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 08:21:33 -0800 Subject: [PATCH 09/16] fix(emoji): count a reaction picker choice only when it adds choosing an emoji you already reacted with removes that reaction, and the toggle reported success, so the removal counted as a use. the toggle now reports added or removed, and the reaction pickers count only additions. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/features/messages/MessageReactions.tsx | 16 +++++++--- tests/browser/emoji-frequency.spec.mjs | 36 ++++++++++++++++++++++ 2 files changed, 47 insertions(+), 5 deletions(-) diff --git a/src/features/messages/MessageReactions.tsx b/src/features/messages/MessageReactions.tsx index 17a70547d6..1ffdf358ab 100644 --- a/src/features/messages/MessageReactions.tsx +++ b/src/features/messages/MessageReactions.tsx @@ -67,7 +67,10 @@ function useReactionAction({ row, session, disabled }: Props) { ["sending", "failed", "unknown"].includes(item.delivery) && session.messages.reactionTarget(item.event) === row.id; const busy = operations.some(blocksToggle); - const toggle = (content: string, emoji?: CustomEmoji) => { + const toggle = ( + content: string, + emoji?: CustomEmoji, + ): "added" | "removed" | false => { if (!active.current || session.outbox?.snapshot().some(blocksToggle)) return false; try { @@ -83,7 +86,7 @@ function useReactionAction({ row, session, disabled }: Props) { session.messages.react(row.id, content, emoji); } setError(undefined); - return true; + return mine.length ? "removed" : "added"; } catch (reason) { setError( reason instanceof Error @@ -105,8 +108,9 @@ export function MessageReactionControls(props: Props) { session.emoji.snapshot, ); const action = useReactionAction(props); + // Only an addition is a use; choosing an existing reaction removes it. const select = (content: string) => - action.toggle(content, catalogEmoji(catalog.entries, content)); + action.toggle(content, catalogEmoji(catalog.entries, content)) === "added"; return ( <> | undefined; disabled: boolean; busy: boolean; - toggle(content: string, emoji?: CustomEmoji): boolean; + toggle(content: string, emoji?: CustomEmoji): "added" | "removed" | false; onFocusedRemoval?: (() => void) | undefined; previewWarm: boolean; previewSlide: "left" | "right" | undefined; @@ -479,7 +483,9 @@ export function MessageReactions( if (!active && preview) setPreview(undefined); if (!active && pointerInRow) setPointerInRow(false); const select = (content: string) => { - return action.toggle(content, catalogEmoji(catalog.entries, content)); + return ( + action.toggle(content, catalogEmoji(catalog.entries, content)) === "added" + ); }; // Count people, not duplicate events. Each emoji shares one control and preview. const reactions = useMemo( diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index 82bd67ace7..be257aa019 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -1,3 +1,4 @@ +import { hoverMessage } from "./message-actions.mjs"; import { test, expect } from "./source-fixture.mjs"; import { watchPageErrors } from "./page-errors.mjs"; @@ -218,3 +219,38 @@ test("emoji a full composer cannot insert teach nothing", async ({ page }) => { await expect.poll(counts).toEqual({ rocket: 1 }); expect(errors.unexplained()).toEqual([]); }); + +test("choosing an existing reaction removes it and teaches nothing", async ({ + page, +}) => { + const errors = watchPageErrors(page); + await page.goto("/tests/fixtures/emoji.html?reactions"); + const row = page.locator("[data-message-id]").first(); + const search = page.getByRole("searchbox", { name: "Search emoji" }); + const pill = row.locator('button[data-reaction="🚀"]'); + const counts = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + ); + const reactRocket = async () => { + await hoverMessage(row); + await row + .getByRole("group", { name: "Message actions", includeHidden: true }) + .getByRole("button", { name: "Add reaction", exact: true }) + .click(); + await search.fill("rocket"); + await page + .locator('em-emoji-picker .category button[aria-label="🚀"]') + .first() + .click(); + await expect(search).toHaveCount(0); + }; + await reactRocket(); + await expect(pill).toHaveAttribute("aria-pressed", "true"); + await expect(pill).toHaveAttribute("aria-disabled", "false"); + await expect.poll(counts).toEqual({ rocket: 1 }); + await reactRocket(); + await expect(pill).toHaveCount(0); + expect(await counts()).toEqual({ rocket: 1 }); + expect(errors.unexplained()).toEqual([]); +}); From 9c8479ee898ab87f9e5107fd0ddffab6d39983fa Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 08:30:55 -0800 Subject: [PATCH 10/16] test(emoji): drop frequency browser checks covered elsewhere remove the picker-width reload test, which guarded the removed default seeding; the row-filling rule is unit tested. drop the hate keyword checks, which repeat the unit ranking test and the stored-defaults check, and the repeated community ranking after reload. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- tests/browser/emoji-frequency.spec.mjs | 36 -------------------------- 1 file changed, 36 deletions(-) diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index be257aa019..de3f629b6d 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -45,8 +45,6 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", // New users get the query order. await input.fill(":sm"); await expect(choices.first()).toHaveText(/:smile:/); - await input.fill(":hate"); - await expect(choices.first()).toHaveText(/:rage:/); await input.fill(":party-p"); await expect.poll(labels).toEqual([":party-parrot:", ":party-parrot-wave:"]); // Highlighting a suggestion is not choosing it. @@ -80,10 +78,6 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await expect(choices.first()).toHaveText(/:smirk:/); await input.press(":"); await expect(input).toHaveJSProperty("value", "😏 "); - // The picker's default row is not usage: never-chosen 😍 stays behind - // the keyword match for `hate`. - await input.fill(":hate"); - await expect(choices.first()).toHaveText(/:rage:/); // A keyboard suggestion choice of a community emoji teaches suggestions and // the picker's Frequently used row, once. @@ -110,8 +104,6 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", await page.reload(); await input.fill(":sm"); await expect(choices.first()).toHaveText(/:smirk:/); - await input.fill(":party-p"); - await expect.poll(labels).toEqual([":party-parrot-wave:", ":party-parrot:"]); await input.press("Escape"); await input.fill(""); await openFrequent(); @@ -120,34 +112,6 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", expect(errors.unexplained()).toEqual([]); }); -test("the default row follows the picker's width across reloads", async ({ - page, -}) => { - const errors = watchPageErrors(page); - const frequent = page.locator( - 'em-emoji-picker .category[data-id="frequent"] button', - ); - const openPicker = async () => { - await page - .getByRole("button", { name: "Emoji and GIFS", exact: true }) - .click(); - await expect(frequent.first()).toBeVisible(); - }; - await page.setViewportSize({ width: 240, height: 844 }); - await page.goto("/tests/fixtures/emoji.html"); - await openPicker(); - await expect(frequent).toHaveCount(4); - await page.setViewportSize({ width: 1440, height: 900 }); - await page.reload(); - await openPicker(); - await expect(frequent).toHaveCount(8); - await page.setViewportSize({ width: 240, height: 844 }); - await page.reload(); - await openPicker(); - await expect(frequent).toHaveCount(4); - expect(errors.unexplained()).toEqual([]); -}); - test("choices in two windows of one profile keep each other", async ({ page, context, From bbe3972083ba33b5bef6fe624453e1a6254f5cdc Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 08:45:08 -0800 Subject: [PATCH 11/16] test(emoji): cover the inline reaction picker and document select results the removal regression now makes its second pick from the plus beside the reactions, so both reaction picker wrappers are tested. the reaction tool and emoji picker contracts say which results count as a use. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiPicker.tsx | 5 ++++- src/features/conversation/contracts.ts | 6 +++++- tests/browser/emoji-frequency.spec.mjs | 18 +++++++++++------- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/bundled/emoji/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 991259e347..94071d6908 100644 --- a/src/bundled/emoji/EmojiPicker.tsx +++ b/src/bundled/emoji/EmojiPicker.tsx @@ -79,7 +79,10 @@ export function EmojiPicker({ addEmoji?: Pick | undefined; scope: string; disabled: boolean; - /** Return false when the insertion is rejected. */ + /** + * Return false when the choice is rejected or removes a reaction; any other + * result counts it as a use. + */ insert(value: string): unknown; reaction?: boolean; gifRequests?: GifRequests | undefined; diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index bd6cde7f7c..e0151e4ab3 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -112,7 +112,11 @@ export type ReactionToolProps = Readonly<{ session: RelaySession; scope: string; disabled: boolean; - /** Host-owned reaction intent; revoked when the tool or target is removed. */ + /** + * Host-owned reaction intent; revoked when the tool or target is removed. + * True means the choice added a reaction and counts as a use; false means it + * was rejected or removed an existing reaction. + */ select(emoji: string): boolean; }>; export type ComposerTool = Readonly<{ diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index de3f629b6d..d342c9beb3 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -196,12 +196,16 @@ test("choosing an existing reaction removes it and teaches nothing", async ({ page.evaluate(() => JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), ); - const reactRocket = async () => { + const actions = row + .getByRole("group", { name: "Message actions", includeHidden: true }) + .getByRole("button", { name: "Add reaction", exact: true }); + // The second pick uses the plus beside the reactions, a separate picker. + const inline = row + .getByTestId("inline-add-reaction") + .getByRole("button", { name: "Add reaction", exact: true }); + const reactRocket = async (plus) => { await hoverMessage(row); - await row - .getByRole("group", { name: "Message actions", includeHidden: true }) - .getByRole("button", { name: "Add reaction", exact: true }) - .click(); + await plus.click(); await search.fill("rocket"); await page .locator('em-emoji-picker .category button[aria-label="🚀"]') @@ -209,11 +213,11 @@ test("choosing an existing reaction removes it and teaches nothing", async ({ .click(); await expect(search).toHaveCount(0); }; - await reactRocket(); + await reactRocket(actions); await expect(pill).toHaveAttribute("aria-pressed", "true"); await expect(pill).toHaveAttribute("aria-disabled", "false"); await expect.poll(counts).toEqual({ rocket: 1 }); - await reactRocket(); + await reactRocket(inline); await expect(pill).toHaveCount(0); expect(await counts()).toEqual({ rocket: 1 }); expect(errors.unexplained()).toEqual([]); From 87a8debdd6d8f31269420efb92ce0df2ac36aff9 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 08:55:28 -0800 Subject: [PATCH 12/16] test(emoji): cover both reaction picker removals and pin keyword matches the reaction regression removed only through the inline picker, so the action bar wrapper could count a removal again unnoticed. re-add and remove through the action bar as well. the keyword ranking test compared results with and without usage but never stated the answer; assert rage and hankey. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-search.test.ts | 10 +++++----- tests/browser/emoji-frequency.spec.mjs | 7 +++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/bundled/emoji/emoji-search.test.ts b/src/bundled/emoji/emoji-search.test.ts index 8bcc57c4a3..aa685020f4 100644 --- a/src/bundled/emoji/emoji-search.test.ts +++ b/src/bundled/emoji/emoji-search.test.ts @@ -158,12 +158,12 @@ it("keeps alias and keyword matches ahead of often chosen fuzzy matches", async (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] of [ - ["hate", "unicode/heart_eyes"], - ["poop", "unicode/person_in_lotus_position"], + for (const [query, fuzzy, match] of [ + ["hate", "unicode/heart_eyes", "rage"], + ["poop", "unicode/person_in_lotus_position", "hankey"], ] as const) { - const plain = await first(query); - expect(await first(query, (id) => (id === fuzzy ? 8 : 0))).toBe(plain); + expect(await first(query)).toBe(match); + expect(await first(query, (id) => (id === fuzzy ? 8 : 0))).toBe(match); } }); diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index d342c9beb3..d6bf67f0e8 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -220,5 +220,12 @@ test("choosing an existing reaction removes it and teaches nothing", async ({ await reactRocket(inline); await expect(pill).toHaveCount(0); expect(await counts()).toEqual({ rocket: 1 }); + // The action bar picker removes too; the inline plus needs a reaction first. + await reactRocket(actions); + await expect(pill).toHaveAttribute("aria-pressed", "true"); + await expect.poll(counts).toEqual({ rocket: 2 }); + await reactRocket(actions); + await expect(pill).toHaveCount(0); + expect(await counts()).toEqual({ rocket: 2 }); expect(errors.unexplained()).toEqual([]); }); From 4f4df8c071034e485eeceedc48d45e3f77f25eac Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 09:37:18 -0800 Subject: [PATCH 13/16] fix(emoji): remove mart seeded defaults from stored usage once emoji mart 5.6 seeded a new history with its defaults at perline - i and saved them with the first pick, so existing histories rank defaults as choices. subtract the widest seed run every count can contain, once, recorded with a marker, and keep the picks made on top of it. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-usage.test.ts | 31 +++++++++++++ src/bundled/emoji/emoji-usage.ts | 54 +++++++++++++++++++++- src/features/messages/MessageReactions.tsx | 16 ++----- 3 files changed, 88 insertions(+), 13 deletions(-) diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 50a3ac65b3..9c3fd548c1 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -40,6 +40,37 @@ it("reads whole choices from the picker's counts for Unicode and community sugge expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); +it("removes the defaults Mart stored as picks once, keeping real picks", () => { + // What Mart 5.6 saves at perLine 9 (module.js:487-505): its seed, then the + // picks rocket once and grinning twice. + const seed = [ + "+1", + "grinning", + "kissing_heart", + "heart_eyes", + "laughing", + "stuck_out_tongue_winking_eye", + "sweat_smile", + "joy", + "scream", + ]; + const mart: Record = Object.fromEntries( + seed.map((id, i) => [id, 9 - i]), + ); + mart.grinning = (mart.grinning ?? 0) + 2; + mart.rocket = 1; + localStorage.setItem("emoji-mart.frequently", JSON.stringify(mart)); + const uses = emojiUsage("s"); + expect(uses("unicode/rocket")).toBe(1); + expect(uses("unicode/grinning")).toBe(2); + expect(uses("unicode/+1")).toBe(0); + expect(uses("unicode/scream")).toBe(0); + expect(stored()).toEqual({ grinning: 2, rocket: 1 }); + // Only once: later counts that look like a seed are real picks. + localStorage.setItem("emoji-mart.frequently", JSON.stringify({ "+1": 1 })); + expect(emojiUsage("s")("unicode/+1")).toBe(1); +}); + it("counts each choice against the latest history, keeping other windows' choices", () => { recordEmojiUsage("wss://relay.test/a", "unicode/smirk"); // Another window chooses from the same storage. diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index 4eac4dc489..66c00ec61a 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -3,6 +3,27 @@ // It is read fresh on every use, so each window keeps the others' choices. const STORE = "emoji-mart.frequently"; const LAST = "emoji-mart.last"; +const SEED_REMOVED = "buzz.emoji-usage.seed-removed"; +// Emoji Mart 5.6 seeded a new history with these defaults at perLine - i, as +// if chosen, and saved them with the first pick. Copied so that suggestions do +// not load Mart. +const MART_SEED = [ + "+1", + "grinning", + "kissing_heart", + "heart_eyes", + "laughing", + "stuck_out_tongue_winking_eye", + "sweat_smile", + "joy", + "scream", + "disappointed", + "unamused", + "weary", + "sob", + "sunglasses", + "heart", +]; /** The picker's ID for a community emoji, scoped like its catalog. */ export const customEmojiId = (scope: string, shortcode: string) => @@ -17,14 +38,43 @@ function usageId(scope: string, id: string) { } function readCounts(): Record { + let counts: Record = {}; try { const stored: unknown = JSON.parse(localStorage.getItem(STORE) ?? "{}"); if (stored && typeof stored === "object" && !Array.isArray(stored)) - return stored as Record; + counts = stored as Record; } catch { /* Without storage, nothing has been chosen. */ } - return {}; + try { + if (localStorage.getItem(SEED_REMOVED) === null) { + if (removeMartSeed(counts)) + localStorage.setItem(STORE, JSON.stringify(counts)); + localStorage.setItem(SEED_REMOVED, "1"); + } + } catch { + /* Retried on the next read. */ + } + return counts; +} + +/** Subtracts Mart's seed once, keeping the picks made on top of it. The seed + * width is unknown, so take the widest run every count can contain. */ +function removeMartSeed(counts: Record) { + const count = (i: number) => uses(counts, MART_SEED[i] ?? ""); + let width = 0; + for (let size = 1; size <= MART_SEED.length; size++) { + let fits = true; + for (let i = 0; i < size && fits; i++) fits = count(i) >= size - i; + if (fits) width = size; + } + for (let i = 0; i < width; i++) { + const id = MART_SEED[i] ?? ""; + const left = count(i) - (width - i); + if (left > 0) counts[id] = left; + else delete counts[id]; + } + return width > 0; } function uses(counts: Record, key: string) { diff --git a/src/features/messages/MessageReactions.tsx b/src/features/messages/MessageReactions.tsx index 1ffdf358ab..17a70547d6 100644 --- a/src/features/messages/MessageReactions.tsx +++ b/src/features/messages/MessageReactions.tsx @@ -67,10 +67,7 @@ function useReactionAction({ row, session, disabled }: Props) { ["sending", "failed", "unknown"].includes(item.delivery) && session.messages.reactionTarget(item.event) === row.id; const busy = operations.some(blocksToggle); - const toggle = ( - content: string, - emoji?: CustomEmoji, - ): "added" | "removed" | false => { + const toggle = (content: string, emoji?: CustomEmoji) => { if (!active.current || session.outbox?.snapshot().some(blocksToggle)) return false; try { @@ -86,7 +83,7 @@ function useReactionAction({ row, session, disabled }: Props) { session.messages.react(row.id, content, emoji); } setError(undefined); - return mine.length ? "removed" : "added"; + return true; } catch (reason) { setError( reason instanceof Error @@ -108,9 +105,8 @@ export function MessageReactionControls(props: Props) { session.emoji.snapshot, ); const action = useReactionAction(props); - // Only an addition is a use; choosing an existing reaction removes it. const select = (content: string) => - action.toggle(content, catalogEmoji(catalog.entries, content)) === "added"; + action.toggle(content, catalogEmoji(catalog.entries, content)); return ( <> | undefined; disabled: boolean; busy: boolean; - toggle(content: string, emoji?: CustomEmoji): "added" | "removed" | false; + toggle(content: string, emoji?: CustomEmoji): boolean; onFocusedRemoval?: (() => void) | undefined; previewWarm: boolean; previewSlide: "left" | "right" | undefined; @@ -483,9 +479,7 @@ export function MessageReactions( if (!active && preview) setPreview(undefined); if (!active && pointerInRow) setPointerInRow(false); const select = (content: string) => { - return ( - action.toggle(content, catalogEmoji(catalog.entries, content)) === "added" - ); + return action.toggle(content, catalogEmoji(catalog.entries, content)); }; // Count people, not duplicate events. Each emoji shares one control and preview. const reactions = useMemo( From 8bd85fef06972499f738e3588189dc63024946b8 Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 09:37:19 -0800 Subject: [PATCH 14/16] fix(emoji): keep reaction select meaning success and onselect bundled choosing an existing reaction again reports success to reaction pickers. the host tells pickers which emoji the viewer already reacted with, so the bundled picker skips counting a removal. completion onselect is forwarded only from bundled providers. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/EmojiPicker.tsx | 5 +--- src/bundled/emoji/ReactionPicker.tsx | 7 +++++- .../conversation/ComposerCompletions.test.tsx | 16 +++++++++--- src/features/conversation/ReactionTool.tsx | 4 +++ src/features/conversation/completion.ts | 4 ++- src/features/conversation/contracts.ts | 10 +++----- src/features/messages/MessageReactions.tsx | 25 ++++++++++++------- 7 files changed, 46 insertions(+), 25 deletions(-) diff --git a/src/bundled/emoji/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 94071d6908..1f68465993 100644 --- a/src/bundled/emoji/EmojiPicker.tsx +++ b/src/bundled/emoji/EmojiPicker.tsx @@ -79,10 +79,7 @@ export function EmojiPicker({ addEmoji?: Pick | undefined; scope: string; disabled: boolean; - /** - * Return false when the choice is rejected or removes a reaction; any other - * result counts it as a use. - */ + /** Return false when the choice is rejected or must not count as a use. */ insert(value: string): unknown; reaction?: boolean; gifRequests?: GifRequests | undefined; diff --git a/src/bundled/emoji/ReactionPicker.tsx b/src/bundled/emoji/ReactionPicker.tsx index 100d3c8dbb..49b438a00a 100644 --- a/src/bundled/emoji/ReactionPicker.tsx +++ b/src/bundled/emoji/ReactionPicker.tsx @@ -13,6 +13,7 @@ export function createReactionPicker(addEmoji?: AddEmoji) { scope, disabled, select, + reacted, }: ReactionToolProps) { const [open, setOpen] = useState(false); const trigger = useRef(null); @@ -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={{ diff --git a/src/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 0f42bc3d32..1c55b4ae66 100644 --- a/src/features/conversation/ComposerCompletions.test.tsx +++ b/src/features/conversation/ComposerCompletions.test.tsx @@ -289,11 +289,17 @@ it("ignores the agent flag from providers outside the bundled people providers", }); const folder = { kind: "folder", id: "/notes", label: "@notes" }; -it.each([true, false, "typed"] as const)( - "tells the provider once about an applied choice, never a rejected or typed-only one (accepted: %s)", - async (accepted) => { +it.each([ + [true, true], + [false, true], + ["typed", true], + [true, false], +] as const)( + "tells a bundled provider once about an applied choice, never a rejected or typed-only one (accepted: %s, bundled: %s)", + async (accepted, bundled) => { const onSelect = vi.fn(); mountPeople("test.plugin", { + bundled, replace: () => accepted, items: [ { id: "first", label: "First", edit: { text: "1" }, onSelect }, @@ -304,7 +310,9 @@ it.each([true, false, "typed"] as const)( fireEvent.pointerMove(option); expect(onSelect).not.toHaveBeenCalled(); fireEvent.click(option); - expect(onSelect).toHaveBeenCalledTimes(accepted === true ? 1 : 0); + expect(onSelect).toHaveBeenCalledTimes( + accepted === true && bundled ? 1 : 0, + ); }, ); it.each([true, false])( diff --git a/src/features/conversation/ReactionTool.tsx b/src/features/conversation/ReactionTool.tsx index 62201be926..49e5797bd1 100644 --- a/src/features/conversation/ReactionTool.tsx +++ b/src/features/conversation/ReactionTool.tsx @@ -38,6 +38,7 @@ export function ReactionTool({ messageId: string; disabled: boolean; select?: (emoji: string) => boolean; + reacted?: (emoji: string) => boolean; showDelivery?: boolean; }) { const tools = useSyncExternalStore( @@ -72,6 +73,7 @@ function OwnedReactionTool({ messageId, disabled, select, + reacted, showDelivery = true, }: { registry: ContributionReader; @@ -81,6 +83,7 @@ function OwnedReactionTool({ messageId: string; disabled: boolean; select?: (emoji: string) => boolean; + reacted?: (emoji: string) => boolean; showDelivery?: boolean; }) { const [error, setError] = useState(); @@ -102,6 +105,7 @@ function OwnedReactionTool({ session={session} scope={scope} disabled={disabled} + {...(reacted ? { reacted } : {})} select={(emoji) => { if ( !alive.current || diff --git a/src/features/conversation/completion.ts b/src/features/conversation/completion.ts index 2e07d7716d..485f43a87f 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -183,7 +183,9 @@ export function completionResult( ...(typeof item.canSelect === "function" ? { canSelect: item.canSelect } : {}), - ...(typeof item.onSelect === "function" + ...(typeof item.onSelect === "function" && + provider && + isBundledContribution(provider) ? { onSelect: item.onSelect } : {}), edit: host diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index e0151e4ab3..6284afcc82 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -112,12 +112,10 @@ export type ReactionToolProps = Readonly<{ session: RelaySession; scope: string; disabled: boolean; - /** - * Host-owned reaction intent; revoked when the tool or target is removed. - * True means the choice added a reaction and counts as a use; false means it - * was rejected or removed an existing reaction. - */ + /** Host-owned reaction intent; revoked when the tool or target is removed. */ select(emoji: string): boolean; + /** Whether the viewer already reacted with this emoji, so selecting it removes that reaction. */ + reacted?: ((emoji: string) => boolean) | undefined; }>; export type ComposerTool = Readonly<{ id: string; @@ -448,7 +446,7 @@ export type CompletionSuggestion = Readonly<{ disabled?: string | undefined; /** Final synchronous evidence check; false never falls through to sending. */ canSelect?: ((key: string) => boolean) | undefined; - /** Called once after the host inserts this choice; never for highlighting. */ + /** Bundled providers only: called once after the host inserts this choice. */ onSelect?: (() => void) | undefined; }>; export type CompletionResult = Readonly<{ diff --git a/src/features/messages/MessageReactions.tsx b/src/features/messages/MessageReactions.tsx index 17a70547d6..9783980efd 100644 --- a/src/features/messages/MessageReactions.tsx +++ b/src/features/messages/MessageReactions.tsx @@ -67,18 +67,19 @@ function useReactionAction({ row, session, disabled }: Props) { ["sending", "failed", "unknown"].includes(item.delivery) && session.messages.reactionTarget(item.event) === row.id; const busy = operations.some(blocksToggle); + const mine = (content: string, emoji?: CustomEmoji) => + row.reactions + .find( + (reaction) => + reaction.content === content && reaction.emoji?.url === emoji?.url, + ) + ?.events.filter((event) => event.authorId === session.viewer) ?? []; const toggle = (content: string, emoji?: CustomEmoji) => { if (!active.current || session.outbox?.snapshot().some(blocksToggle)) return false; try { - const group = row.reactions.find( - (reaction) => - reaction.content === content && reaction.emoji?.url === emoji?.url, - ); - const mine = - group?.events.filter((event) => event.authorId === session.viewer) ?? - []; - if (mine.length) session.messages.remove(mine.map((event) => event.id)); + const own = mine(content, emoji); + if (own.length) session.messages.remove(own.map((event) => event.id)); else { session.messages.react(row.id, content, emoji); } @@ -93,7 +94,7 @@ function useReactionAction({ row, session, disabled }: Props) { return false; } }; - return { toggle, disabled: disabled || busy, busy, error }; + return { toggle, mine, disabled: disabled || busy, busy, error }; } /** The emoji contribution owns the single reaction-picker action. */ @@ -107,6 +108,8 @@ export function MessageReactionControls(props: Props) { const action = useReactionAction(props); const select = (content: string) => action.toggle(content, catalogEmoji(catalog.entries, content)); + const reacted = (content: string) => + action.mine(content, catalogEmoji(catalog.entries, content)).length > 0; return ( <> {action.error && {action.error}} @@ -481,6 +485,8 @@ export function MessageReactions( const select = (content: string) => { return action.toggle(content, catalogEmoji(catalog.entries, content)); }; + const reacted = (content: string) => + action.mine(content, catalogEmoji(catalog.entries, content)).length > 0; // Count people, not duplicate events. Each emoji shares one control and preview. const reactions = useMemo( () => @@ -584,6 +590,7 @@ export function MessageReactions( messageId={row.id} disabled={action.disabled} select={select} + reacted={reacted} showDelivery={false} /> From b9e455e8e38d140a1d13a6e26e88ec8800b2081a Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 09:45:43 -0800 Subject: [PATCH 15/16] fix(emoji): record the seed removal marker before rewriting counts the counts write could succeed while the marker write failed at quota, so the next read subtracted the seed again from real picks. write the marker first: a later failed counts write leaves the seed counted instead. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-usage.test.ts | 27 ++++++++++++++++++++++++++- src/bundled/emoji/emoji-usage.ts | 5 +++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 9c3fd548c1..24fa5cad26 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import data from "@emoji-mart/data"; import { Data, FrequentlyUsed, init } from "emoji-mart"; -import { afterEach, expect, it } from "vitest"; +import { afterEach, expect, it, vi } from "vitest"; import "./emoji-mart"; import { addEmojiUsage, @@ -71,6 +71,31 @@ it("removes the defaults Mart stored as picks once, keeping real picks", () => { expect(emojiUsage("s")("unicode/+1")).toBe(1); }); +it.each(["buzz.emoji-usage.seed-removed", "emoji-mart.frequently"])( + "never subtracts the seed twice when storage refuses %s", + (refused) => { + const values = new Map([ + ["emoji-mart.frequently", JSON.stringify({ "+1": 5, rocket: 3 })], + ]); + vi.stubGlobal("localStorage", { + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => { + if (key === refused) + throw new DOMException("full", "QuotaExceededError"); + values.set(key, value); + }, + }); + try { + // The seed stays counted rather than costing real picks on each read. + for (let read = 0; read < 3; read++) emojiUsage("s"); + expect(emojiUsage("s")("unicode/+1")).toBe(5); + expect(emojiUsage("s")("unicode/rocket")).toBe(3); + } finally { + vi.unstubAllGlobals(); + } + }, +); + it("counts each choice against the latest history, keeping other windows' choices", () => { recordEmojiUsage("wss://relay.test/a", "unicode/smirk"); // Another window chooses from the same storage. diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index 66c00ec61a..d6d5a57c39 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -48,12 +48,13 @@ function readCounts(): Record { } try { if (localStorage.getItem(SEED_REMOVED) === null) { + // Marker first: a failed write can leave the seed, never subtract twice. + localStorage.setItem(SEED_REMOVED, "1"); if (removeMartSeed(counts)) localStorage.setItem(STORE, JSON.stringify(counts)); - localStorage.setItem(SEED_REMOVED, "1"); } } catch { - /* Retried on the next read. */ + /* Without the marker, the seed stays counted until a later read. */ } return counts; } From 5cb445bb093f82fbc4c490c0974660ee7667069a Mon Sep 17 00:00:00 2001 From: Kalvin Chau Date: Mon, 23 Nov 2026 10:01:30 -0800 Subject: [PATCH 16/16] fix(emoji): start buzz usage history from mart without its defaults guessing the seed width from counts fails on histories mart pruned, and cannot tell seeds from real picks. keep buzz usage under its own key; until the first buzz pick, read mart history without the 15 defaults mart seeded. mart history is never rewritten, so no marker is needed. Co-authored-by: peon <9ac6794b000690b7e814eb1805ad32405d0bec7d52838de3a86cf967565dacc0@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kalvin Chau --- src/bundled/emoji/emoji-usage.test.ts | 88 +++++++++----------------- src/bundled/emoji/emoji-usage.ts | 66 ++++++++----------- tests/browser/emoji-frequency.spec.mjs | 8 +-- tests/browser/emoji.spec.mjs | 2 +- 4 files changed, 59 insertions(+), 105 deletions(-) diff --git a/src/bundled/emoji/emoji-usage.test.ts b/src/bundled/emoji/emoji-usage.test.ts index 24fa5cad26..3e398d0b60 100644 --- a/src/bundled/emoji/emoji-usage.test.ts +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import data from "@emoji-mart/data"; import { Data, FrequentlyUsed, init } from "emoji-mart"; -import { afterEach, expect, it, vi } from "vitest"; +import { afterEach, expect, it } from "vitest"; import "./emoji-mart"; import { addEmojiUsage, @@ -13,12 +13,12 @@ import { const party = customEmojiId("wss://relay.test/a", "party"); const stored = () => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "null"); + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "null"); afterEach(() => localStorage.clear()); it("reads whole choices from the picker's counts for Unicode and community suggestions", () => { localStorage.setItem( - "emoji-mart.frequently", + "buzz.emoji-usage.v1", JSON.stringify({ smile: 3, [party]: 2.5, @@ -34,73 +34,43 @@ it("reads whole choices from the picker's counts for Unicode and community sugge expect(uses("unicode/odd")).toBe(0); expect(uses("unicode/constructor")).toBe(0); // JSON parses an out-of-range count as Infinity. - localStorage.setItem("emoji-mart.frequently", '{"huge":1e400}'); + localStorage.setItem("buzz.emoji-usage.v1", '{"huge":1e400}'); expect(emojiUsage("s")("unicode/huge")).toBe(0); - localStorage.setItem("emoji-mart.frequently", "not json"); + localStorage.setItem("buzz.emoji-usage.v1", "not json"); expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); }); -it("removes the defaults Mart stored as picks once, keeping real picks", () => { - // What Mart 5.6 saves at perLine 9 (module.js:487-505): its seed, then the - // picks rocket once and grinning twice. - const seed = [ - "+1", - "grinning", - "kissing_heart", - "heart_eyes", - "laughing", - "stuck_out_tongue_winking_eye", - "sweat_smile", - "joy", - "scream", - ]; - const mart: Record = Object.fromEntries( - seed.map((id, i) => [id, 9 - i]), - ); - mart.grinning = (mart.grinning ?? 0) + 2; - mart.rocket = 1; - localStorage.setItem("emoji-mart.frequently", JSON.stringify(mart)); +it("starts from Mart's history without the defaults it stored as picks", () => { + // Mart 5.6 at perLine 8 (module.js:487-531): its seed +1:8 … joy:1, then + // smirk picked three times and rocket once, then the picker reopened at + // perLine 3, pruning the history to its two rows of six. + const mart = JSON.stringify({ + "+1": 8, + grinning: 7, + kissing_heart: 6, + heart_eyes: 5, + smirk: 3, + rocket: 1, + }); + localStorage.setItem("emoji-mart.frequently", mart); const uses = emojiUsage("s"); + expect(uses("unicode/smirk")).toBe(3); expect(uses("unicode/rocket")).toBe(1); - expect(uses("unicode/grinning")).toBe(2); expect(uses("unicode/+1")).toBe(0); - expect(uses("unicode/scream")).toBe(0); - expect(stored()).toEqual({ grinning: 2, rocket: 1 }); - // Only once: later counts that look like a seed are real picks. - localStorage.setItem("emoji-mart.frequently", JSON.stringify({ "+1": 1 })); - expect(emojiUsage("s")("unicode/+1")).toBe(1); + expect(uses("unicode/heart_eyes")).toBe(0); + // The first pick starts Buzz's history from that import; Mart's is kept. + addEmojiUsage("+1"); + expect(stored()).toEqual({ smirk: 3, rocket: 1, "+1": 1 }); + expect(localStorage.getItem("emoji-mart.frequently")).toBe(mart); + localStorage.setItem("emoji-mart.frequently", "{}"); + expect(emojiUsage("s")("unicode/smirk")).toBe(3); }); -it.each(["buzz.emoji-usage.seed-removed", "emoji-mart.frequently"])( - "never subtracts the seed twice when storage refuses %s", - (refused) => { - const values = new Map([ - ["emoji-mart.frequently", JSON.stringify({ "+1": 5, rocket: 3 })], - ]); - vi.stubGlobal("localStorage", { - getItem: (key: string) => values.get(key) ?? null, - setItem: (key: string, value: string) => { - if (key === refused) - throw new DOMException("full", "QuotaExceededError"); - values.set(key, value); - }, - }); - try { - // The seed stays counted rather than costing real picks on each read. - for (let read = 0; read < 3; read++) emojiUsage("s"); - expect(emojiUsage("s")("unicode/+1")).toBe(5); - expect(emojiUsage("s")("unicode/rocket")).toBe(3); - } finally { - vi.unstubAllGlobals(); - } - }, -); - it("counts each choice against the latest history, keeping other windows' choices", () => { recordEmojiUsage("wss://relay.test/a", "unicode/smirk"); // Another window chooses from the same storage. localStorage.setItem( - "emoji-mart.frequently", + "buzz.emoji-usage.v1", JSON.stringify({ ...stored(), rocket: 1 }), ); recordEmojiUsage("wss://relay.test/a", "custom/party"); @@ -110,7 +80,7 @@ it("counts each choice against the latest history, keeping other windows' choice expect(localStorage.getItem("emoji-mart.last")).toBe('"smirk"'); // Unreadable history starts over rather than blocking choices. for (const value of ["[1,2]", "null", "garbage"]) { - localStorage.setItem("emoji-mart.frequently", value); + localStorage.setItem("buzz.emoji-usage.v1", value); addEmojiUsage("smirk"); expect(stored()).toEqual({ smirk: 1 }); } @@ -127,7 +97,7 @@ it("orders the Frequently used row like Mart, filling a first row with defaults" expect(row(2)).toEqual(["+1", "grinning"]); expect(row(2, 0)).toEqual([]); localStorage.setItem( - "emoji-mart.frequently", + "buzz.emoji-usage.v1", JSON.stringify({ b: 2, a: 2, c: 5, hidden: 9, seeded: 0.5, joy: 1 }), ); // Ties sort by ID; unshown and unchosen entries are skipped. diff --git a/src/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts index d6d5a57c39..54baabf1fe 100644 --- a/src/bundled/emoji/emoji-usage.ts +++ b/src/bundled/emoji/emoji-usage.ts @@ -1,13 +1,14 @@ -// Picker and autocomplete share one usage history under Emoji Mart's storage -// key: it fills the picker's Frequently used row and ranks colon suggestions. -// It is read fresh on every use, so each window keeps the others' choices. -const STORE = "emoji-mart.frequently"; +// Picker and autocomplete share one usage history: it fills the picker's +// Frequently used row and ranks colon suggestions. It is read fresh on every +// use, so each window keeps the others' choices. +const STORE = "buzz.emoji-usage.v1"; const LAST = "emoji-mart.last"; -const SEED_REMOVED = "buzz.emoji-usage.seed-removed"; -// Emoji Mart 5.6 seeded a new history with these defaults at perLine - i, as -// if chosen, and saved them with the first pick. Copied so that suggestions do -// not load Mart. -const MART_SEED = [ +// Until Buzz records a pick, the history is Emoji Mart's, which Buzz never +// rewrites. Mart 5.6 stored these defaults as if chosen, and pruning makes +// them indistinguishable from real picks, so they are left out. Copied so +// that suggestions do not load Mart. +const MART_STORE = "emoji-mart.frequently"; +const MART_DEFAULTS = [ "+1", "grinning", "kissing_heart", @@ -37,45 +38,28 @@ function usageId(scope: string, id: string) { return undefined; } -function readCounts(): Record { - let counts: Record = {}; +function parseCounts(raw: string | null) { try { - const stored: unknown = JSON.parse(localStorage.getItem(STORE) ?? "{}"); + const stored: unknown = JSON.parse(raw ?? "null"); if (stored && typeof stored === "object" && !Array.isArray(stored)) - counts = stored as Record; - } catch { - /* Without storage, nothing has been chosen. */ - } - try { - if (localStorage.getItem(SEED_REMOVED) === null) { - // Marker first: a failed write can leave the seed, never subtract twice. - localStorage.setItem(SEED_REMOVED, "1"); - if (removeMartSeed(counts)) - localStorage.setItem(STORE, JSON.stringify(counts)); - } + return stored as Record; } catch { - /* Without the marker, the seed stays counted until a later read. */ + /* Unreadable history means nothing has been chosen. */ } - return counts; + return {}; } -/** Subtracts Mart's seed once, keeping the picks made on top of it. The seed - * width is unknown, so take the widest run every count can contain. */ -function removeMartSeed(counts: Record) { - const count = (i: number) => uses(counts, MART_SEED[i] ?? ""); - let width = 0; - for (let size = 1; size <= MART_SEED.length; size++) { - let fits = true; - for (let i = 0; i < size && fits; i++) fits = count(i) >= size - i; - if (fits) width = size; - } - for (let i = 0; i < width; i++) { - const id = MART_SEED[i] ?? ""; - const left = count(i) - (width - i); - if (left > 0) counts[id] = left; - else delete counts[id]; +function readCounts(): Record { + try { + const raw = localStorage.getItem(STORE); + if (raw !== null) return parseCounts(raw); + const counts = parseCounts(localStorage.getItem(MART_STORE)); + for (const id of MART_DEFAULTS) delete counts[id]; + return counts; + } catch { + /* Without storage, nothing has been chosen. */ } - return width > 0; + return {}; } function uses(counts: Record, key: string) { diff --git a/tests/browser/emoji-frequency.spec.mjs b/tests/browser/emoji-frequency.spec.mjs index d6bf67f0e8..e48478664a 100644 --- a/tests/browser/emoji-frequency.spec.mjs +++ b/tests/browser/emoji-frequency.spec.mjs @@ -35,7 +35,7 @@ test("emoji chosen in the picker or suggestions rise in both, after reload too", }; const counts = () => page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), ); const closePicker = async () => { await page.keyboard.press("Escape"); @@ -140,7 +140,7 @@ test("choices in two windows of one profile keep each other", async ({ await expect .poll(() => page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), ), ) .toEqual({ smirk: 1, rocket: 1, tada: 1 }); @@ -154,7 +154,7 @@ test("emoji a full composer cannot insert teach nothing", async ({ page }) => { const search = page.getByRole("searchbox", { name: "Search emoji" }); const counts = () => page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), ); const pickRocket = async () => { await page @@ -194,7 +194,7 @@ test("choosing an existing reaction removes it and teaches nothing", async ({ const pill = row.locator('button[data-reaction="🚀"]'); const counts = () => page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), ); const actions = row .getByRole("group", { name: "Message actions", includeHidden: true }) diff --git a/tests/browser/emoji.spec.mjs b/tests/browser/emoji.spec.mjs index 6db4ce1bfb..a053b4938b 100644 --- a/tests/browser/emoji.spec.mjs +++ b/tests/browser/emoji.spec.mjs @@ -1356,7 +1356,7 @@ test("the first toned pick asks for a default skin tone", async ({ page }) => { page.evaluate(() => localStorage.getItem("emoji-mart.skin")); const usage = () => page.evaluate(() => - JSON.parse(localStorage.getItem("emoji-mart.frequently") ?? "{}"), + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), ); const grid = (label) => page