:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): add Slack-style : emoji type-ahead to rich editors (#73272)
Luke Beltonce95eab2ddbd
diff --git a/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsxindex 6069e01f660b..d0b1a11dcbfa 100644--- a/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx+++ b/frontend/src/lib/components/EmojiPicker/EmojiPickerPanel.tsx@@ -32,10 +32,19 @@ export type EmojiPickerPanelProps = {/** Called with the selected emoji character */onEmojiSelect: (emoji: string) => voidclassName?: string+ /** Seed the search box with an initial query (uncontrolled — the user can edit it afterwards) */+ initialSearch?: string+ /** Focus the search box on mount, e.g. when opened from a `:` type-ahead */+ autoFocusSearch?: boolean}/** Frimousse emoji grid + search (no trigger); use inside a Popover or other container */-export function EmojiPickerPanel({ onEmojiSelect, className }: EmojiPickerPanelProps): JSX.Element {+export function EmojiPickerPanel({+ onEmojiSelect,+ className,+ initialSearch,+ autoFocusSearch,+}: EmojiPickerPanelProps): JSX.Element {return (<EmojiPicker.RootclassName={clsx('isolate flex h-[368px] w-fit flex-col bg-bg-light', className)}@@ -43,7 +52,11 @@ export function EmojiPickerPanel({ onEmojiSelect, className }: EmojiPickerPanelPonEmojiSelect(emoji)}}>- <EmojiPicker.Search className="z-10 mx-2 mt-2 appearance-none rounded bg-fill-input px-2.5 py-2 text-sm border" />+ <EmojiPicker.Search+ className="z-10 mx-2 mt-2 appearance-none rounded bg-fill-input px-2.5 py-2 text-sm border"+ defaultValue={initialSearch}+ autoFocus={autoFocusSearch}+ /><EmojiPicker.Viewport className="relative flex-1 outline-hidden"><EmojiPicker.Loading className="absolute inset-0 flex items-center justify-center text-tertiary text-sm">Loading…diff --git a/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.test.tsx b/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.test.tsxnew file mode 100644index 000000000000..a43871aab612--- /dev/null+++ b/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.test.tsx@@ -0,0 +1,120 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Editor } from '@tiptap/react'+import { Provider } from 'kea'+import { expectLogic } from 'kea-test-utils'++import { emojiUsageLogic } from 'lib/lemon-ui/LemonTextArea/emojiUsageLogic'++import { initKeaTests } from '~/test/init'++import { EmojiSuggestionPanel } from './EmojiSuggestionExtension'++// Render a stand-in for the frimousse picker: frimousse loads emoji data over the network and+// isn't meaningfully drivable in jsdom, so we assert the props we pass and fire a pick ourselves.+jest.mock('lib/components/EmojiPicker/EmojiPickerPanel', () => ({+ EmojiPickerPanel: ({ initialSearch, autoFocusSearch, onEmojiSelect }: any) => (+ <button+ data-attr="mock-emoji-panel"+ data-initial-search={initialSearch}+ data-autofocus={String(autoFocusSearch)}+ onClick={() => onEmojiSelect('🔥')}+ >+ pick+ </button>+ ),+}))++function createMockEditor(): { editor: Editor; run: jest.Mock; deleteRange: jest.Mock; insertContent: jest.Mock } {+ const run = jest.fn()+ const insertContent = jest.fn(() => ({ run }))+ const deleteRange = jest.fn(() => ({ insertContent }))+ const focus = jest.fn(() => ({ deleteRange }))+ const chain = jest.fn(() => ({ focus }))+ return { editor: { chain } as unknown as Editor, run, deleteRange, insertContent }+}++describe('EmojiSuggestionPanel', () => {+ beforeEach(() => {+ initKeaTests()+ emojiUsageLogic.mount()+ })++ afterEach(() => {+ cleanup()+ })++ it('does not render the picker until a character follows the colon', () => {+ const { editor } = createMockEditor()+ render(+ <Provider>+ <EmojiSuggestionPanel+ editor={editor}+ range={{ from: 0, to: 1 }}+ query=""+ visible={false}+ onClose={jest.fn()}+ />+ </Provider>+ )+ expect(screen.queryByTestId('mock-emoji-panel')).not.toBeInTheDocument()+ })++ it('seeds the picker search with the typed query and autofocuses it', () => {+ const { editor } = createMockEditor()+ render(+ <Provider>+ <EmojiSuggestionPanel+ editor={editor}+ range={{ from: 3, to: 6 }}+ query="sm"+ visible={true}+ onClose={jest.fn()}+ />+ </Provider>+ )+ const panel = screen.getByTestId('mock-emoji-panel')+ expect(panel).toHaveAttribute('data-initial-search', 'sm')+ expect(panel).toHaveAttribute('data-autofocus', 'true')+ })++ it('replaces the :query range with the picked emoji, records usage and closes', async () => {+ const { editor, run, deleteRange, insertContent } = createMockEditor()+ const onClose = jest.fn()+ const range = { from: 3, to: 6 }++ render(+ <Provider>+ <EmojiSuggestionPanel editor={editor} range={range} query="sm" visible={true} onClose={onClose} />+ </Provider>+ )++ await expectLogic(emojiUsageLogic, () => {+ fireEvent.click(screen.getByTestId('mock-emoji-panel'))+ }).toDispatchActions(['emojiUsed'])++ expect(deleteRange).toHaveBeenCalledWith(range)+ expect(insertContent).toHaveBeenCalledWith('🔥')+ expect(run).toHaveBeenCalledTimes(1)+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('closes on Escape', () => {+ const { editor } = createMockEditor()+ const onClose = jest.fn()+ render(+ <Provider>+ <EmojiSuggestionPanel+ editor={editor}+ range={{ from: 0, to: 1 }}+ query="s"+ visible={true}+ onClose={onClose}+ />+ </Provider>+ )+ fireEvent.keyDown(screen.getByTestId('mock-emoji-panel'), { key: 'Escape' })+ expect(onClose).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.tsx b/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.tsxnew file mode 100644index 000000000000..731a56ecdd99--- /dev/null+++ b/frontend/src/lib/components/RichContentEditor/EmojiSuggestionExtension.tsx@@ -0,0 +1,200 @@+import { Plugin, PluginKey } from '@tiptap/pm/state'+import type { EditorView } from '@tiptap/pm/view'+import { Editor, Extension, ReactRenderer } from '@tiptap/react'+import Suggestion, { exitSuggestion } from '@tiptap/suggestion'+import { useActions } from 'kea'++import { EmojiPickerPanel } from 'lib/components/EmojiPicker/EmojiPickerPanel'+import { emojiUsageLogic } from 'lib/lemon-ui/LemonTextArea/emojiUsageLogic'+import { Popover } from 'lib/lemon-ui/Popover'++import { EditorRange } from './types'++type EmojiSuggestionProps = {+ range: EditorRange+ /** What the user typed after the colon, in the editor, before focus moved into the picker */+ query: string+ editor: Editor+ /** Only mount + autofocus the picker once a character follows the colon */+ visible: boolean+ onClose: () => void+}++type EmojiSuggestionPopoverProps = EmojiSuggestionProps & {+ decorationNode?: HTMLElement | null+}++export function EmojiSuggestionPanel({+ range,+ query,+ editor,+ visible,+ onClose,+}: EmojiSuggestionProps): JSX.Element | null {+ const { emojiUsed } = useActions(emojiUsageLogic)++ if (!visible) {+ return null+ }++ const handleSelect = (emoji: string): void => {+ // Delete the `:query` still sitting in the editor (the range stops growing once+ // focus moves into the picker) and drop the emoji in its place.+ editor.chain().focus().deleteRange(range).insertContent(emoji).run()+ emojiUsed(emoji)+ onClose()+ }++ return (+ <div+ onKeyDown={(e) => {+ // Focus lives inside the picker, so the editor's suggestion keydown handler+ // never sees Escape — close from here instead.+ if (e.key === 'Escape') {+ e.preventDefault()+ onClose()+ }+ }}+ >+ <EmojiPickerPanel initialSearch={query} autoFocusSearch onEmojiSelect={handleSelect} />+ </div>+ )+}++function EmojiSuggestionPopover({ decorationNode, ...props }: EmojiSuggestionPopoverProps): JSX.Element {+ return (+ <Popover+ placement="bottom-start"+ fallbackPlacements={['top-start']}+ padded={false}+ overlay={<EmojiSuggestionPanel {...props} />}+ referenceElement={decorationNode ?? null}+ visible={props.visible}+ onClickOutside={props.onClose}+ >+ <span />+ </Popover>+ )+}++export const EmojiSuggestionPluginKey = new PluginKey('emojiSuggestion')++/**+ * Slack-style `:` emoji type-ahead for TipTap editors. Typing `:` immediately followed by a+ * character opens the emoji picker at the cursor, seeded with the typed query; picking an emoji+ * replaces the `:query` text. A bare `:` does nothing until a character follows it.+ *+ * Generic and dependency-free beyond the shared emoji picker — drop it into any editor's+ * `extensions` array.+ */+export const EmojiSuggestionExtension = Extension.create({+ name: 'emojiSuggestion',++ addProseMirrorPlugins() {+ // Position of a colon whose picker was Escaped. Suppresses the re-match that returning+ // focus to the editor would otherwise trigger; cleared once the caret leaves the token+ // (see the reset plugin below).+ let suppressedFrom: number | null = null++ return [+ Suggestion({+ pluginKey: EmojiSuggestionPluginKey,+ editor: this.editor,+ char: ':',+ startOfLine: false,+ // A space ends the match, so `: ` never opens the picker.+ allowSpaces: false,+ allow: ({ state, range, isActive }) => {+ // Only trigger when the colon starts a word — avoids `https://`, `12:30`, `foo:bar`.+ const before = state.doc.textBetween(Math.max(0, range.from - 1), range.from)+ if (before !== '' && !/\s/.test(before)) {+ return false+ }+ if (isActive) {+ return true+ }+ if (suppressedFrom === range.from) {+ return false+ }+ suppressedFrom = null+ return true+ },+ render: () => {+ let renderer: ReactRenderer<unknown, EmojiSuggestionPopoverProps> | null = null++ const dismiss = (view: EditorView, from: number): void => {+ suppressedFrom = from+ exitSuggestion(view, EmojiSuggestionPluginKey)+ renderer?.destroy()+ renderer = null+ // Hand focus back to the editor (it moved into the picker's search box) so+ // the caret returns after the typed `:query` and typing continues.+ view.focus()+ }++ const buildProps = (props: {+ editor: Editor+ range: EditorRange+ query: string+ decorationNode?: Element | null+ }): EmojiSuggestionPopoverProps => ({+ editor: props.editor,+ range: props.range,+ query: props.query,+ decorationNode: (props.decorationNode as HTMLElement) ?? null,+ visible: props.query.length >= 1,+ onClose: () => dismiss(props.editor.view, props.range.from),+ })++ return {+ onStart: (props) => {+ renderer = new ReactRenderer(EmojiSuggestionPopover, {+ props: buildProps(props),+ editor: props.editor,+ })+ },++ onUpdate(props) {+ renderer?.updateProps(buildProps(props))+ },++ onKeyDown(props) {+ // Escape only reaches here while focus is still in the editor (bare `:`,+ // or before autofocus lands); once open, the panel owns Escape.+ if (props.event.key === 'Escape') {+ dismiss(props.view, props.range.from)+ return true+ }+ return false+ },++ onExit() {+ renderer?.destroy()+ renderer = null+ },+ }+ },+ }),+ // Clear the dismissal memory once the caret leaves the Escaped token, so a fresh `:`+ // at (or returning to) that spot can reopen the picker.+ new Plugin({+ key: new PluginKey('emojiSuggestionSuppressionReset'),+ view: () => ({+ update: (view) => {+ if (suppressedFrom === null) {+ return+ }+ const { doc, selection } = view.state+ const stillOnToken =+ selection.empty &&+ selection.from > suppressedFrom &&+ /^:\S*$/.test(doc.textBetween(suppressedFrom, selection.from))+ if (!stillOnToken) {+ suppressedFrom = null+ }+ },+ }),+ }),+ ]+ },+})diff --git a/frontend/src/lib/lemon-ui/LemonRichContent/LemonRichContentEditor.tsx b/frontend/src/lib/lemon-ui/LemonRichContent/LemonRichContentEditor.tsxindex 0a936c0888d2..5243d01ae923 100644--- a/frontend/src/lib/lemon-ui/LemonRichContent/LemonRichContentEditor.tsx+++ b/frontend/src/lib/lemon-ui/LemonRichContent/LemonRichContentEditor.tsx@@ -15,6 +15,7 @@ import { TextContent } from 'lib/components/Cards/TextCard/TextCard'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useRichContentEditor } from 'lib/components/RichContentEditor'import { CommandEnterExtension } from 'lib/components/RichContentEditor/CommandEnterExtension'+import { EmojiSuggestionExtension } from 'lib/components/RichContentEditor/EmojiSuggestionExtension'import { MentionsExtension } from 'lib/components/RichContentEditor/MentionsExtension'import { RichContentNodeMention } from 'lib/components/RichContentEditor/RichContentNodeMention'import { RichContentEditorType, RichContentNodeType, TTEditor } from 'lib/components/RichContentEditor/types'@@ -51,6 +52,7 @@ const DEFAULT_INITIAL_CONTENT: JSONContent = {export const DEFAULT_EXTENSIONS = [MentionsExtension,+ EmojiSuggestionExtension,RichContentNodeMention,ExtensionDocument,StarterKit.configure({diff --git a/products/conversations/frontend/components/Editor/SupportEditor.tsx b/products/conversations/frontend/components/Editor/SupportEditor.tsxindex 8ba2712a7097..e77482e1e628 100644--- a/products/conversations/frontend/components/Editor/SupportEditor.tsx+++ b/products/conversations/frontend/components/Editor/SupportEditor.tsx@@ -27,6 +27,7 @@ import { IconCode, IconCopy, IconImage, IconTerminal } from '@posthog/icons'import { EmojiPickerPopover } from 'lib/components/EmojiPicker/EmojiPickerPopover'import { useRichContentEditor } from 'lib/components/RichContentEditor'import { CommandEnterExtension } from 'lib/components/RichContentEditor/CommandEnterExtension'+import { EmojiSuggestionExtension } from 'lib/components/RichContentEditor/EmojiSuggestionExtension'import { MentionsExtension } from 'lib/components/RichContentEditor/MentionsExtension'import { RichContentNodeMention } from 'lib/components/RichContentEditor/RichContentNodeMention'import { RichContentEditorType, RichContentNodeType, TTEditor } from 'lib/components/RichContentEditor/types'@@ -220,6 +221,7 @@ const LinkOnPasteExtension = Extension.create({export const SUPPORT_EXTENSIONS = [MentionsExtension,+ EmojiSuggestionExtension,RichContentNodeMention,ExtensionDocument,StarterKit.configure({