{"version":3,"file":"textComposerEmojiMiddleware.mjs","names":[],"sources":["../../../../../src/plugins/Emojis/middleware/textComposerEmojiMiddleware.ts"],"sourcesContent":["import mergeWith from 'lodash.mergewith';\nimport type {\n  Middleware,\n  SearchSourceOptions,\n  SearchSourceType,\n  TextComposerMiddlewareExecutorState,\n  TextComposerMiddlewareOptions,\n  TextComposerSuggestion,\n} from 'stream-chat';\nimport {\n  BaseSearchSource,\n  getTokenizedSuggestionDisplayName,\n  getTriggerCharWithToken,\n  insertItemWithTrigger,\n  replaceWordWithEntity,\n} from 'stream-chat';\nimport type {\n  EmojiSearchIndex,\n  EmojiSearchIndexResult,\n} from '../../../components/MessageComposer';\n\nexport type EmojiSuggestion<T extends EmojiSearchIndexResult = EmojiSearchIndexResult> =\n  TextComposerSuggestion<T>;\n\nclass EmojiSearchSource<\n  T extends TextComposerSuggestion<EmojiSearchIndexResult>,\n> extends BaseSearchSource<T> {\n  readonly type: SearchSourceType = 'emoji';\n  private emojiSearchIndex: EmojiSearchIndex;\n\n  constructor(emojiSearchIndex: EmojiSearchIndex, options?: SearchSourceOptions) {\n    super(options);\n    this.emojiSearchIndex = emojiSearchIndex;\n  }\n\n  async query(searchQuery: string) {\n    if (searchQuery.length === 0) {\n      return { items: [] as T[], next: null };\n    }\n    const emojis = (await this.emojiSearchIndex.search(searchQuery)) ?? [];\n\n    // emojiIndex.search sometimes returns undefined values, so filter those out first\n    return {\n      items: emojis\n        .filter(Boolean)\n        .slice(0, 7)\n        .map(({ emoticons = [], id, name, native, skins = [] }) => {\n          const [firstSkin] = skins;\n\n          return {\n            emoticons,\n            id,\n            name,\n            native: native ?? firstSkin.native,\n          };\n        }) as T[],\n      next: null, // todo: generate cursor\n    };\n  }\n\n  protected filterQueryResults(items: T[]): T[] | Promise<T[]> {\n    return items.map((item) => ({\n      ...item,\n      ...getTokenizedSuggestionDisplayName({\n        displayName: item.id,\n        searchToken: this.searchQuery,\n      }),\n    }));\n  }\n}\n\nconst DEFAULT_OPTIONS: TextComposerMiddlewareOptions = { minChars: 1, trigger: ':' };\n\nexport type EmojiMiddleware<T extends EmojiSearchIndexResult = EmojiSearchIndexResult> =\n  Middleware<\n    TextComposerMiddlewareExecutorState<EmojiSuggestion<T>>,\n    'onChange' | 'onSuggestionItemSelect'\n  >;\n\n/**\n * Creates the text composer middleware that suggests emojis for a typed `:query` and replaces a\n * completed emoticon with its emoji.\n *\n * ```ts\n * composer.textComposer.middlewareExecutor.insert({\n *   middleware: [createTextComposerEmojiMiddleware(SearchIndex) as TextComposerMiddleware],\n *   position: { before: 'stream-io/text-composer/mentions-middleware' },\n *   unique: true,\n * });\n * ```\n *\n * @param emojiSearchIndex - Index searched for matching emojis.\n * @param options - `trigger` (defaults to `':'`) and `minChars` (defaults to 1).\n * @returns The middleware to register on a text composer's middleware executor.\n */\nexport const createTextComposerEmojiMiddleware = (\n  emojiSearchIndex: EmojiSearchIndex,\n  options?: Partial<TextComposerMiddlewareOptions>,\n): EmojiMiddleware => {\n  const finalOptions = mergeWith({}, DEFAULT_OPTIONS, options ?? {});\n  const emojiSearchSource = new EmojiSearchSource(emojiSearchIndex);\n  emojiSearchSource.activate();\n\n  return {\n    id: 'stream-io/emoji-middleware',\n    // eslint-disable-next-line sort-keys\n    handlers: {\n      onChange: async ({ complete, forward, next, state }) => {\n        if (!state.selection) return forward();\n\n        const triggerWithToken = getTriggerCharWithToken({\n          acceptTrailingSpaces: false,\n          text: state.text.slice(0, state.selection.end),\n          trigger: finalOptions.trigger,\n        });\n\n        const triggerWasRemoved =\n          !triggerWithToken || triggerWithToken.length < finalOptions.minChars;\n\n        if (triggerWasRemoved) {\n          const hasSuggestionsForTrigger =\n            state.suggestions?.trigger === finalOptions.trigger;\n          const newState = { ...state };\n          if (hasSuggestionsForTrigger && newState.suggestions) {\n            delete newState.suggestions;\n          }\n          return next(newState);\n        }\n\n        const newSearchTriggerred =\n          triggerWithToken && triggerWithToken === finalOptions.trigger;\n\n        if (newSearchTriggerred) {\n          emojiSearchSource.resetStateAndActivate();\n        }\n\n        const textWithReplacedWord = await replaceWordWithEntity({\n          caretPosition: state.selection.end,\n          getEntityString: async (word: string) => {\n            const { items } = await emojiSearchSource.query(word);\n\n            const emoji = items\n              .filter(Boolean)\n              .slice(0, 10)\n              .find(({ emoticons }) => !!emoticons?.includes(word));\n\n            if (!emoji) return null;\n\n            const [firstSkin] = emoji.skins ?? [];\n\n            return emoji.native ?? firstSkin.native;\n          },\n          text: state.text,\n        });\n\n        if (textWithReplacedWord !== state.text) {\n          return complete({\n            ...state,\n            suggestions: undefined, // prevents the executor from running the first page query\n            text: textWithReplacedWord,\n          });\n        }\n\n        return complete({\n          ...state,\n          suggestions: {\n            query: triggerWithToken.slice(1),\n            searchSource: emojiSearchSource,\n            trigger: finalOptions.trigger,\n          },\n        });\n      },\n      onSuggestionItemSelect: ({ complete, forward, state }) => {\n        const { selectedSuggestion } = state.change ?? {};\n        if (!selectedSuggestion || state.suggestions?.trigger !== finalOptions.trigger)\n          return forward();\n\n        emojiSearchSource.resetStateAndActivate();\n        return complete({\n          ...state,\n          ...insertItemWithTrigger({\n            insertText: `${'native' in selectedSuggestion ? selectedSuggestion.native : ''} `,\n            selection: state.selection,\n            text: state.text,\n            trigger: finalOptions.trigger,\n          }),\n          suggestions: undefined,\n        });\n      },\n    },\n  };\n};\n"],"mappings":";;;AAwBA,IAAM,oBAAN,cAEU,iBAAoB;CAC5B,OAAkC;CAClC;CAEA,YAAY,kBAAoC,SAA+B;EAC7E,MAAM,OAAO;EACb,KAAK,mBAAmB;CAC1B;CAEA,MAAM,MAAM,aAAqB;EAC/B,IAAI,YAAY,WAAW,GACzB,OAAO;GAAE,OAAO,CAAC;GAAU,MAAM;EAAK;EAKxC,OAAO;GACL,QAJc,MAAM,KAAK,iBAAiB,OAAO,WAAW,KAAM,CAAC,EAAA,CAKhE,OAAO,OAAO,CAAC,CACf,MAAM,GAAG,CAAC,CAAC,CACX,KAAK,EAAE,YAAY,CAAC,GAAG,IAAI,MAA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