carbon-react
Version:
A library of reusable React components for easily building user interfaces.
2 lines (1 loc) • 2.33 kB
JavaScript
import{jsx as e}from"react/jsx-runtime";import{useLexicalComposerContext as t}from"@lexical/react/LexicalComposerContext";import{LexicalTypeaheadMenuPlugin as n}from"@lexical/react/LexicalTypeaheadMenuPlugin";import{$isTextNode as o,$createTextNode as r,KEY_BACKSPACE_COMMAND as i,$getSelection as s,$isRangeSelection as l,TextNode as a,COMMAND_PRIORITY_LOW as m}from"lexical";import{useState as c,useMemo as p,useCallback as d,useEffect as u}from"react";import f from"react-dom";import{SUGGESTION_LIST_LENGTH_LIMIT as x}from"./constants.js";import{getPossibleQueryMatch as g}from"./helpers.js";import{MentionsTypeaheadMenuItem as h}from"./mentions-typeahead-menu-item.component.js";import{MentionTypeaheadOption as C}from"./mention-typeahead-option.class.js";import{$createMentionNode as j,$isMentionNode as y}from"../../__nodes__/mention.node.js";import _ from"../../../../../hooks/__internal__/useLocale/useLocale.js";import{TypeaheadPopover as L,MentionsList as $}from"./mentions.style.js";const b=({namespace:b,searchOptions:v})=>{const[w]=t(),[S,T]=c(null),k=p((()=>S?v.filter((e=>e.name.toLowerCase().includes(S.toLowerCase()))):[]),[S,v]),A=_(),O=p((()=>k.map((e=>new C(e.id,e.name,e.initials,e.iconType,e.src))).slice(0,x)),[k]),E=d(((e,t,n)=>{w.update((()=>{const i=j(`@${e.name}`);t&&t.replace(i);const s=i.getNextSibling();if(o(s)&&s.getTextContent().startsWith(" "))s.select(1,1);else{const e=r(" ");i.insertAfter(e),e.select()}n()}))}),[w]);return u((()=>w.registerCommand(i,(()=>{const e=s();if(!l(e)||!e.isCollapsed())return!1;const{anchor:t}=e,n=t.getNode();if(y(n)){const e=new a(n.getTextContent());return n.replace(e),!0}return!1}),m)),[w]),e(n,{onQueryChange:T,onSelectOption:E,triggerFn:e=>g(e),options:O,menuRenderFn:(t,{selectedIndex:n,selectOptionAndCleanUp:o,setHighlightedIndex:r})=>t.current&&k.length?f.createPortal(e(L,{id:`${b}-mentions-menu`,children:e($,{"data-role":"mention-list",id:`${b}-mention-list`,role:"listbox","aria-label":A.textEditor.mentions.listAriaLabel(),children:O.map(((t,i)=>{var s,l;const a=null!==(l=null!==(s=t.key)&&void 0!==s?s:t.id)&&void 0!==l?l:`${b}-${i}`;return e(h,{index:i,isSelected:n===i,onClick:()=>{r(i),o(t)},onMouseEnter:()=>{r(i)},option:t,namespace:b,currentQueryString:null!=S?S:void 0},a)}))})}),t.current):null})};export{b as MentionsPlugin,b as default};