index.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import {
  2. useCallback,
  3. useEffect,
  4. } from 'react'
  5. import type { TextNode } from 'lexical'
  6. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  7. import { useLexicalTextEntity } from '../../hooks'
  8. import {
  9. $createVariableValueBlockNode,
  10. VariableValueBlockNode,
  11. } from './node'
  12. import { getHashtagRegexString } from './utils'
  13. const REGEX = new RegExp(getHashtagRegexString(), 'i')
  14. const VariableValueBlock = () => {
  15. const [editor] = useLexicalComposerContext()
  16. useEffect(() => {
  17. if (!editor.hasNodes([VariableValueBlockNode]))
  18. throw new Error('VariableValueBlockPlugin: VariableValueNode not registered on editor')
  19. }, [editor])
  20. const createVariableValueBlockNode = useCallback((textNode: TextNode): VariableValueBlockNode => {
  21. return $createVariableValueBlockNode(textNode.getTextContent())
  22. }, [])
  23. const getVariableValueMatch = useCallback((text: string) => {
  24. const matchArr = REGEX.exec(text)
  25. if (matchArr === null)
  26. return null
  27. const hashtagLength = matchArr[0].length
  28. const startOffset = matchArr.index
  29. const endOffset = startOffset + hashtagLength
  30. return {
  31. end: endOffset,
  32. start: startOffset,
  33. }
  34. }, [])
  35. useLexicalTextEntity<VariableValueBlockNode>(
  36. getVariableValueMatch,
  37. VariableValueBlockNode,
  38. createVariableValueBlockNode,
  39. )
  40. return null
  41. }
  42. export default VariableValueBlock