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.

Inline emoji picker (#4536)

Pedro Ladeira6cbaa0eb3b51
diff --git a/apps/web/package.json b/apps/web/package.json
index 15641f2e4d..9bf9260746 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -92,6 +92,7 @@
"frimousse": "^0.3.0",
"fuse.js": "^6.6.2",
"geist": "^1.3.1",
+ "gemoji": "8.1.0",
"he": "^1.2.0",
"html-escaper": "^3.0.3",
"input-otp": "^1.2.4",
diff --git a/apps/web/ui/shared/emoji-picker.tsx b/apps/web/ui/shared/emoji-picker.tsx
index 2b91a9e288..05d3bdeefa 100644
--- a/apps/web/ui/shared/emoji-picker.tsx
+++ b/apps/web/ui/shared/emoji-picker.tsx
@@ -82,18 +82,18 @@ export function EmojiPicker({
}}
content={
<div
- className="isolate flex h-[300px] w-fit flex-col"
+ className="isolate flex h-[300px] w-full flex-col sm:w-fit"
onKeyDownCapture={handleBackspaceClose}
>
<EmojiPickerBase.Root
- className="flex min-h-0 flex-1 flex-col"
+ className="flex min-h-0 w-full flex-1 flex-col"
onEmojiSelect={({ emoji }) => {
onSelect(emoji);
setOpenPopover(false);
}}
>
- <EmojiPickerBase.Search className="border-border-default focus:border-border-default z-10 rounded-t-lg border-0 border-b bg-white px-3 py-2.5 text-base outline-none placeholder:text-neutral-400 focus:ring-0 sm:text-sm" />
- <EmojiPickerBase.Viewport className="outline-hidden relative flex-1">
+ <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.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>
@@ -101,24 +101,24 @@ export function EmojiPicker({
No emoji found.
</EmojiPickerBase.Empty>
<EmojiPickerBase.List
- className="select-none pb-1.5"
+ className="w-full select-none pb-1.5"
components={{
CategoryHeader: ({ category, ...props }) => (
<div
- className="text-content-subtle bg-white px-3 pb-1.5 pt-3 text-xs font-medium"
+ className="text-content-subtle w-full bg-white px-3 pb-1.5 pt-3 text-xs font-medium"
{...props}
>
{category.label}
</div>
),
Row: ({ children, ...props }) => (
- <div className="scroll-my-1.5 px-1.5" {...props}>
+ <div className="w-full scroll-my-1.5 px-1.5" {...props}>
{children}
</div>
),
Emoji: ({ emoji, ...props }) => (
<button
- className="flex size-7 items-center justify-center rounded-md text-lg data-[active]:bg-neutral-100"
+ 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"
{...props}
>
{emoji.emoji}
diff --git a/apps/web/ui/shared/inline-emoji-menu.tsx b/apps/web/ui/shared/inline-emoji-menu.tsx
new file mode 100644
index 0000000000..00edc11e50
--- /dev/null
+++ b/apps/web/ui/shared/inline-emoji-menu.tsx
@@ -0,0 +1,359 @@
+"use client";
+
+import { useRichTextContext } from "@dub/ui";
+import { cn } from "@dub/utils";
+import {
+ autoUpdate,
+ flip,
+ FloatingPortal,
+ offset,
+ shift,
+ useFloating,
+} from "@floating-ui/react";
+import { gemoji } from "gemoji";
+import {
+ forwardRef,
+ useEffect,
+ useId,
+ useImperativeHandle,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+
+type EmojiShortcode = {
+ emoji: string;
+ shortcode: string;
+};
+
+const RESULT_LIMIT = 20;
+
+const primaryShortcodes: EmojiShortcode[] = gemoji.map((entry) => ({
+ emoji: entry.emoji,
+ shortcode: entry.names[0],
+}));
+
+const allShortcodes: EmojiShortcode[] = gemoji.flatMap((entry) =>
+ entry.names.map((shortcode) => ({
+ emoji: entry.emoji,
+ shortcode,
+ })),
+);
+
+function searchEmojiShortcodes(query: string) {
+ const normalized = query.toLowerCase();
+
+ if (!normalized) return primaryShortcodes.slice(0, RESULT_LIMIT);
+
+ return allShortcodes
+ .filter((item) => item.shortcode.startsWith(normalized))
+ .sort((a, b) => {
+ if (a.shortcode.length !== b.shortcode.length) {
+ return a.shortcode.length - b.shortcode.length;
+ }
+ return a.shortcode.localeCompare(b.shortcode);
+ })
+ .slice(0, RESULT_LIMIT);
+}
+
+const EMOJI_TOKEN = /(?:^|[\s\0\n]):([a-z0-9_+-]*)$/i;
+
+// `\0` is a one-character stand-in for leaf nodes, so the index matches a
+// ProseMirror parent offset.
+function matchEmojiToken(textBeforeCaret: string) {
+ const match = textBeforeCaret.match(EMOJI_TOKEN);
+ if (!match || match.index === undefined) return null;
+
+ return {
+ query: match[1],
+ colonIndex: match.index + match[0].lastIndexOf(":"),
+ };
+}
+
+type RichTextEditor = NonNullable<
+ ReturnType<typeof useRichTextContext>["editor"]
+>;
+
+type EmojiToken = {
+ query: string;
+ from: number;
+ to: number;
+};
+
+export type InlineEmojiAutocompleteHandle = {
+ onKeyDown: (event: KeyboardEvent) => boolean;
+};
+
+function readEmojiToken(editor: RichTextEditor): EmojiToken | null {
+ const { selection } = editor.state;
+ if (!selection.empty) return null;
+
+ const { $from } = selection;
+ // `\0` stands in for leaf nodes (hard breaks) and is one character, so the
+ // string index lines up with the parent offset.
+ const textBeforeCaret = $from.parent.textBetween(
+ 0,
+ $from.parentOffset,
+ "\n",
+ "\0",
+ );
+ const match = matchEmojiToken(textBeforeCaret);
+ if (!match) return null;
+
+ return {
+ query: match.query,
+ from: $from.start() + match.colonIndex,
+ to: $from.pos,
+ };
+}
+
+export const InlineEmojiAutocomplete = forwardRef<
+ InlineEmojiAutocompleteHandle,
+ { suspended?: boolean }
+>(function InlineEmojiAutocomplete({ suspended = false }, ref) {
+ const { editor } = useRichTextContext();
+ const listboxId = useId();
+ const [token, setToken] = useState<EmojiToken | null>(null);
+ const [dismissed, setDismissed] = useState(false);
+ const [activeIndex, setActiveIndex] = useState(0);
+ const activeIndexRef = useRef(0);
+ const menuRef = useRef<HTMLDivElement | null>(null);
+
+ const query = token?.query ?? "";
+ const results = useMemo(
+ () =>
+ token && !dismissed && !suspended ? searchEmojiShortcodes(query) : [],
+ [token, dismissed, suspended, query],
+ );
+ const open = results.length > 0;
+ const activeIndexClamped = results.length
+ ? Math.min(activeIndex, results.length - 1)
+ : 0;
+ const activeOptionId = `${listboxId}-option-${activeIndexClamped}`;
+
+ const { refs, floatingStyles, update } = useFloating({
+ open,
+ placement: "top-start",
+ strategy: "fixed",
+ middleware: [offset(6), flip(), shift({ padding: 8 })],
+ whileElementsMounted: autoUpdate,
+ });
+
+ useEffect(() => {
+ if (suspended) setDismissed(true);
+ }, [suspended]);
+
+ useEffect(() => {
+ if (!editor) return;
+
+ const syncToken = () => {
+ const next = readEmojiToken(editor);
+ setToken((current) =>
+ current?.query === next?.query &&
+ current?.from === next?.from &&
+ current?.to === next?.to
+ ? current
+ : next,
+ );
+ if (!next) setDismissed(false);
+ };
+
+ syncToken();
+ editor.on("update", syncToken);
+ editor.on("selectionUpdate", syncToken);
+
+ return () => {
+ editor.off("update", syncToken);
+ editor.off("selectionUpdate", syncToken);
+ };
+ }, [editor]);
+
+ useEffect(() => {
+ activeIndexRef.current = 0;
+ setActiveIndex(0);
+ }, [query]);
+
+ useLayoutEffect(() => {
+ if (!open || !editor) return;
+
+ refs.setPositionReference({
+ getBoundingClientRect: () => {
+ const coords = editor.view.coordsAtPos(editor.state.selection.from);
+ return new DOMRect(
+ coords.left,
+ coords.top,
+ coords.right - coords.left,
+ coords.bottom - coords.top,
+ );
+ },
+ });
+ }, [open, editor, token?.from, token?.to, refs]);
+
+ useEffect(() => {
+ if (!open) return;
+
+ const viewport = window.visualViewport;
+ if (!viewport) return;
+
+ const onViewportChange = () => update();
+ viewport.addEventListener("resize", onViewportChange);
+ viewport.addEventListener("scroll", onViewportChange);
+
+ return () => {
+ viewport.removeEventListener("resize", onViewportChange);
+ viewport.removeEventListener("scroll", onViewportChange);
+ };
+ }, [open, update]);
+
+ useEffect(() => {
+ if (!open || !editor) return;
+
+ const onPointerDown = (event: PointerEvent) => {
+ const target = event.target;
+ if (!(target instanceof Node)) return;
+ if (menuRef.current?.contains(target)) return;
+ if (editor.view.dom.contains(target)) return;
+ setDismissed(true);
+ };
+
+ document.addEventListener("pointerdown", onPointerDown, true);
+ return () =>
+ document.removeEventListener("pointerdown", onPointerDown, true);
+ }, [open, editor]);
+
+ useEffect(() => {
+ if (!open) return;
+ menuRef.current
+ ?.querySelector<HTMLElement>(`[data-index="${activeIndexClamped}"]`)
+ ?.scrollIntoView({ block: "nearest" });
+ }, [open, activeIndexClamped, query]);
+
+ useEffect(() => {
+ if (!open || !editor) return;
+
+ const dom = editor.view.dom;
+ dom.setAttribute("aria-controls", listboxId);
+ dom.setAttribute("aria-expanded", "true");
+ dom.setAttribute("aria-autocomplete", "list");
+ dom.setAttribute("aria-activedescendant", activeOptionId);
+
+ return () => {
+ dom.removeAttribute("aria-controls");
+ dom.removeAttribute("aria-expanded");
+ dom.removeAttribute("aria-autocomplete");
+ dom.removeAttribute("aria-activedescendant");
+ };
+ }, [open, editor, listboxId, activeOptionId]);
+
+ const selectIndex = (index: number) => {
+ const next = results[index];
+ if (!next || !editor || !token) return;
+
+ editor
+ .chain()
+ .focus()
+ .deleteRange({ from: token.from, to: token.to })
+ .insertContent(next.emoji)
+ .run();
+ };
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ onKeyDown: (event) => {
+ if (!open || event.isComposing) return false;
+
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ const next = (activeIndexRef.current + 1) % results.length;
+ activeIndexRef.current = next;
+ setActiveIndex(next);
+ return true;
+ }
+
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ const next =
+ (activeIndexRef.current - 1 + results.length) % results.length;
+ activeIndexRef.current = next;
+ setActiveIndex(next);
+ return true;
+ }
+
+ if (
+ (event.key === "Enter" && !event.metaKey && !event.ctrlKey) ||
+ event.key === "Tab"
+ ) {
+ event.preventDefault();
+ const index = Math.min(
+ activeIndexRef.current,
+ Math.max(results.length - 1, 0),
+ );
+ selectIndex(index);
+ return true;
+ }
+
+ if (event.key === "Escape") {
+ event.preventDefault();
+ setDismissed(true);
+ return true;
+ }
+
+ return false;
+ },
+ }),
+ [open, results, editor, token],
+ );
+
+ if (!open) return null;
+
+ return (
+ <FloatingPortal>
+ <div
+ ref={(node) => {
+ menuRef.current = node;
+ refs.setFloating(node);
+ }}
+ id={listboxId}
+ style={floatingStyles}
+ role="listbox"
+ aria-label="Emoji suggestions"
+ 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>
+ );
+ })}
+ </div>
+ </FloatingPortal>
+ );
+});
diff --git a/apps/web/ui/shared/message-input.tsx b/apps/web/ui/shared/message-input.tsx
index 4a6ec4e09f..5d61304f76 100644
--- a/apps/web/ui/shared/message-input.tsx
+++ b/apps/web/ui/shared/message-input.tsx
@@ -33,6 +33,10 @@ import {
import { toast } from "sonner";
import { ATTACHMENT_MIME_TYPE_COLOR } from "../messages/message-attachments";
import { EmojiPicker } from "../shared/emoji-picker";
+import {
+ InlineEmojiAutocomplete,
+ type InlineEmojiAutocompleteHandle,
+} from "../shared/inline-emoji-menu";
export type PendingAttachment = Omit<MessageAttachmentInput, "storageKey"> & {
id: string;
@@ -82,22 +86,10 @@ export function MessageInput({
const richTextRef = useRef<{ setContent: (content: any) => void }>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const emojiAutocompleteRef = useRef<InlineEmojiAutocompleteHandle>(null);
const [typedMessage, setTypedMessage] = useState(defaultValue || "");
- const [emojiPickerOpen, setEmojiPickerOpenState] = useState(false);
+ const [emojiPickerOpen, setEmojiPickerOpen] = useState(false);
const [dragActive, setDragActive] = useState(false);
- const [cursorRect, setCursorRect] = useState<{
- top: number;
- bottom: number;
- left: number;
- right: number;
- } | null>(null);
- const stripColonOnEmojiPickRef = useRef(false);
-
- const setEmojiPickerOpen = useCallback((open: boolean) => {
- stripColonOnEmojiPickRef.current = false;
- if (!open) setCursorRect(null);
- setEmojiPickerOpenState(open);
- }, []);
const hasCompletedAttachments = attachments.some(
(a) => !a.uploading && a.storageKey,
@@ -234,35 +226,14 @@ export function MessageInput({
onChange={(editor) => setTypedMessage((editor as any).getMarkdown())}
editorProps={{
handleDOMEvents: {
- keydown: (view, e) => {
+ keydown: (_view, e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
e.stopPropagation();
sendMessage();
return false;
}
- if (e.key === ":" && !e.metaKey && !e.ctrlKey && !e.altKey) {
- const { $from } = view.state.selection;
- const afterHardBreak =
- $from.nodeBefore?.type.name === "hardBreak";
- const atBlockStart = $from.parentOffset === 0;
- const afterWhitespace =
- $from.parentOffset > 0 &&
- /\s/.test(
- $from.parent.textBetween(
- $from.parentOffset - 1,
- $from.parentOffset,
- ),
- );
- if (atBlockStart || afterWhitespace || afterHardBreak) {
- const coords = view.coordsAtPos(view.state.selection.from);
- setCursorRect(coords);
- setTimeout(() => {
- stripColonOnEmojiPickRef.current = true;
- setEmojiPickerOpenState(true);
- }, 0);
- }
- }
+ if (emojiAutocompleteRef.current?.onKeyDown(e)) return true;
},
},
}}
@@ -270,6 +241,10 @@ export function MessageInput({
<div className="relative">
<RichTextArea />
<MessageInputEditorOverflowFades />
+ <InlineEmojiAutocomplete
+ ref={emojiAutocompleteRef}
+ suspended={emojiPickerOpen}
+ />
</div>
{/* Attachment preview strip */}
@@ -290,8 +265,6 @@ export function MessageInput({
disabled={Boolean(permissionsError)}
emojiPickerOpen={emojiPickerOpen}
setEmojiPickerOpen={setEmojiPickerOpen}
- stripColonOnEmojiPickRef={stripColonOnEmojiPickRef}
- cursorRect={cursorRect}
onAttachClick={
canAddFiles ? () => fileInputRef.current?.click() : undefined
}
@@ -568,20 +541,11 @@ function MessageInputToolbar({
disabled,
emojiPickerOpen,
setEmojiPickerOpen,
- stripColonOnEmojiPickRef,
- cursorRect,
onAttachClick,
}: {
disabled?: boolean;
emojiPickerOpen: boolean;
setEmojiPickerOpen: (open: boolean) => void;
- stripColonOnEmojiPickRef: { current: boolean };
- cursorRect: {
- top: number;
- bottom: number;
- left: number;
- right: number;
- } | null;
onAttachClick?: () => void;
}) {
const { editor } = useRichTextContext();
@@ -594,26 +558,9 @@ function MessageInputToolbar({
openPopover={emojiPickerOpen}
setOpenPopover={setEmojiPickerOpen}
onKeyboardDismissFocusEditor={() => editor?.commands.focus()}
- anchorRect={cursorRect}
onSelect={(emoji) => {
if (!editor || disabled) return;
- const stripColon = stripColonOnEmojiPickRef.current;
- stripColonOnEmojiPickRef.current = false;
-
- const { from } = editor.state.selection;
- if (
- stripColon &&
- from > 0 &&
- editor.state.doc.textBetween(from - 1, from) === ":"
- ) {
- editor
- .chain()
- .deleteRange({ from: from - 1, to: from })
- .insertContent(emoji)
- .run();
- } else {
- editor.chain().insertContent(emoji).run();
- }
+ editor.chain().insertContent(emoji).run();
setTimeout(() => editor.commands.focus(), 0);
}}
>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4f8c907c64..6eb36ee3bf 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -254,6 +254,9 @@ importers:
geist:
specifier: ^1.3.1
+ gemoji:
+ specifier: 8.1.0
+ version: 8.1.0
he:
specifier: ^1.2.0
version: 1.2.0
@@ -675,7 +678,7 @@ importers:
dependencies:
'@hubspot/cli':
specifier: ^7.6.2
devDependencies:
'@types/node':
specifier: 18.11.9
@@ -8544,6 +8547,9 @@ packages:
peerDependencies:
next: '>=13.2.0'
+ resolution: {integrity: sha512-HA4Gx59dw2+tn+UAa7XEV4ufUKI4fH1KgcbenVA9YKSj1QJTT0xh5Mwv5HMFNN3l2OtUe3ZIfuRwSyZS5pLIWw==}
+
resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==}
@@ -13160,7 +13166,7 @@ packages:
resolution: {integrity: sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==}
- deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
+ deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
hasBin: true
@@ -14616,9 +14622,9 @@ snapshots:
'@babel/core': 7.24.5
'@babel/helper-plugin-utils': 7.25.9
dependencies:
- '@babel/core': 7.24.5
+ '@babel/core': 7.28.4
'@babel/helper-plugin-utils': 7.27.1
optional: true
@@ -15448,7 +15454,7 @@ snapshots:
- encoding
- supports-color
dependencies:
'@hubspot/local-dev-lib': 3.19.1
'@hubspot/project-parsing-lib': 0.8.6(@hubspot/[email protected])
@@ -15479,7 +15485,7 @@ snapshots:
yargs: 17.7.2
yargs-parser: 21.1.1
optionalDependencies:
'@modelcontextprotocol/sdk': 1.13.3
transitivePeerDependencies:
- '@babel/core'
@@ -15517,7 +15523,7 @@ snapshots:
react-dom: 18.3.1([email protected])
optional: true
dependencies:
'@babel/code-frame': 7.26.2
'@babel/parser': 7.26.2
@@ -15544,7 +15550,7 @@ snapshots:
'@vitejs/plugin-react': 4.7.0([email protected](@types/[email protected])([email protected]))
ansi-to-html: 0.7.2
babel-plugin-macros: 3.1.0
chalk: 5.4.1
class-variance-authority: 0.7.0
cli-progress: 3.12.0
@@ -15563,7 +15569,7 @@ snapshots:
react-dom: 18.3.1([email protected])
request: 2.88.2
storybook: 8.6.14([email protected])
tailwind-merge: 2.6.0
tailwindcss-animate: 1.0.7
typescript: 4.7.4
@@ -20601,11 +20607,11 @@ snapshots:
resolve: 1.22.6
optional: true
dependencies:
'@babel/helper-annotate-as-pure': 7.27.3
'@babel/helper-module-imports': 7.25.9
- '@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])
+ '@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])
lodash: 4.17.21
picomatch: 2.3.1
@@ -22918,6 +22924,8 @@ snapshots:
dependencies:
+
dependencies:
is-property: 1.0.2
@@ -27704,12 +27712,12 @@ snapshots:
tslib: 2.6.2
optional: true
dependencies:
client-only: 0.0.1
react: 18.3.1
optionalDependencies:
- '@babel/core': 7.24.5
+ '@babel/core': 7.28.4
babel-plugin-macros: 3.1.0
optional: true