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/EmojiPicker.tsx b/src/bundled/emoji/EmojiPicker.tsx index 54ef7e00c9..1f68465993 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 choice is rejected or must not count as a use. */ + 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/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/bundled/emoji/emoji-mart.ts b/src/bundled/emoji/emoji-mart.ts index 3db240fb45..ab3f15cef7 100644 --- a/src/bundled/emoji/emoji-mart.ts +++ b/src/bundled/emoji/emoji-mart.ts @@ -5,9 +5,10 @@ import { pickerIcons } from "../../shared/design-system/icons/svg"; // Emoji Mart config adapted from block/buzz's shared picker; see NOTICE.md. import data from "@emoji-mart/data"; import english from "@emoji-mart/data/i18n/en.json"; -import { Data, Picker, SearchIndex } from "emoji-mart"; +import { Data, FrequentlyUsed, Picker, SearchIndex } from "emoji-mart"; import type { CustomEmoji } from "../../features/relay/emoji"; import { rankShortcodes } from "./emoji-search"; +import { addEmojiUsage, customEmojiId, frequentEmoji } from "./emoji-usage"; import { PREVIEW_ACTION_SLOT } from "./add-emoji"; import { SKIN_TONE_SLOT, @@ -32,10 +33,24 @@ function checkMartPropTimer(picker: HTMLElement) { "emoji-mart no longer exposes component.nextStateTimer; dispose() cannot cancel its deferred re-render", ); } +// Buzz owns usage history. Mart caches its copy per window, overwriting other +// windows' choices, and counts a pick before the tone prompt confirms it. +Object.assign(FrequentlyUsed, { + add() {}, + get(props: { maxFrequentRows: number; perLine: number }) { + // Mart fills this row last, after dropping from the other categories what + // this client cannot render or this picker does not offer. + const shown = new Set(); + for (const category of Data?.categories ?? []) + if (category.id !== "frequent") + for (const emoji of category.emojis) + shown.add(typeof emoji === "string" ? emoji : emoji.id); + return frequentEmoji(props, FrequentlyUsed.DEFAULTS, (id) => shown.has(id)); + }, +}); const resolvedTheme = (value: unknown): "light" | "dark" => value === "dark" ? "dark" : "light"; -const prefix = "buzz-custom/"; // Idle and with no matches, the footer shows only its actions; the empty grid // under the query already says nothing matched. const previewStrings = { @@ -113,7 +128,8 @@ export function mountEmojiMart({ searchChange(value: string): void; entries: readonly CustomEmoji[]; media(url: string): string | undefined; - select(value: string, customEmoji?: string): void; + /** Return false when the host rejects the insertion; it then does not count. */ + select(value: string, customEmoji?: string): unknown; close(): void; /** With `preview`, the footer's skin-tone action renders the saved tone (1–6). */ skinToneChange?(tone: number, open: boolean): void; @@ -124,7 +140,7 @@ export function mountEmojiMart({ const emojis = entries.flatMap(({ shortcode, url }) => { const src = media(url); if (!src) return []; - const id = `${prefix}${encodeURIComponent(scope)}/${shortcode}`; + const id = customEmojiId(scope, shortcode); const literal = `:${shortcode}:`; values.set(id, { literal, shortcode }); // Match Mart's first-hyphen query normalization as well as individual words. @@ -145,15 +161,6 @@ export function mountEmojiMart({ }, ]; }); - // Restore Mart's default Frequent row if storage contains a poisoned empty map. - try { - if (localStorage.getItem("emoji-mart.frequently") === "{}") { - localStorage.removeItem("emoji-mart.frequently"); - localStorage.removeItem("emoji-mart.last"); - } - } catch { - /* Like Mart, selection works without localStorage. */ - } const picker = new Picker({ data, custom: emojis.length @@ -190,12 +197,16 @@ export function mountEmojiMart({ ), onEmojiSelect: (emoji: { native?: string; id?: string }) => { if (disposed) return; + if (!emoji.id) return; if (emoji.native) { - if (!promptSkinTone(emoji.id)) select(emoji.native); + if (promptSkinTone(emoji.id)) return; + if (select(emoji.native) !== false) addEmojiUsage(emoji.id); return; } - const custom = values.get(emoji.id ?? ""); - if (custom) select(custom.literal, custom.shortcode); + const custom = values.get(emoji.id); + if (!custom) return; + if (select(custom.literal, custom.shortcode) !== false) + addEmojiUsage(emoji.id); }, }) as unknown as HTMLElement; // The documented web-component attribute updates in place: do not recreate the @@ -676,7 +687,7 @@ ${[1, 2, 3, 4, 5, 6].map((tone) => ` .menu .skin-tone-${tone}::before { conte const tone = chosenTone; const native = tone && Data?.emojis[id]?.skins[tone - 1]?.native; if (!native || disposed) return false; - select(native); + if (select(native) !== false) addEmojiUsage(id); return true; }; // Mart clears the preview whenever the pointer leaves an emoji, so crossing diff --git a/src/bundled/emoji/emoji-search.test.ts b/src/bundled/emoji/emoji-search.test.ts index 72a7a4ef34..aa685020f4 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,69 @@ it("copies native primitives even when Mart previously mutated the shared dictio }); it("Unicode completions use the picker's saved default skin tone", async () => { - const [hand] = await searchEmoji("call_me_hand", [], 1, 4); + const [hand] = await searchEmoji("call_me_hand", [], undefined, 1, 4); expect(hand?.text).toBe("🤙🏽"); vi.stubGlobal("localStorage", { getItem: (key: string) => (key === "emoji-mart.skin" ? "6" : null), }); try { - const [saved] = await searchEmoji("call_me_hand", [], 1); + const [saved] = await searchEmoji("call_me_hand", [], undefined, 1); expect(saved?.text).toBe("🤙🏿"); // Emoji without tones keep their only form. - const [rocket] = await searchEmoji("rocket", [], 1); + const [rocket] = await searchEmoji("rocket", [], undefined, 1); expect(rocket?.text).toBe("🚀"); } finally { vi.unstubAllGlobals(); } }); + +it("keeps alias and keyword matches ahead of often chosen fuzzy matches", async () => { + const first = async (query: string, uses?: (id: string) => number) => + (await searchEmoji(query, [], uses))[0]?.shortcode; + // `hate` and `poop` are a keyword of 😡 and an alias of 💩, and only + // subsequences of the chosen shortcodes. + for (const [query, fuzzy, match] of [ + ["hate", "unicode/heart_eyes", "rage"], + ["poop", "unicode/person_in_lotus_position", "hankey"], + ] as const) { + expect(await first(query)).toBe(match); + expect(await first(query, (id) => (id === fuzzy ? 8 : 0))).toBe(match); + } +}); + +it("puts often chosen emoji first within exact, prefix and other matches", async () => { + const shortcodes = async (query: string, uses?: (id: string) => number) => + (await searchEmoji(query, [], uses)).map((item) => item.shortcode); + const usage = (counts: Record) => (id: string) => + counts[id] ?? 0; + const plain = await shortcodes("sm"); + const smirk = await shortcodes("sm", usage({ "unicode/smirk": 2 })); + expect(smirk[0]).toBe("smirk"); + expect(smirk.slice(1)).toEqual(plain.filter((name) => name !== "smirk")); + // A strong use cannot lift a weaker match over a prefix match. + const sweat = await shortcodes("sm", usage({ "unicode/sweat_smile": 99 })); + expect(sweat.indexOf("sweat_smile")).toBeGreaterThan(sweat.indexOf("smiley")); + // The exact name stays first; equal counts keep the query order. + expect( + (await shortcodes("smile", usage({ "unicode/smiley": 5 }))).slice(0, 2), + ).toEqual(["smile", "smiley"]); + // The typed shortcode leads a separator-insensitive namesake used more. + expect( + (await shortcodes("icecream", usage({ "unicode/ice_cream": 9 })))[0], + ).toBe("icecream"); + expect( + (await shortcodes("ice_cream", usage({ "unicode/icecream": 9 })))[0], + ).toBe("ice_cream"); + expect( + await shortcodes("sm", usage({ "unicode/smile": 1, "unicode/smirk": 1 })), + ).toEqual(plain); + const custom = [ + { shortcode: "party", url: "https://a.test/party.png" }, + { shortcode: "parrot", url: "https://a.test/parrot.png" }, + ]; + expect( + searchCustomEmoji("par", custom, usage({ "custom/party": 1 })).map( + (item) => item.shortcode, + ), + ).toEqual(["party", "parrot"]); +}); diff --git a/src/bundled/emoji/emoji-search.ts b/src/bundled/emoji/emoji-search.ts index ea52cebacf..05c296941a 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,26 @@ function rankEmoji( .map(({ item }) => item) .filter((item) => !semanticIds.has(item.id)), ]; + const literal = query.toLowerCase(); const strong = rank(combined) .filter(({ tier }) => tier <= 1) - .map(({ item }) => item); - const promoted = new Set(strong.map((item) => item.id)); + // The typed shortcode itself leads its separator-insensitive namesakes. + .map((match) => + match.item.shortcode.toLowerCase() === literal + ? { ...match, tier: -1 } + : match, + ); + const promoted = new Set(strong.map(({ item }) => item.id)); const ranked = [ ...strong, - ...combined.filter((item) => !promoted.has(item.id)), - ]; + ...combined + .filter((item) => !promoted.has(item.id)) + .map((item) => ({ item, tier: semanticIds.has(item.id) ? 2 : 3 })), + ] + // Within literal, exact, prefix, name or keyword, and fuzzy matches, the more often + // chosen emoji comes first; ties and unused emoji keep their query order. + .sort((a, b) => a.tier - b.tier || uses(b.item.id) - uses(a.item.id)) + .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..3e398d0b60 --- /dev/null +++ b/src/bundled/emoji/emoji-usage.test.ts @@ -0,0 +1,135 @@ +// @vitest-environment jsdom +import data from "@emoji-mart/data"; +import { Data, FrequentlyUsed, init } from "emoji-mart"; +import { afterEach, expect, it } from "vitest"; +import "./emoji-mart"; +import { + addEmojiUsage, + customEmojiId, + emojiUsage, + frequentEmoji, + recordEmojiUsage, +} from "./emoji-usage"; + +const party = customEmojiId("wss://relay.test/a", "party"); +const stored = () => + 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( + "buzz.emoji-usage.v1", + JSON.stringify({ + smile: 3, + [party]: 2.5, + seeded: 0.9, + 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/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("buzz.emoji-usage.v1", '{"huge":1e400}'); + expect(emojiUsage("s")("unicode/huge")).toBe(0); + localStorage.setItem("buzz.emoji-usage.v1", "not json"); + expect(emojiUsage("wss://relay.test/a")("unicode/smile")).toBe(0); +}); + +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/+1")).toBe(0); + 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("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( + "buzz.emoji-usage.v1", + JSON.stringify({ ...stored(), rocket: 1 }), + ); + 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("buzz.emoji-usage.v1", value); + addEmojiUsage("smirk"); + expect(stored()).toEqual({ smirk: 1 }); + } +}); + +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( + "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. + 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"]); + // 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/bundled/emoji/emoji-usage.ts b/src/bundled/emoji/emoji-usage.ts new file mode 100644 index 0000000000..54baabf1fe --- /dev/null +++ b/src/bundled/emoji/emoji-usage.ts @@ -0,0 +1,126 @@ +// 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"; +// 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", + "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) => + `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; +} + +function parseCounts(raw: string | null) { + try { + const stored: unknown = JSON.parse(raw ?? "null"); + if (stored && typeof stored === "object" && !Array.isArray(stored)) + return stored as Record; + } catch { + /* Unreadable history means nothing has been chosen. */ + } + return {}; +} + +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 {}; +} + +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 { + const counts = readCounts(); + return (id) => { + const key = usageId(scope, id); + return key ? uses(counts, key) : 0; + }; +} + +/** 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) 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/features/conversation/ComposerCompletions.test.tsx b/src/features/conversation/ComposerCompletions.test.tsx index 60684f4e03..1c55b4ae66 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,6 +289,32 @@ it("ignores the agent flag from providers outside the bundled people providers", }); const folder = { kind: "folder", id: "/notes", label: "@notes" }; +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 }, + { 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 === true && bundled ? 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..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"; @@ -548,7 +550,14 @@ function OwnedCompletion({ current.current.replace(item.edit, source.query, observation, key), ); if (accepted) current.current.editor.invalidate(); - return accepted; + if (accepted === true) { + try { + item.onSelect?.(); + } catch { + /* A provider callback cannot undo the accepted edit. */ + } + } + return !!accepted; } useLayoutEffect(() => { const element = input.current; 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 dbb2c13c90..485f43a87f 100644 --- a/src/features/conversation/completion.ts +++ b/src/features/conversation/completion.ts @@ -183,6 +183,11 @@ export function completionResult( ...(typeof item.canSelect === "function" ? { canSelect: item.canSelect } : {}), + ...(typeof item.onSelect === "function" && + provider && + isBundledContribution(provider) + ? { onSelect: item.onSelect } + : {}), edit: host ? edit : Object.freeze( diff --git a/src/features/conversation/contracts.ts b/src/features/conversation/contracts.ts index 91bfd95caa..6284afcc82 100644 --- a/src/features/conversation/contracts.ts +++ b/src/features/conversation/contracts.ts @@ -114,6 +114,8 @@ export type ReactionToolProps = Readonly<{ disabled: boolean; /** 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; @@ -444,6 +446,8 @@ export type CompletionSuggestion = Readonly<{ disabled?: string | undefined; /** Final synchronous evidence check; false never falls through to sending. */ canSelect?: ((key: string) => boolean) | undefined; + /** Bundled providers only: called once after the host inserts this choice. */ + onSelect?: (() => void) | undefined; }>; export type CompletionResult = Readonly<{ items: readonly CompletionSuggestion[]; 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/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} /> 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 new file mode 100644 index 0000000000..e48478664a --- /dev/null +++ b/tests/browser/emoji-frequency.spec.mjs @@ -0,0 +1,231 @@ +import { hoverMessage } from "./message-actions.mjs"; +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 counts = () => + page.evaluate(() => + JSON.parse(localStorage.getItem("buzz.emoji-usage.v1") ?? "{}"), + ); + 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(); + // 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(), + ).toBeVisible(); + await page.keyboard.press("Enter"); + await expect(input).toHaveJSProperty("value", "😏 "); + // 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", "😏 "); + // 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", "😏 "); + + // 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 stored = await counts(); + expect(stored).toMatchObject({ + smirk: 3, + "buzz-custom/a/party-parrot-wave": 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); + await closePicker(); + + await page.reload(); + await input.fill(":sm"); + await expect(choices.first()).toHaveText(/:smirk:/); + 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([]); +}); + +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("buzz.emoji-usage.v1") ?? "{}"), + ), + ) + .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("buzz.emoji-usage.v1") ?? "{}"), + ); + 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([]); +}); + +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("buzz.emoji-usage.v1") ?? "{}"), + ); + 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 plus.click(); + await search.fill("rocket"); + await page + .locator('em-emoji-picker .category button[aria-label="🚀"]') + .first() + .click(); + await expect(search).toHaveCount(0); + }; + 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(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([]); +}); diff --git a/tests/browser/emoji.spec.mjs b/tests/browser/emoji.spec.mjs index 383619848c..a053b4938b 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("buzz.emoji-usage.v1") ?? "{}"), + ); 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();