Skip to content

Edge-Drop is a clipboard shelf on the edge of your screen. Hover to open it. Drag files and images into any app, click to copy text and links. Free and open-source for Windows.

perf(emoji): load picker glyphs a screen at a time to stop category-bar stutter

Deepender256febbb5a1af9
diff --git a/electron/main/imageProtocol.ts b/electron/main/imageProtocol.ts
index 3dbca9c..da4073d 100644
--- a/electron/main/imageProtocol.ts
+++ b/electron/main/imageProtocol.ts
@@ -1,4 +1,5 @@
import { existsSync, readdirSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
import { basename, dirname, extname, join, resolve } from 'node:path'
import { APP_CONFIG } from './config'
@@ -75,6 +76,33 @@ export function resolveEmojiAsset(assetDir: string, fileName: string): string |
return filePath
}
+/** Most glyphs one readEmojiBatch call returns (a screen is ~80-370). */
+export const EMOJI_BATCH_MAX = 400
+
+/**
+ * Read many picker glyphs at once: valid file name -> base64 PNG. Names go
+ * through resolveEmojiAsset (same allowlist and directory check as the
+ * protocol route); invalid or missing names are left out. Reads run in
+ * parallel off the main thread.
+ */
+export async function readEmojiBatch(assetDir: string, names: readonly unknown[]): Promise<Record<string, string>> {
+ const out: Record<string, string> = {}
+ if (!Array.isArray(names)) return out
+ const unique = [...new Set(names.filter((n): n is string => typeof n === 'string').map((n) => n.toLowerCase()))]
+ await Promise.all(
+ unique.slice(0, EMOJI_BATCH_MAX).map(async (name) => {
+ const filePath = resolveEmojiAsset(assetDir, name)
+ if (!filePath) return
+ try {
+ out[name] = (await readFile(filePath)).toString('base64')
+ } catch {
+ /* unreadable: leave it out */
+ }
+ })
+ )
+ return out
+}
+
/**
* File-kind folder icons (PNG, resources/file-icons). Fixed 13-name
* allowlist so the protocol cannot escape the icon directory — same
diff --git a/electron/main/ipc.ts b/electron/main/ipc.ts
index f657110..29aa334 100644
--- a/electron/main/ipc.ts
+++ b/electron/main/ipc.ts
@@ -25,6 +25,7 @@ import { isStoreBuild } from './config'
import { applyLaunchAtLogin, refreshLaunchAtLoginFromOs } from './loginItems'
import { toUnpackagedFilePath, toUnpackagedFilePaths } from '../store/paths'
import { isPasteableEmoji } from '../../shared/emoji'
+import { emojiAssetDir, readEmojiBatch } from './imageProtocol'
export { isStoreBuild }
@@ -525,6 +526,13 @@ export function registerIpc(): void {
return true
})
+ handle('emoji:glyphs', (files) =>
+ readEmojiBatch(
+ emojiAssetDir({ packaged: app.isPackaged, resourcesPath: process.resourcesPath, appPath: app.getAppPath(), cwd: process.cwd() }),
+ files
+ )
+ )
+
handle('emoji:paste', async (text) => {
if (!isPasteableEmoji(text)) return false
const now = Date.now()
diff --git a/electron/preload/index.ts b/electron/preload/index.ts
index 3d987b6..c6853aa 100644
--- a/electron/preload/index.ts
+++ b/electron/preload/index.ts
@@ -188,6 +188,7 @@ const api = {
pasteItem: (id: string) => invoke('item:paste', id),
pasteSubitem: (req: import('../../shared/types').DragRequest) => invoke('item:paste-subitem', req),
pasteEmoji: (text: string) => invoke('emoji:paste', text),
+ emojiGlyphs: (files: string[]) => invoke('emoji:glyphs', files),
installUpdate: () => invoke('app:install-update'),
checkForUpdatesManual: () => invoke('updater:check-manual'),
startUpdateDownload: () => invoke('updater:start-download'),
diff --git a/shared/bridge.ts b/shared/bridge.ts
index e9297db..770995b 100644
--- a/shared/bridge.ts
+++ b/shared/bridge.ts
@@ -33,6 +33,7 @@ export interface EdgeApi {
pasteItem: (id: string) => Promise<boolean>
pasteSubitem: (req: DragRequest) => Promise<boolean>
pasteEmoji: (text: string) => Promise<boolean>
+ emojiGlyphs: (files: string[]) => Promise<Record<string, string>>
installUpdate: () => Promise<void>
checkForUpdatesManual: () => Promise<{ status: string; version?: string; error?: string }>
startUpdateDownload: () => Promise<void>
diff --git a/shared/ipc.ts b/shared/ipc.ts
index 10c67f0..30f8979 100644
--- a/shared/ipc.ts
+++ b/shared/ipc.ts
@@ -53,6 +53,14 @@ export interface InvokeMap {
/** Write a Unicode emoji to the clipboard and Ctrl+V into the still-focused app. Does not close the shelf. */
'emoji:paste': { args: [text: string]; result: boolean }
+ /**
+ * Picker glyph PNGs, many per call: file name -> base64 PNG. One call per
+ * screen of the grid instead of one image request per glyph (each costs
+ * main-thread time that delays this window's frames). Unknown names are
+ * left out.
+ */
+ 'emoji:glyphs': { args: [files: string[]]; result: Record<string, string> }
+
/** Add local file paths dragged into the shelf. */
'item:add-files': { args: [paths: string[]]; result: ClipboardItemDto[] }
diff --git a/src/App.tsx b/src/App.tsx
index 87c4a87..056a798 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -61,38 +61,20 @@ export default function App() {
} catch { /* ignore */ }
// 2. Emoji catalog JSON parse + build — cached in load.ts `pending`
// so the first emoji click reuses it instead of parsing on click.
- // Then pre-warm the first screen of the default (smileys) category:
- // ~48 glyph PNGs fetched through the same edgelocal:// URLs the grid
- // uses, so the click finds warm main-process stats + Chromium cache
- // instead of causing a ~100-file burst. Same images, same cache —
- // just filled idle instead of on click.
+ // Then pre-warm the first screen of the page the picker opens on
+ // (recents when there are any, otherwise smileys — same rule as
+ // setEmojiOpen): up to 48 glyphs in one call, kept by glyphCache so
+ // they are still loaded when the picker opens, however much later
+ // that is. Same images, just loaded idle instead of on click.
try {
- void Promise.all([import('./lib/emoji/load'), import('./lib/emoji/catalog')])
- .then(([loadMod, catalogMod]) =>
+ void Promise.all([import('./lib/emoji/load'), import('./lib/emoji/catalog'), import('./lib/emoji/glyphCache'), import('./lib/emoji/prefs')])
+ .then(([loadMod, catalogMod, cacheMod, prefsMod]) =>
loadMod.loadEmojiCatalog().then((catalog) => {
if (cancelled || !catalog) return
try {
- const smileys = catalogMod.CATEGORY_ORDER.find((c) => c.id === 'smileys')
- const sources = (smileys as { sources?: readonly string[] } | undefined)?.sources ?? []
- const files: string[] = []
- for (const src of sources) {
- const list = (catalog.byCategory as Record<string, Array<{ file?: string }>>)[src] ?? []
- for (const entry of list) {
- if (typeof entry?.file === 'string' && entry.file) files.push(entry.file)
- if (files.length >= 48) break
- }
- if (files.length >= 48) break
- }
- const ImgCtor = (globalThis as any)?.Image
- if (typeof ImgCtor !== 'function') return
- for (const file of files) {
- if (cancelled) break
- try {
- const im = new ImgCtor() as HTMLImageElement
- try { (im as any).decoding = 'async' } catch { /* ignore */ }
- im.src = catalogMod.emojiGlyphUrl(file)
- } catch { /* ignore */ }
- }
+ const recents = prefsMod.loadRecents()
+ const landing = recents.length > 0 ? 'recents' : 'smileys'
+ cacheMod.loadGlyphs(catalogMod.entriesForCategory(catalog, landing, recents).slice(0, 48).map((item) => item.file))
} catch { /* ignore */ }
}).catch(() => undefined)
)
diff --git a/src/components/EmojiCategoryBar.tsx b/src/components/EmojiCategoryBar.tsx
index c8e46a2..256bae7 100644
--- a/src/components/EmojiCategoryBar.tsx
+++ b/src/components/EmojiCategoryBar.tsx
@@ -1,8 +1,11 @@
-import { useCallback, useMemo, useState, useEffect } from 'react'
+import { memo, useCallback, useMemo, useRef, useState, useEffect } from 'react'
import {
CATEGORY_ORDER,
+ entriesForCategory,
type EmojiCategoryId
} from '../lib/emoji/catalog'
+import { loadGlyphs, screenGlyphCount } from '../lib/emoji/glyphCache'
+import { peekEmojiCatalog } from '../lib/emoji/load'
import { loadRecents } from '../lib/emoji/prefs'
import { useStore } from '../store/appStore'
import { playButtonClickSound } from '../lib/soundEffects'
@@ -37,11 +40,12 @@ export interface EmojiCategoryBarProps {
/** Which dock the bar is in. The control is the same size in both. */
isHorizontal?: boolean
className?: string
- /** Hover-intent hook: warm a category's first screen before it's clicked. */
- onHoverCategory?: (id: EmojiCategoryId) => void
}
-export function EmojiCategoryBar({ className = '', onHoverCategory }: EmojiCategoryBarProps) {
+/** How long the pointer must rest on a category before its glyphs are warmed. */
+const WARM_DWELL_MS = 80
+
+function CategoryBar({ className = '' }: EmojiCategoryBarProps) {
const { t } = useTranslation()
const category = useStore((s) => s.emojiCategory)
const setCategory = useStore((s) => s.setEmojiCategory)
@@ -67,8 +71,37 @@ export function EmojiCategoryBar({ className = '', onHoverCategory }: EmojiCateg
const reduceMotion = useStore((s) => !!s.settings.reduceMotion)
+ // Hover warm-up: when the pointer rests on a category, load its first
+ // screen of glyphs (one call, kept by glyphCache) so the click shows them
+ // at once. The short dwell skips categories the pointer only passes over.
+ const warmTimer = useRef<number | null>(null)
+ const cancelWarm = useCallback(() => {
+ if (warmTimer.current === null) return
+ window.clearTimeout(warmTimer.current)
+ warmTimer.current = null
+ }, [])
+ const warmOnRest = useCallback(
+ (id: EmojiCategoryId) => {
+ cancelWarm()
+ if (id === useStore.getState().emojiCategory) return
+ warmTimer.current = window.setTimeout(() => {
+ warmTimer.current = null
+ const catalog = peekEmojiCatalog()
+ if (!catalog || id === useStore.getState().emojiCategory) return
+ loadGlyphs(entriesForCategory(catalog, id, loadRecents()).slice(0, screenGlyphCount()).map((item) => item.file))
+ }, WARM_DWELL_MS)
+ },
+ [cancelWarm]
+ )
+ useEffect(() => cancelWarm, [cancelWarm])
+
return (
- <div className={`emoji-cat-bar${className ? ` ${className}` : ''}`} style={{ margin: 0 }}>
+ <div
+ className={`emoji-cat-bar${className ? ` ${className}` : ''}`}
+ style={{ margin: 0 }}
+ onPointerLeave={cancelWarm}
+ onPointerDown={cancelWarm}
+ >
<SegmentedControl
items={shownCats.map((c) => {
const Icon = CATEGORY_ICONS[c.id]
@@ -76,7 +109,7 @@ export function EmojiCategoryBar({ className = '', onHoverCategory }: EmojiCateg
})}
value={category}
onChange={(val) => selectCategory(val)}
- onHoverItem={onHoverCategory}
+ onHoverItem={warmOnRest}
ariaLabel={t('emoji.categories')}
reduceMotion={reduceMotion}
/>
@@ -84,4 +117,8 @@ export function EmojiCategoryBar({ className = '', onHoverCategory }: EmojiCateg
)
}
+// Memoised: the picker re-renders every frame while its grid fills in after
+// a switch; the bar only needs to when its own props or store values change.
+export const EmojiCategoryBar = memo(CategoryBar)
+
export default EmojiCategoryBar
diff --git a/src/components/EmojiPicker.tsx b/src/components/EmojiPicker.tsx
index 3173664..410255c 100644
--- a/src/components/EmojiPicker.tsx
+++ b/src/components/EmojiPicker.tsx
@@ -2,18 +2,17 @@
* Unicode emoji library. Glyphs are Twemoji; paste is the character itself.
* No text field — categories + click — so the shelf never takes OS focus.
*/
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import {
- emojiGlyphUrl,
entriesForCategory,
hasSkinTones,
pushRecent,
skinChoices,
unifiedToNative,
type EmojiCatalog,
- type EmojiCategoryId,
type EmojiEntry
} from '../lib/emoji/catalog'
+import { glyphSrc, glyphsVersion, loadGlyphs, setScreenGlyphCount, subscribeGlyphs } from '../lib/emoji/glyphCache'
import { loadEmojiCatalog } from '../lib/emoji/load'
import { loadRecents, saveRecents } from '../lib/emoji/prefs'
import { useStore } from '../store/appStore'
@@ -36,10 +35,16 @@ interface TonePopup {
}
function Glyph({ file, size = 22 }: { file: string; size?: number }) {
+ // Loaded a screen at a time (glyphCache); no src until its batch lands.
+ // Once shown, a glyph keeps its image even if the cache later drops it.
+ const shown = useRef<{ file: string; src?: string }>({ file })
+ if (shown.current.file !== file) shown.current = { file }
+ const src = glyphSrc(file) ?? shown.current.src
+ shown.current.src = src
return (
<img
className="emoji-glyph"
- src={emojiGlyphUrl(file)}
+ src={src}
alt=""
width={size}
height={size}
@@ -85,17 +90,10 @@ export function EmojiPicker({
// always the image mount burst, which the row budget below spreads out.
useEffect(() => {
let alive = true
- // TEMP-DIAG-EMOJI (remove after diagnosis): stage timings.
- const tMount = performance.now()
loadEmojiCatalog()
.then((c) => {
if (!alive) return
- const tLoaded = performance.now()
setCatalog(c)
- requestAnimationFrame(() => {
- // eslint-disable-next-line no-console
- console.log(`[EmojiPerf] mountToLoadStart=~0ms load=${(tLoaded - tMount).toFixed(1)}ms loadToPaint=${(performance.now() - tLoaded).toFixed(1)}ms`)
- })
if (loadRecents().length > 0 && category === 'smileys') {
setCategory('recents')
}
@@ -161,33 +159,6 @@ export function EmojiPicker({
return entriesForCategory(catalog, category, recents)
}, [catalog, category, recents])
- // Hover-intent preload: while the user aims at a category button (no
- // animation running), decode its first screen into the image cache so the
- // click lands warm. Capped and deduped; keyboard/touch users without hover
- // are still covered by the fetch-budget ramp below. Never prefetches the
- // active category (already mounted).
- const warmedCats = useRef<Set<string>>(new Set())
- const preloadCategory = useCallback(
- (id: EmojiCategoryId) => {
- if (id === category || !catalog) return
- if (warmedCats.current.has(id)) return
- warmedCats.current.add(id)
- try {
- const first = entriesForCategory(catalog, id, recents).slice(0, 28)
- const ImgCtor = (globalThis as any)?.Image
- if (typeof ImgCtor !== 'function') return
- for (const item of first) {
- try {
- const im = new ImgCtor() as HTMLImageElement
- try { (im as any).decoding = 'async' } catch { /* ignore */ }
- im.src = emojiGlyphUrl(item.file)
- } catch { /* ignore */ }
- }
- } catch { /* ignore */ }
- },
- [catalog, category, recents]
- )
-
const cols = useMemo(() => {
if (!isHorizontal) return COLS
if (viewW <= 0) return 24
@@ -197,6 +168,14 @@ export function EmojiPicker({
const rowH = isHorizontal ? 32 : ROW_H
const glyphSize = isHorizontal ? 22 : 26
+ // Tell the category bar's hover warm-up how many glyphs fill one screen.
+ useEffect(() => {
+ setScreenGlyphCount(cols * Math.ceil(viewH / rowH))
+ }, [cols, viewH, rowH])
+
+ // Re-render when a batch of glyphs lands.
+ useSyncExternalStore(subscribeGlyphs, glyphsVersion)
+
const rows = Math.ceil(items.length / cols)
// First paint mounts a tight window (fewer images fighting for decode),
// then widens to full overscan on the next frame for scroll smoothness.
@@ -236,6 +215,17 @@ export function EmojiPicker({
}, [catalog, windowRows, rowBudget])
const effEndRow = Math.min(endRow, startRow + rowBudget)
+ // The whole window's glyphs in one call, as soon as the window is known
+ // (not row by row with the mount ramp above).
+ useEffect(() => {
+ if (!catalog || !active) return
+ loadGlyphs(items.slice(startRow * cols, endRow * cols).map((item) => item.file))
+ }, [catalog, active, items, startRow, endRow, cols])
+
+ useEffect(() => {
+ if (tonePop) loadGlyphs(skinChoices(tonePop.entry).map((choice) => choice.file))
+ }, [tonePop])
+
const onPaste = useCallback(
(unified: string) => {
const now = Date.now()
@@ -273,7 +263,7 @@ export function EmojiPicker({
if (!t.closest('[data-tone-popup], [data-has-skins]')) setTonePop(null)
}}
>
- {!isHorizontal && <EmojiCategoryBar isHorizontal={false} onHoverCategory={preloadCategory} />}
+ {!isHorizontal && <EmojiCategoryBar isHorizontal={false} />}
{failed ? (
<div className="emoji-status">{t('emoji.loadFailed')}</div>
diff --git a/src/lib/emoji/glyphCache.ts b/src/lib/emoji/glyphCache.ts
new file mode 100644
index 0000000..3fbe351
--- /dev/null
+++ b/src/lib/emoji/glyphCache.ts
@@ -0,0 +1,99 @@
+/**
+ * Emoji glyph images for the picker, loaded a screen at a time.
+ *
+ * Every image request through the edgelocal:// protocol costs ~1.7ms on the
+ * main process's UI thread, the same thread that puts this transparent
+ * window's frames on screen. A category switch shows ~90-170 new glyphs, so
+ * one request each kept that thread busy for most of the category bar's
+ * thumb slide, and the thumb stuttered. Chromium also forgets an image once
+ * no element shows it, so every revisit asked again.
+ *
+ * Instead, glyphs are fetched with one IPC call per screen (emoji:glyphs)
+ * and kept as data: URLs: only the small PNG file as text (~3.6KB each).
+ * Decoded pixels are still freed when a glyph leaves the screen. An <img>
+ * with a data: URL needs nothing from the main process.
+ *
+ * The cap keeps this under ~3MB. It must stay above what can be on screen
+ * at once (a top-dock window with overscan is ~340 glyphs) plus a
+ * hover-warmed screen, since a glyph dropped while shown would lose its
+ * image. Beyond that, a revisit to a dropped category is one more call.
+ */
+import { edge } from '../edge'
+import { emojiGlyphUrl } from './catalog'
+
+export const GLYPH_CACHE_CAP = 800
+/** Glyphs per IPC call (EMOJI_BATCH_MAX in the main process). */
+const BATCH = 400
+
+const srcs = new Map<string, string>()
+const inflight = new Set<string>()
+const listeners = new Set<() => void>()
+let version = 0
+
+/** The glyph's image URL once loaded, otherwise undefined. */
+export function glyphSrc(file: string): string | undefined {
+ return srcs.get(file)
+}
+
+/** Load the glyphs not loaded yet (one call per BATCH) and mark all as recently used. */
+export function loadGlyphs(files: readonly string[]): void {
+ const want: string[] = []
+ for (const file of files) {
+ const src = srcs.get(file)
+ if (src !== undefined) {
+ srcs.delete(file)
+ srcs.set(file, src)
+ continue
+ }
+ if (inflight.has(file)) continue
+ inflight.add(file)
+ want.push(file)
+ }
+ for (let i = 0; i < want.length; i += BATCH) void fetchBatch(want.slice(i, i + BATCH))
+}
+
+async function fetchBatch(files: string[]): Promise<void> {
+ let got: Record<string, string> | undefined
+ try {
+ const pending = edge.emojiGlyphs(files) as Promise<Record<string, string>> | undefined
+ got = pending && typeof pending.then === 'function' ? await pending : undefined
+ } catch {
+ got = undefined
+ }
+ for (const file of files) {
+ inflight.delete(file)
+ const b64 = got?.[file]
+ // No answer for it: fall back to the per-file protocol URL so it still shows.
+ srcs.set(file, b64 ? `data:image/png;base64,${b64}` : emojiGlyphUrl(file))
+ }
+ while (srcs.size > GLYPH_CACHE_CAP) {
+ const oldest = srcs.keys().next().value
+ if (oldest === undefined) break
+ srcs.delete(oldest)
+ }
+ version++
+ for (const listener of listeners) listener()
+}
+
+/** useSyncExternalStore pair: re-render when a batch lands. */
+export function subscribeGlyphs(listener: () => void): () => void {
+ listeners.add(listener)
+ return () => {
+ listeners.delete(listener)
+ }
+}
+
+export function glyphsVersion(): number {
+ return version
+}
+
+let screenGlyphs = 48
+
+/** How many glyphs one screen of the grid shows (the picker keeps this current). */
+export function setScreenGlyphCount(n: number): void {
+ if (Number.isFinite(n) && n > 0) screenGlyphs = Math.min(BATCH, Math.ceil(n))
+}
+
+export function screenGlyphCount(): number {
+ return screenGlyphs
+}
diff --git a/src/styles/emoji.css b/src/styles/emoji.css
index a28cd63..aa1926b 100644
--- a/src/styles/emoji.css
+++ b/src/styles/emoji.css
@@ -62,7 +62,9 @@
padding: 0;
color: inherit;
position: relative;
- transform: translateZ(0);
+ /* No forced layer (translateZ): one compositor layer per cell (130-340 of
+ them) made every grid update costlier. The hover/press scale still runs
+ on the compositor while it animates. */
transition: transform 0.14s cubic-bezier(0.22, 1, 0.36, 1),
background 0.14s cubic-bezier(0.22, 1, 0.36, 1);
-webkit-user-drag: none;
diff --git a/tests/emojiGlyphs.test.ts b/tests/emojiGlyphs.test.ts
new file mode 100644
index 0000000..13d0e9c
--- /dev/null
+++ b/tests/emojiGlyphs.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { EMOJI_BATCH_MAX, readEmojiBatch } from '../electron/main/imageProtocol'
+
+const read = (p: string) => readFileSync(join(__dirname, '..', p), 'utf8')
+
+describe('readEmojiBatch (main)', () => {
+ const dir = join(tmpdir(), `ed-emoji-batch-${process.pid}`)
+ beforeEach(() => {
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(join(dir, '1f600.png'), 'smile')
+ writeFileSync(join(dir, '1f44b-1f3fb.png'), 'wave')
+ writeFileSync(join(dir, 'secret.txt'), 'no')
+ })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+
+ it('returns base64 PNGs for valid names and leaves out everything else', async () => {
+ const out = await readEmojiBatch(dir, ['1f600.png', '1F44B-1F3FB.PNG', 'missing.png', '../secret.txt', 'secret.txt', 42, null])
+ expect(out).toEqual({
+ '1f600.png': Buffer.from('smile').toString('base64'),
+ '1f44b-1f3fb.png': Buffer.from('wave').toString('base64')
+ })
+ })
+
+ it('ignores a non-array payload and caps one call', async () => {
+ expect(await readEmojiBatch(dir, 'nope' as unknown as string[])).toEqual({})
+ const many = Array.from({ length: EMOJI_BATCH_MAX + 50 }, () => '1f600.png')
+ expect(Object.keys(await readEmojiBatch(dir, many))).toEqual(['1f600.png'])
+ })
+})
+
+describe('glyph cache (renderer)', () => {
+ let calls: string[][]
+ let answer: (files: string[]) => Promise<Record<string, string>> | undefined
+
+ beforeEach(() => {
+ vi.resetModules()
+ calls = []
+ answer = (files) => Promise.resolve(Object.fromEntries(files.map((f) => [f, `b64-${f}`])))
+ ;(globalThis as { window?: unknown }).window = {
+ edge: {
+ emojiGlyphs: (files: string[]) => {
+ calls.push(files)
+ return answer(files)
+ }
+ }
+ }
+ })
+ afterEach(() => {
+ delete (globalThis as { window?: unknown }).window
+ })
+
+ const flush = () => new Promise((r) => setTimeout(r, 0))
+
+ it('loads a screen in one call, as data: URLs, and never asks twice', async () => {
+ const g = await import('../src/lib/emoji/glyphCache')
+ const seen: number[] = []
+ g.subscribeGlyphs(() => seen.push(g.glyphsVersion()))
+ g.loadGlyphs(['a.png', 'b.png'])
+ g.loadGlyphs(['a.png', 'b.png']) // in flight: no second call
+ expect(calls).toEqual([['a.png', 'b.png']])
+ expect(g.glyphSrc('a.png')).toBeUndefined()
+ await flush()
+ expect(g.glyphSrc('a.png')).toBe('data:image/png;base64,b64-a.png')
+ expect(seen).toEqual([1])
+ g.loadGlyphs(['a.png', 'b.png', 'c.png'])
+ expect(calls[1]).toEqual(['c.png'])
+ })
+
+ it('splits big requests into batches of 400', async () => {
+ const g = await import('../src/lib/emoji/glyphCache')
+ g.loadGlyphs(Array.from({ length: 900 }, (_, i) => `${i}.png`))
+ expect(calls.map((c) => c.length)).toEqual([400, 400, 100])
+ })
+
+ it('falls back to the per-file protocol URL when the call fails or omits a glyph', async () => {
+ answer = (files) => (files[0] === 'x.png' ? Promise.reject(new Error('down')) : Promise.resolve({}))
+ const g = await import('../src/lib/emoji/glyphCache')
+ g.loadGlyphs(['x.png'])
+ g.loadGlyphs(['y.png'])
+ await flush()
+ expect(g.glyphSrc('x.png')).toBe('edgelocal://emoji/x.png')
+ expect(g.glyphSrc('y.png')).toBe('edgelocal://emoji/y.png')
+ })
+
+ it('drops the least recently used glyphs past the cap', async () => {
+ const g = await import('../src/lib/emoji/glyphCache')
+ const first = Array.from({ length: g.GLYPH_CACHE_CAP }, (_, i) => `${i}.png`)
+ for (let i = 0; i < first.length; i += 400) {
+ g.loadGlyphs(first.slice(i, i + 400))
+ await flush()
+ }
+ g.loadGlyphs(['0.png']) // touch: now most recent
+ g.loadGlyphs(['new.png'])
+ await flush()
+ expect(g.glyphSrc('0.png')).toBeDefined()
+ expect(g.glyphSrc('1.png')).toBeUndefined()
+ expect(g.glyphSrc('new.png')).toBeDefined()
+ })
+
+ it('caps the screen size used for hover warm-up to one call', async () => {
+ const g = await import('../src/lib/emoji/glyphCache')
+ g.setScreenGlyphCount(168)
+ expect(g.screenGlyphCount()).toBe(168)
+ g.setScreenGlyphCount(5000)
+ expect(g.screenGlyphCount()).toBe(400)
+ g.setScreenGlyphCount(NaN)
+ expect(g.screenGlyphCount()).toBe(400)
+ })
+})
+
+describe('emoji picker wiring', () => {
+ it('exposes emoji:glyphs through the shared contract, preload and main', () => {
+ expect(read('shared/ipc.ts')).toContain("'emoji:glyphs': { args: [files: string[]]; result: Record<string, string> }")
+ expect(read('shared/bridge.ts')).toContain('emojiGlyphs: (files: string[]) => Promise<Record<string, string>>')
+ expect(read('electron/preload/index.ts')).toContain("emojiGlyphs: (files: string[]) => invoke('emoji:glyphs', files)")
+ expect(read('electron/main/ipc.ts')).toMatch(/handle\('emoji:glyphs'[\s\S]*?readEmojiBatch\(/)
+ })
+
+ it('grid glyphs come from the cache and keep their image once shown', () => {
+ const src = read('src/components/EmojiPicker.tsx')
+ expect(src).toContain('src={src}')
+ expect(src).toContain('const src = glyphSrc(file) ?? shown.current.src')
+ expect(src).toContain('loadGlyphs(items.slice(startRow * cols, endRow * cols)')
+ expect(src).not.toContain('emojiGlyphUrl(')
+ })
+
+ it('category bar is memoised and warms on a hover rest', () => {
+ const src = read('src/components/EmojiCategoryBar.tsx')
+ expect(src).toContain('export const EmojiCategoryBar = memo(CategoryBar)')
+ expect(src).toContain('onHoverItem={warmOnRest}')
+ expect(src).toContain('onPointerLeave={cancelWarm}')
+ })
+
+ it('emoji cells do not force a compositor layer each', () => {
+ expect(read('src/styles/emoji.css')).not.toMatch(/\.emoji-cell \{[^}]*transform:\s*translateZ/)
+ })
+})