Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add a Jev fallback for emoji search

Pedro Ladeira1d2fd9263f52
diff --git a/apps/web/app/api/ai/emoji-search/route.ts b/apps/web/app/api/ai/emoji-search/route.ts
new file mode 100644
index 0000000000..70e66fd0d6
--- /dev/null
+++ b/apps/web/app/api/ai/emoji-search/route.ts
@@ -0,0 +1,26 @@
+import { searchEmojis, warmEmojiCatalog } from "@/lib/ai/search-emojis";
+import { withSession } from "@/lib/auth";
+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const emojiSearchSchema = z.object({
+ query: z.string().trim().min(2).max(64),
+});
+
+warmEmojiCatalog();
+
+// POST /api/ai/emoji-search – semantic emoji matches when name search misses
+export const POST = withSession(async ({ req, session }) => {
+ const { query } = emojiSearchSchema.parse(await req.json());
+
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.emojiSearch,
+ identifier: session.user.id,
+ });
+
+ const emojis = await searchEmojis(query);
+
+ return NextResponse.json({ emojis });
+});
diff --git a/apps/web/lib/ai/search-emojis.ts b/apps/web/lib/ai/search-emojis.ts
new file mode 100644
index 0000000000..f046efdc82
--- /dev/null
+++ b/apps/web/lib/ai/search-emojis.ts
@@ -0,0 +1,207 @@
+import { experimental_evaluate as evaluate } from "ai";
+
+const EMOJIBASE_DATA_URL =
+ "https://cdn.jsdelivr.net/npm/[email protected]/en/data.json";
+
+const MATCH_LIMIT = 18;
+const MATCH_THRESHOLD = 0.25;
+const MAX_QUESTIONS_JSON_CHARS = 100_000;
+const MAX_TAGS = 12;
+const SEARCH_CACHE_LIMIT = 100;
+
+const MATCH_INSTRUCTIONS =
+ "Is this a good emoji for the search, including the same subject, synonyms, and close themes such as movies, characters, places, and objects?";
+
+export type EmojiMatch = {
+ emoji: string;
+ label: string;
+};
+
+export type EmojiCatalogEntry = EmojiMatch & {
+ id: string;
+ tags?: string[];
+};
+
+let catalogPromise: Promise<EmojiCatalogEntry[]> | null = null;
+const searchCache = new Map<string, EmojiMatch[]>();
+const searchRequests = new Map<string, Promise<EmojiMatch[]>>();
+
+export function rankEmojiMatches(
+ catalog: EmojiCatalogEntry[],
+ probabilities: Record<string, number>,
+): EmojiMatch[] {
+ return catalog
+ .flatMap((entry) => {
+ const probability = probabilities[entry.id];
+
+ if (probability === undefined || probability <= MATCH_THRESHOLD) {
+ return [];
+ }
+
+ return [{ ...entry, probability }];
+ })
+ .sort((a, b) => b.probability - a.probability)
+ .slice(0, MATCH_LIMIT)
+ .map(({ emoji, label }) => ({ emoji, label }));
+}
+
+function emojiQuestion(entry: EmojiCatalogEntry) {
+ const tags = (entry.tags ?? [])
+ .filter(
+ (tag) =>
+ tag.length > 1 && tag.toLowerCase() !== entry.label.toLowerCase(),
+ )
+ .slice(0, MAX_TAGS);
+
+ return {
+ type: "boolean" as const,
+ instructions: MATCH_INSTRUCTIONS,
+ criteria: {
+ true:
+ tags.length === 0 ? entry.label : `${entry.label} (${tags.join(", ")})`,
+ false: "unrelated subject",
+ },
+ };
+}
+
+export function chunkEmojiCatalog(
+ catalog: EmojiCatalogEntry[],
+): EmojiCatalogEntry[][] {
+ const chunks: EmojiCatalogEntry[][] = [];
+ let current: EmojiCatalogEntry[] = [];
+ let size = 2;
+
+ for (const entry of catalog) {
+ const question = emojiQuestion(entry);
+ const entrySize =
+ JSON.stringify(entry.id).length + JSON.stringify(question).length + 1;
+
+ if (current.length > 0 && size + entrySize > MAX_QUESTIONS_JSON_CHARS) {
+ chunks.push(current);
+ current = [];
+ size = 2;
+ }
+
+ current.push(entry);
+ size += entrySize;
+ }
+
+ if (current.length > 0) {
+ chunks.push(current);
+ }
+
+ return chunks;
+}
+
+function getEmojiCatalog() {
+ catalogPromise ??= fetch(EMOJIBASE_DATA_URL)
+ .then(async (response) => {
+ if (!response.ok) {
+ throw new Error("Failed to load emoji data");
+ }
+
+ const data: unknown = await response.json();
+
+ if (!Array.isArray(data)) {
+ throw new Error("Failed to load emoji data");
+ }
+
+ const catalog: EmojiCatalogEntry[] = [];
+ const seen = new Set<string>();
+
+ for (const item of data) {
+ if (!item || typeof item !== "object") continue;
+
+ const record = item as Record<string, unknown>;
+ const emoji = typeof record.emoji === "string" ? record.emoji : null;
+ const label =
+ typeof record.label === "string" ? record.label.trim() : null;
+ const hexcode =
+ typeof record.hexcode === "string" ? record.hexcode : null;
+ const tags = Array.isArray(record.tags)
+ ? record.tags.filter((tag): tag is string => typeof tag === "string")
+ : [];
+
+ if (!emoji || !label || !hexcode || seen.has(hexcode)) continue;
+
+ seen.add(hexcode);
+ catalog.push({ id: hexcode, emoji, label, tags });
+ }
+
+ return catalog;
+ })
+ .catch((error) => {
+ catalogPromise = null;
+ throw error;
+ });
+
+ return catalogPromise;
+}
+
+export function warmEmojiCatalog() {
+ void getEmojiCatalog().catch(() => undefined);
+}
+
+export async function searchEmojis(query: string): Promise<EmojiMatch[]> {
+ const normalized = query.trim().toLowerCase();
+
+ if (normalized.length < 2) {
+ return [];
+ }
+
+ const cached = searchCache.get(normalized);
+ if (cached) return cached;
+
+ const pending = searchRequests.get(normalized);
+ if (pending) return pending;
+
+ const request = getEmojiCatalog()
+ .then(async (catalog) => {
+ const probabilitySets = await Promise.all(
+ chunkEmojiCatalog(catalog).map(async (entries) => {
+ const result = await evaluate({
+ model: "typesafe-ai/jev",
+ state: normalized,
+ questions: Object.fromEntries(
+ entries.map((entry) => [entry.id, emojiQuestion(entry)]),
+ ),
+ providerOptions: {
+ gateway: {
+ zeroDataRetention: true,
+ },
+ },
+ });
+
+ const probabilities: Record<string, number> = {};
+
+ for (const entry of entries) {
+ const answer = result.answers[entry.id];
+
+ if (answer?.type === "boolean") {
+ probabilities[entry.id] = answer.probability;
+ }
+ }
+
+ return probabilities;
+ }),
+ );
+ const matches = rankEmojiMatches(
+ catalog,
+ Object.assign({}, ...probabilitySets),
+ );
+
+ if (searchCache.size >= SEARCH_CACHE_LIMIT) {
+ const oldest = searchCache.keys().next().value;
+ if (oldest) searchCache.delete(oldest);
+ }
+
+ searchCache.set(normalized, matches);
+ return matches;
+ })
+ .finally(() => {
+ searchRequests.delete(normalized);
+ });
+
+ searchRequests.set(normalized, request);
+ return request;
+}
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index 8990f57eb3..b1c7a00ab5 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -282,4 +282,10 @@ export const RATELIMIT_POLICIES = {
window: "24 h",
keyPrefix: "rl:tremendous:verify-otp",
},
+
+ emojiSearch: {
+ attempts: 30,
+ window: "10 s",
+ keyPrefix: "rl:ai:emoji-search",
+ },
} as const satisfies Record<string, RatelimitPolicy>;
diff --git a/apps/web/tests/misc/search-emojis.test.ts b/apps/web/tests/misc/search-emojis.test.ts
new file mode 100644
index 0000000000..4312097a75
--- /dev/null
+++ b/apps/web/tests/misc/search-emojis.test.ts
@@ -0,0 +1,63 @@
+import {
+ chunkEmojiCatalog,
+ rankEmojiMatches,
+ type EmojiCatalogEntry,
+} from "@/lib/ai/search-emojis";
+import { describe, expect, it } from "vitest";
+
+function entry(
+ id: string,
+ emoji: string,
+ label = "grinning face",
+): EmojiCatalogEntry {
+ return { id, emoji, label };
+}
+
+describe("rankEmojiMatches", () => {
+ const catalog = [
+ entry("1", "😀", "grinning face"),
+ entry("2", "🍕", "pizza"),
+ entry("3", "🤒", "face with thermometer"),
+ ];
+
+ it("keeps thematic matches above 0.25, highest probability first", () => {
+ expect(
+ rankEmojiMatches(catalog, {
+ "1": 0.3,
+ "2": 0.25,
+ "3": 0.91,
+ }),
+ ).toEqual([
+ { emoji: "🤒", label: "face with thermometer" },
+ { emoji: "😀", label: "grinning face" },
+ ]);
+ });
+
+ it("returns at most 18 matches", () => {
+ const many = Array.from({ length: 50 }, (_, index) =>
+ entry(String(index), String.fromCodePoint(0x1f600 + (index % 20))),
+ );
+
+ const probabilities = Object.fromEntries(
+ many.map((item, index) => [item.id, 0.7 + index / 1000]),
+ );
+
+ expect(rankEmojiMatches(many, probabilities)).toHaveLength(18);
+ });
+});
+
+describe("chunkEmojiCatalog", () => {
+ it("keeps a small catalog in one request", () => {
+ expect(
+ chunkEmojiCatalog([entry("1F600", "😀"), entry("1F355", "🍕", "pizza")]),
+ ).toHaveLength(1);
+ });
+
+ it("splits a catalog that would exceed Jev's context window", () => {
+ const label = "a".repeat(60_000);
+
+ expect(
+ chunkEmojiCatalog([entry("1", "😀", label), entry("2", "🍕", label)]),
+ ).toHaveLength(2);
+ });
+});
diff --git a/apps/web/ui/shared/emoji-picker.tsx b/apps/web/ui/shared/emoji-picker.tsx
index 05d3bdeefa..01af81864c 100644
--- a/apps/web/ui/shared/emoji-picker.tsx
+++ b/apps/web/ui/shared/emoji-picker.tsx
@@ -1,12 +1,100 @@
+import type { EmojiMatch } from "@/lib/ai/search-emojis";
import { Button, Popover } from "@dub/ui";
import { FaceSmile } from "@dub/ui/icons";
import { EmojiPicker as EmojiPickerBase } from "frimousse";
import {
PropsWithChildren,
+ useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
} from "react";
+import {
+ DUB_EMOJI_MATCHES,
+ normalizeEmojiQuery,
+ useSemanticEmojiSearch,
+} from "./use-semantic-emoji-search";
+
+const EMOJI_COLUMNS = 9;
+
+function EmojiMatchGrid({
+ matches,
+ onSelect,
+}: {
+ matches: EmojiMatch[];
+ onSelect: (emoji: string) => void;
+}) {
+ const rows = Array.from(
+ { length: Math.ceil(matches.length / EMOJI_COLUMNS) },
+ (_, index) =>
+ matches.slice(index * EMOJI_COLUMNS, (index + 1) * EMOJI_COLUMNS),
+ );
+
+ return (
+ <div className="w-full select-none pb-1.5">
+ {rows.map((row, rowIndex) => (
+ <div key={rowIndex} className="flex w-full px-1.5">
+ {row.map((match) => (
+ <button
+ key={`${match.label}-${match.emoji}`}
+ type="button"
+ aria-label={match.label}
+ className="flex aspect-square w-[10%] shrink-0 items-center justify-center rounded-md text-xl transition-transform duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] active:scale-[0.97] data-[active]:bg-neutral-100 sm:aspect-auto sm:size-7 sm:text-lg [@media(hover:hover)_and_(pointer:fine)]:hover:bg-neutral-100"
+ style={{ fontFamily: "var(--frimousse-emoji-font)" }}
+ onClick={() => onSelect(match.emoji)}
+ >
+ {match.emoji}
+ </button>
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function EmojiSkeleton() {
+ return (
+ <div className="w-full pt-1.5" aria-hidden>
+ {Array.from({ length: 8 }, (_, row) => (
+ <div key={row} className="flex w-full px-1.5">
+ {Array.from({ length: EMOJI_COLUMNS }, (_, column) => (
+ <div
+ key={column}
+ className="flex aspect-square w-[10%] shrink-0 items-center justify-center rounded-md sm:aspect-auto sm:size-7"
+ >
+ <span className="size-5 animate-pulse rounded-md bg-neutral-200/80 motion-reduce:animate-none" />
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function EmojiSearchFallback({
+ search,
+ onSelect,
+}: {
+ search: string;
+ onSelect: (emoji: string) => void;
+}) {
+ const query = normalizeEmojiQuery(search);
+ const semantic = useSemanticEmojiSearch(query, query.length >= 2);
+
+ if (semantic.status === "loading") {
+ return <EmojiSkeleton />;
+ }
+
+ if (semantic.status !== "ready") {
+ return (
+ <div className="absolute inset-0 flex items-center justify-center text-sm text-neutral-400">
+ No emoji found.
+ </div>
+ );
+ }
+
+ return <EmojiMatchGrid matches={semantic.matches} onSelect={onSelect} />;
+}
type EmojiPickerProps = PropsWithChildren<{
onSelect: (emoji: string) => void;
@@ -35,6 +123,16 @@ export function EmojiPicker({
const openPopover = isControlled ? controlledOpen : internalOpen;
const setOpenPopover = isControlled ? controlledSetOpen : setInternalOpen;
const keyboardDismissRef = useRef(false);
+ const [search, setSearch] = useState("");
+ const showDubEasterEgg = normalizeEmojiQuery(search) === "dub";
+ const selectEmoji = (emoji: string) => {
+ onSelect(emoji);
+ setOpenPopover(false);
+ };
+
+ useEffect(() => {
+ if (!openPopover) setSearch("");
+ }, [openPopover]);
const anchorEl = anchorRect ? (
<div
@@ -82,23 +180,32 @@ export function EmojiPicker({
}}
content={
<div
- className="isolate flex h-[300px] w-full flex-col sm:w-fit"
- onKeyDownCapture={handleBackspaceClose}
+ className="isolate flex h-[300px] w-full flex-col sm:w-[17.25rem]"
+ onKeyDownCapture={(event) => {
+ handleBackspaceClose(event);
+ if (!showDubEasterEgg) return;
+ if (event.key === "Enter" || event.key.startsWith("Arrow")) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }}
>
<EmojiPickerBase.Root
className="flex min-h-0 w-full flex-1 flex-col"
- onEmojiSelect={({ emoji }) => {
- onSelect(emoji);
- setOpenPopover(false);
- }}
+ onEmojiSelect={({ emoji }) => selectEmoji(emoji)}
>
- <EmojiPickerBase.Search className="border-border-default focus:border-border-default z-10 w-full border-0 border-b bg-white px-3 py-2.5 text-base outline-none placeholder:text-neutral-400 focus:ring-0 sm:rounded-t-lg sm:text-sm" />
+ <EmojiPickerBase.Search
+ onChange={(event) => setSearch(event.target.value)}
+ className="border-border-default focus:border-border-default z-10 w-full border-0 border-b bg-white px-3 py-2.5 text-base outline-none placeholder:text-neutral-400 focus:ring-0 sm:rounded-t-lg sm:text-sm"
+ />
<EmojiPickerBase.Viewport className="outline-hidden relative w-full flex-1">
- <EmojiPickerBase.Loading className="absolute inset-0 flex items-center justify-center text-sm text-neutral-400">
- Loading…
+ <EmojiPickerBase.Loading className="absolute inset-0 overflow-hidden">
+ <EmojiSkeleton />
</EmojiPickerBase.Loading>
- <EmojiPickerBase.Empty className="absolute inset-0 flex items-center justify-center text-sm text-neutral-400">
- No emoji found.
+ <EmojiPickerBase.Empty className="absolute inset-0 block overflow-y-auto">
+ {({ search }) => (
+ <EmojiSearchFallback search={search} onSelect={selectEmoji} />
+ )}
</EmojiPickerBase.Empty>
<EmojiPickerBase.List
className="w-full select-none pb-1.5"
@@ -118,7 +225,7 @@ export function EmojiPicker({
),
Emoji: ({ emoji, ...props }) => (
<button
- className="flex aspect-square w-[10%] shrink-0 items-center justify-center rounded-md text-xl data-[active]:bg-neutral-100 sm:aspect-auto sm:size-7 sm:w-auto sm:text-lg"
+ className="flex aspect-square w-[10%] shrink-0 items-center justify-center rounded-md text-xl data-[active]:bg-neutral-100 sm:aspect-auto sm:size-7 sm:text-lg"
{...props}
>
{emoji.emoji}
@@ -126,6 +233,14 @@ export function EmojiPicker({
),
}}
/>
+ {showDubEasterEgg && (
+ <div className="absolute inset-0 z-10 overflow-y-auto bg-white">
+ <EmojiMatchGrid
+ matches={DUB_EMOJI_MATCHES}
+ onSelect={selectEmoji}
+ />
+ </div>
+ )}
</EmojiPickerBase.Viewport>
</EmojiPickerBase.Root>
</div>
diff --git a/apps/web/ui/shared/inline-emoji-menu.tsx b/apps/web/ui/shared/inline-emoji-menu.tsx
index 00edc11e50..ff505d6f38 100644
--- a/apps/web/ui/shared/inline-emoji-menu.tsx
+++ b/apps/web/ui/shared/inline-emoji-menu.tsx
@@ -21,6 +21,11 @@ import {
useRef,
useState,
} from "react";
+import {
+ DUB_EMOJI_MATCHES,
+ normalizeEmojiQuery,
+ useSemanticEmojiSearch,
+} from "./use-semantic-emoji-search";
type EmojiShortcode = {
emoji: string;
@@ -121,14 +126,34 @@ export const InlineEmojiAutocomplete = forwardRef<
const menuRef = useRef<HTMLDivElement | null>(null);
const query = token?.query ?? "";
- const results = useMemo(
- () =>
- token && !dismissed && !suspended ? searchEmojiShortcodes(query) : [],
- [token, dismissed, suspended, query],
+ const normalizedQuery = normalizeEmojiQuery(query);
+ const menuActive = Boolean(token && !dismissed && !suspended);
+ const showDub = menuActive && normalizedQuery === "dub";
+ const localResults = useMemo(
+ () => (menuActive && !showDub ? searchEmojiShortcodes(query) : []),
+ [menuActive, showDub, query],
+ );
+ const semantic = useSemanticEmojiSearch(
+ query,
+ menuActive && !showDub && localResults.length === 0,
);
- const open = results.length > 0;
- const activeIndexClamped = results.length
- ? Math.min(activeIndex, results.length - 1)
+ const suggestions = showDub
+ ? DUB_EMOJI_MATCHES
+ : localResults.length > 0
+ ? localResults.map((item) => ({
+ emoji: item.emoji,
+ label: item.shortcode,
+ }))
+ : semantic.matches;
+ const loading =
+ menuActive &&
+ !showDub &&
+ localResults.length === 0 &&
+ semantic.status === "loading";
+ const open =
+ showDub || localResults.length > 0 || loading || suggestions.length > 0;
+ const activeIndexClamped = suggestions.length
+ ? Math.min(activeIndex, suggestions.length - 1)
: 0;
const activeOptionId = `${listboxId}-option-${activeIndexClamped}`;
@@ -247,7 +272,7 @@ export const InlineEmojiAutocomplete = forwardRef<
}, [open, editor, listboxId, activeOptionId]);
const selectIndex = (index: number) => {
- const next = results[index];
+ const next = suggestions[index];
if (!next || !editor || !token) return;
editor
@@ -264,9 +289,19 @@ export const InlineEmojiAutocomplete = forwardRef<
onKeyDown: (event) => {
if (!open || event.isComposing) return false;
+ if (suggestions.length === 0) {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setDismissed(true);
+ return true;
+ }
+
+ return false;
+ }
+
if (event.key === "ArrowDown") {
event.preventDefault();
- const next = (activeIndexRef.current + 1) % results.length;
+ const next = (activeIndexRef.current + 1) % suggestions.length;
activeIndexRef.current = next;
setActiveIndex(next);
return true;
@@ -275,7 +310,8 @@ export const InlineEmojiAutocomplete = forwardRef<
if (event.key === "ArrowUp") {
event.preventDefault();
const next =
- (activeIndexRef.current - 1 + results.length) % results.length;
+ (activeIndexRef.current - 1 + suggestions.length) %
+ suggestions.length;
activeIndexRef.current = next;
setActiveIndex(next);
return true;
@@ -288,7 +324,7 @@ export const InlineEmojiAutocomplete = forwardRef<
event.preventDefault();
const index = Math.min(
activeIndexRef.current,
- Math.max(results.length - 1, 0),
+ Math.max(suggestions.length - 1, 0),
);
selectIndex(index);
return true;
@@ -303,7 +339,7 @@ export const InlineEmojiAutocomplete = forwardRef<
return false;
},
}),
- [open, results, editor, token],
+ [open, suggestions, editor, token],
);
if (!open) return null;
@@ -322,37 +358,51 @@ export const InlineEmojiAutocomplete = forwardRef<
onMouseDown={(event) => event.preventDefault()}
className="border-border-subtle bg-bg-default z-[60] flex max-h-52 w-max min-w-40 max-w-[min(18rem,calc(100vw-16px))] flex-col overflow-y-auto rounded-lg border p-1 shadow-sm"
>
- {results.map((item, index) => {
- const selected = index === activeIndexClamped;
-
- return (
- <button
- key={item.shortcode}
- id={`${listboxId}-option-${index}`}
- type="button"
- role="option"
- aria-selected={selected}
- data-index={index}
- data-selected={selected}
- onPointerEnter={() => {
- activeIndexRef.current = index;
- setActiveIndex(index);
- }}
- onClick={() => selectIndex(index)}
- className={cn(
- "flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",
- "data-[selected=true]:bg-bg-subtle",
- )}
- >
- <span className="w-5 shrink-0 text-center text-base leading-none">
- {item.emoji}
- </span>
- <span className="text-content-subtle truncate">
- {item.shortcode}
- </span>
- </button>
- );
- })}
+ {loading ? (
+ <div aria-hidden className="flex flex-col">
+ {Array.from({ length: 5 }, (_, index) => (
+ <div key={index} className="flex items-center gap-2 px-2 py-1.5">
+ <span className="size-5 shrink-0 animate-pulse rounded-md bg-neutral-200/80 motion-reduce:animate-none" />
+ <span
+ className="h-3.5 max-w-40 animate-pulse rounded-md bg-neutral-200/80 motion-reduce:animate-none"
+ style={{ width: `${56 + (index % 3) * 28}px` }}
+ />
+ </div>
+ ))}
+ </div>
+ ) : (
+ suggestions.map((item, index) => {
+ const selected = index === activeIndexClamped;
+
+ return (
+ <button
+ key={`${item.label}-${item.emoji}`}
+ id={`${listboxId}-option-${index}`}
+ type="button"
+ role="option"
+ aria-selected={selected}
+ data-index={index}
+ data-selected={selected}
+ onPointerEnter={() => {
+ activeIndexRef.current = index;
+ setActiveIndex(index);
+ }}
+ onClick={() => selectIndex(index)}
+ className={cn(
+ "flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",
+ "data-[selected=true]:bg-bg-subtle",
+ )}
+ >
+ <span className="w-5 shrink-0 text-center text-base leading-none">
+ {item.emoji}
+ </span>
+ <span className="text-content-subtle truncate">
+ {item.label}
+ </span>
+ </button>
+ );
+ })
+ )}
</div>
</FloatingPortal>
);
diff --git a/apps/web/ui/shared/use-semantic-emoji-search.ts b/apps/web/ui/shared/use-semantic-emoji-search.ts
new file mode 100644
index 0000000000..54d6f0b2cc
--- /dev/null
+++ b/apps/web/ui/shared/use-semantic-emoji-search.ts
@@ -0,0 +1,126 @@
+"use client";
+
+import type { EmojiMatch } from "@/lib/ai/search-emojis";
+import { useEffect, useState } from "react";
+
+export const DUB_EMOJI_MATCHES: EmojiMatch[] = [
+ { emoji: "🤝", label: "Partners" },
+ { emoji: "💰", label: "Money" },
+ { emoji: "💸", label: "Payout" },
+ { emoji: "🔗", label: "Link" },
+ { emoji: "📱", label: "Mobile" },
+ { emoji: "🚀", label: "Growth" },
+ { emoji: "📊", label: "Analytics" },
+ { emoji: "🎯", label: "Conversion" },
+ { emoji: "🌐", label: "Domain" },
+ { emoji: "📈", label: "Clicks" },
+ { emoji: "🏷️", label: "Tag" },
+ { emoji: "👥", label: "Customers" },
+ { emoji: "💬", label: "Messages" },
+ { emoji: "🎁", label: "Reward" },
+ { emoji: "🏆", label: "Bounty" },
+ { emoji: "🔔", label: "Webhook" },
+];
+
+const emojiSearchCache = new Map<string, EmojiMatch[]>();
+const emojiSearchRequests = new Map<string, Promise<EmojiMatch[]>>();
+
+export function normalizeEmojiQuery(query: string) {
+ return query.trim().toLowerCase();
+}
+
+function fetchEmojiMatches(query: string) {
+ const cached = emojiSearchCache.get(query);
+ if (cached) return Promise.resolve(cached);
+
+ const pending = emojiSearchRequests.get(query);
+ if (pending) return pending;
+
+ const request = fetch("/api/ai/emoji-search", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ query }),
+ })
+ .then(async (response) => {
+ if (!response.ok) {
+ throw new Error("Emoji search failed");
+ }
+
+ const data = (await response.json()) as { emojis?: EmojiMatch[] };
+ const matches = Array.isArray(data.emojis)
+ ? data.emojis.filter(
+ (match) =>
+ !!match &&
+ typeof match.emoji === "string" &&
+ typeof match.label === "string",
+ )
+ : [];
+
+ emojiSearchCache.set(query, matches);
+ return matches;
+ })
+ .finally(() => {
+ emojiSearchRequests.delete(query);
+ });
+
+ emojiSearchRequests.set(query, request);
+ return request;
+}
+
+export function useSemanticEmojiSearch(query: string, enabled: boolean) {
+ const normalized = normalizeEmojiQuery(query);
+ const [result, setResult] = useState<{
+ query: string;
+ matches: EmojiMatch[];
+ } | null>(null);
+ const [failedQuery, setFailedQuery] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!enabled || normalized.length < 2 || emojiSearchCache.has(normalized)) {
+ return;
+ }
+
+ let active = true;
+ const timeout = window.setTimeout(() => {
+ fetchEmojiMatches(normalized)
+ .then((matches) => {
+ if (!active) return;
+ setFailedQuery((current) =>
+ current === normalized ? null : current,
+ );
+ setResult({ query: normalized, matches });
+ })
+ .catch(() => {
+ if (!active) return;
+ setFailedQuery(normalized);
+ });
+ }, 120);
+
+ return () => {
+ active = false;
+ window.clearTimeout(timeout);
+ };
+ }, [enabled, normalized]);
+
+ if (!enabled || normalized.length < 2) {
+ return { status: "idle" as const, matches: [] as EmojiMatch[] };
+ }
+
+ const matches =
+ emojiSearchCache.get(normalized) ??
+ (result?.query === normalized ? result.matches : undefined);
+
+ if (!matches) {
+ if (failedQuery === normalized) {
+ return { status: "empty" as const, matches: [] as EmojiMatch[] };
+ }
+
+ return { status: "loading" as const, matches: [] as EmojiMatch[] };
+ }
+
+ if (matches.length === 0) {
+ return { status: "empty" as const, matches };
+ }
+
+ return { status: "ready" as const, matches };
+}