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: eliminate cold-start animation jank, optimize emoji scroll, and boost startup/wake polling

Deepender25a2acee2c8458
diff --git a/electron/main/imageProtocol.ts b/electron/main/imageProtocol.ts
index 274c52a..a1a3ea5 100644
--- a/electron/main/imageProtocol.ts
+++ b/electron/main/imageProtocol.ts
@@ -46,6 +46,16 @@ export function emojiAssetDir(opts: { packaged: boolean; resourcesPath: string;
return candidates.find((dir) => existsSync(dir)) ?? candidates[0]
}
+/**
+ * Cache of validated emoji asset paths. The 64px PNG set is static at
+ * runtime, so a resolved filename never changes its answer. Caching skips a
+ * `resolve` + `existsSync` disk stat per glyph — the first emoji grid mounts
+ * ~100 `<img>` tags at once, and without this every one of them stats the
+ * disk inside the click. Only positive hits are cached, so the map is bounded
+ * by the real file count and invalid names never accumulate.
+ */
+const emojiAssetCache = new Map<string, string>()
+
/**
* Resolve a picker glyph filename to an on-disk PNG. Rejects anything that
* is not a lowercase hex-and-hyphen name so the protocol cannot escape the
@@ -55,9 +65,13 @@ export function resolveEmojiAsset(assetDir: string, fileName: string): string |
const name = fileName.toLowerCase()
if (!EMOJI_FILE_RE.test(name)) return null
const baseDir = resolve(assetDir)
+ const cacheKey = `${baseDir}${name}`
+ const cached = emojiAssetCache.get(cacheKey)
+ if (cached !== undefined) return cached
const filePath = resolve(join(baseDir, name))
if (dirname(filePath) !== baseDir) return null
if (!existsSync(filePath)) return null
+ emojiAssetCache.set(cacheKey, filePath)
return filePath
}
diff --git a/electron/main/state.ts b/electron/main/state.ts
index 406fd36..acdbe49 100644
--- a/electron/main/state.ts
+++ b/electron/main/state.ts
@@ -15,7 +15,7 @@ import { isStagedTempPath } from '../store/paths'
import { prefetchFileIcons } from './drag'
import { forgetStagedItems, reconcileTempOnStartup } from './stagedTemp'
import { runtime } from './config'
-import { getMainWindow, registerClipboardUpdateListener } from './window'
+import { getMainWindow, registerClipboardUpdateListener, requestPollBoost } from './window'
const store = new ItemStore((removed) => forgetStagedItems(removed))
const watcher = new ClipboardWatcher(600, 220)
@@ -29,6 +29,9 @@ function handleSystemSleep(): void {
function handleSystemWake(): void {
watcher.resyncSignature()
watcher.setPaused(true)
+ // First hover after sleep/unlock otherwise hits a SLOW poll tick and feels
+ // laggy. Hold FAST briefly; self-expiring, idle battery behavior unchanged.
+ try { requestPollBoost(8000) } catch { /* ignore */ }
if (wakeTimer !== null) clearTimeout(wakeTimer)
wakeTimer = setTimeout(() => {
diff --git a/electron/main/window.ts b/electron/main/window.ts
index 58539ad..23e5749 100644
--- a/electron/main/window.ts
+++ b/electron/main/window.ts
@@ -176,11 +176,19 @@ export function isInteractive(): boolean {
* - interactive=true (expanded) -> normal interactive window: the black blade
* captures all clicks.
*/
+let gcTimer: ReturnType<typeof setTimeout> | null = null
+
export function setInteractive(value: boolean): void {
if (!mainWindow || value === interactive) return
interactive = value
if (value) {
// Panel is open: disable click-through so user can interact.
+ // Cancel any pending idle GC: collecting during the open animation is
+ // what made fast reopen-after-close hitch. The next close re-arms it.
+ if (gcTimer !== null) {
+ clearTimeout(gcTimer)
+ gcTimer = null
+ }
mainWindow.setIgnoreMouseEvents(false)
// Use 'screen-saver' level to stay above fullscreen apps (YouTube fullscreen, games, etc.)
// 'floating' (HWND_TOPMOST) can be pushed behind by fullscreen D3D/browser windows.
@@ -196,7 +204,9 @@ export function setInteractive(value: boolean): void {
// Trigger gentle idle memory cleanup 1.5s after panel closes to reclaim RAM
if (global.gc) {
- setTimeout(() => {
+ if (gcTimer !== null) clearTimeout(gcTimer)
+ gcTimer = setTimeout(() => {
+ gcTimer = null
if (!interactive && global.gc) {
try { global.gc() } catch { /* ignore */ }
}
@@ -245,8 +255,35 @@ let heartbeatPaused = false
/** Whether the poll is currently running in fast (16ms) mode. */
let _pollFast = false
+/**
+ * Cold-start / wake boost deadline (epoch ms). While `Date.now()` is before
+ * this, the poll stays FAST even with the cursor far from the edge. Covers
+ * the first hover after launch/restart/wake, which otherwise hits a SLOW
+ * tick (75/100ms) + dwell and feels like lag. Steady-state adaptive behavior
+ * is unchanged once the window expires.
+ */
+let _boostUntilMs = 0
/** Timestamp of when the cursor last left the proximity zone. */
let _lastProximityExitMs = 0
+
+/**
+ * Hold the cursor poll at full speed for `durationMs`. Used once at launch
+ * and after system wake. Bounded and self-expiring: after the deadline the
+ * adaptive SLOW/FAST logic resumes exactly as before, so idle battery cost
+ * is unchanged (one ~8s FAST window per launch/wake).
+ */
+export function requestPollBoost(durationMs = 8000): void {
+ try {
+ _boostUntilMs = Date.now() + Math.max(0, durationMs)
+ } catch {
+ _boostUntilMs = 0
+ }
+ if (cursorPollTimer !== null && !_pollFast) {
+ _pollFast = true
+ _lastProximityExitMs = 0
+ _restartPollTimer(POLL_FAST_MS)
+ }
+}
/** Last sent cursor position — used to suppress duplicate IPC messages. */
let _lastSentX = -9999
let _lastSentY = -9999
@@ -326,7 +363,9 @@ function _pollTick(): void {
const distFromEdge = seam.probe.distFromEdge
// ── Adaptive speed: switch to fast poll when cursor approaches the edge ──
- const nearProximity = isNearProximity(distFromEdge)
+ // The launch/wake boost forces FAST during the cold window so the first
+ // hover never waits on a SLOW tick. `isNearProximity` behavior is untouched.
+ const nearProximity = isNearProximity(distFromEdge) || Date.now() < _boostUntilMs
if (nearProximity || interactive) {
_lastProximityExitMs = 0 // reset cooldown
@@ -400,6 +439,10 @@ export function startCursorPoll(): void {
const slowMs = powerMonitor.isOnBatteryPower() ? POLL_SLOW_BATTERY_MS : POLL_SLOW_AC_MS
_pollFast = false
cursorPollTimer = setInterval(_pollTick, slowMs)
+ // Cold-start boost: hold FAST briefly so the very first hover after a
+ // device restart / full relaunch responds on a 16ms tick, not a 75/100ms
+ // one. Self-expiring; idle battery behavior after the window is unchanged.
+ requestPollBoost(8000)
}
export function stopCursorPoll(): void {
diff --git a/src/App.tsx b/src/App.tsx
index 77cb9bc..e0ee4a4 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -8,7 +8,7 @@
* - the edge-hover controller (open/close the blade)
* - the Panel itself
*/
-import { useEffect } from 'react'
+import { useEffect, useRef } from 'react'
import { Panel } from './components/Panel'
import { useStore } from './store/appStore'
import { edge } from './lib/edge'
@@ -21,10 +21,162 @@ export default function App() {
const setSettings = useStore((s) => s.setSettings)
const pushToast = useStore((s) => s.pushToast)
const settings = useStore((s) => s.settings)
+ const hydrated = useStore((s) => s.hydrated)
+ const warmupDone = useRef(false)
// Drive the edge open/close behavior.
useEdgeHover()
+ // Cold-start warmup (no visual / feature change).
+ // The first shelf open and first emoji open jank because one-time init
+ // (font raster, emoji JSON parse, AudioContext creation, thumbnail decode,
+ // framer-motion JIT) lands inside the open animation. Warm each once, idle,
+ // after hydration so later opens reuse warm caches. Steady-state RAM/CPU
+ // are unchanged: every artifact warmed here is created on first use anyway.
+ useEffect(() => {
+ if (!hydrated || warmupDone.current) return
+ warmupDone.current = true
+ let cancelled = false
+ let idleHandle: any = null
+ let timeoutHandle: any = null
+
+ const warm = () => {
+ if (cancelled) return
+ // 1. Fonts declared in main.tsx — rasterize off the animation path.
+ try {
+ const doc = (globalThis as any)?.document
+ const fonts = doc?.fonts
+ if (fonts?.load) {
+ void Promise.allSettled([
+ fonts.load('400 12px "Plus Jakarta Sans"'),
+ fonts.load('500 12px "Plus Jakarta Sans"'),
+ fonts.load('600 12px "Plus Jakarta Sans"'),
+ fonts.load('700 12px "Plus Jakarta Sans"'),
+ fonts.load('400 12px "JetBrains Mono"'),
+ fonts.load('500 12px "JetBrains Mono"')
+ ]).catch(() => {})
+ }
+ } 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.
+ try {
+ void Promise.all([import('./lib/emoji/load'), import('./lib/emoji/catalog')])
+ .then(([loadMod, catalogMod]) =>
+ 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 */ }
+ }
+ } catch { /* ignore */ }
+ }).catch(() => undefined)
+ )
+ .catch(() => undefined)
+ } catch { /* ignore */ }
+ // 3. Shared AudioContext singleton — creation/resume off the gesture.
+ try {
+ void import('./lib/soundEffects')
+ .then((m) => {
+ try { m.warmAudioContext() } catch { /* ignore */ }
+ })
+ .catch(() => undefined)
+ } catch { /* ignore */ }
+ // 4. Framer-motion solver JIT (module already bundled via Panel).
+ try {
+ void import('framer-motion')
+ .then((m) => {
+ try {
+ const animate = (m as any)?.animate
+ if (typeof animate === 'function') void animate(0, 0, { duration: 0.01 } as any)
+ } catch { /* ignore */ }
+ })
+ .catch(() => undefined)
+ } catch { /* ignore */ }
+ // 5. First viewport thumbnails — prefetch through the same
+ // edgelocal/data URLs the cards use, warming both the main-process
+ // thumbnail cache and Chromium's decoded-image cache.
+ try {
+ const items = useStore.getState().items ?? []
+ const urls: string[] = []
+ for (const it of items) {
+ const d = (it as any)?.data
+ if (!d) continue
+ if (typeof d.preview === 'string' && d.preview) urls.push(d.preview)
+ if (Array.isArray(d.images)) {
+ for (const im of d.images) {
+ if (typeof im?.preview === 'string' && im.preview) urls.push(im.preview)
+ }
+ }
+ if (Array.isArray(d.previews)) {
+ for (const p of d.previews) {
+ if (typeof p === 'string' && p) urls.push(p)
+ }
+ }
+ if (Array.isArray(d.entries)) {
+ for (const e of d.entries) {
+ if (typeof e?.preview === 'string' && e.preview) urls.push(e.preview)
+ }
+ }
+ if (urls.length >= 12) break
+ }
+ const ImgCtor = (globalThis as any)?.Image
+ if (typeof ImgCtor === 'function') {
+ for (const u of urls.slice(0, 12)) {
+ try {
+ const im = new ImgCtor() as HTMLImageElement
+ try { (im as any).decoding = 'async' } catch { /* ignore */ }
+ im.src = u
+ } catch { /* ignore */ }
+ }
+ }
+ } catch { /* ignore */ }
+ }
+
+ try {
+ const ric = (globalThis as any)?.requestIdleCallback
+ if (typeof ric === 'function') {
+ idleHandle = ric(() => warm(), { timeout: 3000 })
+ } else {
+ timeoutHandle = setTimeout(warm, 1500)
+ }
+ } catch {
+ try { timeoutHandle = setTimeout(warm, 1500) } catch { /* ignore */ }
+ }
+ return () => {
+ cancelled = true
+ try {
+ const cic = (globalThis as any)?.cancelIdleCallback
+ if (idleHandle != null && typeof cic === 'function') cic(idleHandle)
+ } catch { /* ignore */ }
+ try {
+ if (timeoutHandle != null) clearTimeout(timeoutHandle)
+ } catch { /* ignore */ }
+ }
+ }, [hydrated])
+
// Hydrate once + subscribe to pushed updates.
useEffect(() => {
void hydrate()
diff --git a/src/components/EmojiPicker.tsx b/src/components/EmojiPicker.tsx
index ffe6436..ca93774 100644
--- a/src/components/EmojiPicker.tsx
+++ b/src/components/EmojiPicker.tsx
@@ -69,6 +69,7 @@ function Glyph({ file, size = 22 }: { file: string; size?: number }) {
height={size}
draggable={false}
decoding="async"
+ loading="lazy"
style={{ width: size, height: size }}
/>
)
@@ -99,6 +100,12 @@ export function EmojiPicker({
const scrollerRef = useRef<HTMLDivElement>(null)
const pickerRef = useRef<HTMLDivElement>(null)
const lastPasteAt = useRef(0)
+ // Scroll position is consumed one frame at a time: rapid scroll events
+ // only record the latest offset and schedule a single rAF commit, so the
+ // virtualized grid recomputes at most once per frame instead of once per
+ // raw scroll event. Same scroll position, less CPU while scrolling.
+ const scrollRaf = useRef<number | null>(null)
+ const pendingScrollTop = useRef(0)
const shownCats = useMemo(() => {
return CATEGORY_ORDER.filter((c) => c.id !== 'recents' || recents.length > 0)
@@ -138,6 +145,15 @@ export function EmojiPicker({
if (scrollerRef.current) scrollerRef.current.scrollTop = 0
}, [category])
+ useEffect(() => {
+ return () => {
+ if (scrollRaf.current !== null) {
+ try { cancelAnimationFrame(scrollRaf.current) } catch { /* ignore */ }
+ scrollRaf.current = null
+ }
+ }
+ }, [])
+
useEffect(() => {
if (!active || !catalog) return
const el = scrollerRef.current
@@ -297,9 +313,14 @@ export function EmojiPicker({
ref={scrollerRef}
className="emoji-grid"
onScroll={(e) => {
- setScrollTop((e.currentTarget as HTMLDivElement).scrollTop)
- setTonePop(null)
- setHoveredCat(null)
+ pendingScrollTop.current = (e.currentTarget as HTMLDivElement).scrollTop
+ if (scrollRaf.current !== null) return
+ scrollRaf.current = requestAnimationFrame(() => {
+ scrollRaf.current = null
+ setScrollTop(pendingScrollTop.current)
+ setTonePop(null)
+ setHoveredCat(null)
+ })
}}
>
<div style={{ height: startRow * rowH }} />
diff --git a/src/hooks/useEdgeHover.ts b/src/hooks/useEdgeHover.ts
index a3a8fc2..099000d 100644
--- a/src/hooks/useEdgeHover.ts
+++ b/src/hooks/useEdgeHover.ts
@@ -316,9 +316,29 @@ export function useEdgeHover(): void {
window.clearTimeout(interactiveTimer)
interactiveTimer = undefined
}
- edge.setInteractive(true)
+ // Sequence the open across two steps so the OS/DWM surface work
+ // (click-through off + always-on-top re-assert over IPC) starts before
+ // the React clip-path/spring commit. Previously both fired in the same
+ // tick, so DWM recomposition contended with layout + first-paint work
+ // and the first open after launch visibly hitched. No visual change:
+ // the same two calls run in the same order, one frame apart.
+ try {
+ void (edge.setInteractive(true) as unknown as Promise<void>)?.catch?.(() => {})
+ } catch { /* ignore IPC errors; close path still governs state */ }
if (useStore.getState().open) return
- useStore.getState().setOpen(true)
+ const commitOpen = () => {
+ if (useStore.getState().open) return
+ useStore.getState().setOpen(true)
+ }
+ try {
+ if (typeof window.requestAnimationFrame === 'function') {
+ window.requestAnimationFrame(() => commitOpen())
+ } else {
+ commitOpen()
+ }
+ } catch {
+ commitOpen()
+ }
}
// ── panel:leave / panel:enter (from Panel.tsx blade div) ──────────────
diff --git a/src/lib/soundEffects.ts b/src/lib/soundEffects.ts
index e83e56c..ef90455 100644
--- a/src/lib/soundEffects.ts
+++ b/src/lib/soundEffects.ts
@@ -33,6 +33,21 @@ function getAudioContext(): any | null {
return audioCtx
}
+/**
+ * Idle warmup for the shared AudioContext.
+ * Creates/resumes the singleton off the animation path (called once from an
+ * idle callback after hydration). No sound is played; first real UI sound
+ * then reuses the warm context instead of paying creation cost mid-animation.
+ * Respects the `soundEffects` setting via getAudioContext().
+ */
+export function warmAudioContext(): void {
+ try {
+ getAudioContext()
+ } catch {
+ /* ignore Web Audio API restrictions */
+ }
+}
+
// Global auto-unlock listener: resumes AudioContext on first pointerdown/mouseenter/keydown
const win = typeof globalThis !== 'undefined' ? (globalThis as any).window : undefined
if (win && win.addEventListener) {