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