您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

last-run-block-replacement-block.tsx 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import {
  2. memo,
  3. useCallback,
  4. useEffect,
  5. } from 'react'
  6. import { $applyNodeReplacement } from 'lexical'
  7. import { mergeRegister } from '@lexical/utils'
  8. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  9. import { decoratorTransform } from '../../utils'
  10. import { LAST_RUN_PLACEHOLDER_TEXT } from '../../constants'
  11. import type { LastRunBlockType } from '../../types'
  12. import {
  13. $createLastRunBlockNode,
  14. LastRunBlockNode,
  15. } from './node'
  16. import { CustomTextNode } from '../custom-text/node'
  17. const REGEX = new RegExp(LAST_RUN_PLACEHOLDER_TEXT)
  18. const LastRunReplacementBlock = ({
  19. onInsert,
  20. }: LastRunBlockType) => {
  21. const [editor] = useLexicalComposerContext()
  22. useEffect(() => {
  23. if (!editor.hasNodes([LastRunBlockNode]))
  24. throw new Error('LastRunMessageBlockNodePlugin: LastRunMessageBlockNode not registered on editor')
  25. }, [editor])
  26. const createLastRunBlockNode = useCallback((): LastRunBlockNode => {
  27. if (onInsert)
  28. onInsert()
  29. return $applyNodeReplacement($createLastRunBlockNode())
  30. }, [onInsert])
  31. const getMatch = useCallback((text: string) => {
  32. const matchArr = REGEX.exec(text)
  33. if (matchArr === null)
  34. return null
  35. const startOffset = matchArr.index
  36. const endOffset = startOffset + LAST_RUN_PLACEHOLDER_TEXT.length
  37. return {
  38. end: endOffset,
  39. start: startOffset,
  40. }
  41. }, [])
  42. useEffect(() => {
  43. REGEX.lastIndex = 0
  44. return mergeRegister(
  45. editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getMatch, createLastRunBlockNode)),
  46. )
  47. // eslint-disable-next-line react-hooks/exhaustive-deps
  48. }, [])
  49. return null
  50. }
  51. export default memo(LastRunReplacementBlock)