update-block.tsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { $insertNodes } from 'lexical'
  2. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  3. import { textToEditorState } from '../utils'
  4. import { CustomTextNode } from './custom-text/node'
  5. import { CLEAR_HIDE_MENU_TIMEOUT } from './workflow-variable-block'
  6. import { useEventEmitterContextContext } from '@/context/event-emitter'
  7. export const PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER = 'PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER'
  8. export const PROMPT_EDITOR_INSERT_QUICKLY = 'PROMPT_EDITOR_INSERT_QUICKLY'
  9. type UpdateBlockProps = {
  10. instanceId?: string
  11. }
  12. const UpdateBlock = ({
  13. instanceId,
  14. }: UpdateBlockProps) => {
  15. const { eventEmitter } = useEventEmitterContextContext()
  16. const [editor] = useLexicalComposerContext()
  17. eventEmitter?.useSubscription((v: any) => {
  18. if (v.type === PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER && v.instanceId === instanceId) {
  19. const editorState = editor.parseEditorState(textToEditorState(v.payload))
  20. editor.setEditorState(editorState)
  21. }
  22. })
  23. eventEmitter?.useSubscription((v: any) => {
  24. if (v.type === PROMPT_EDITOR_INSERT_QUICKLY && v.instanceId === instanceId) {
  25. editor.focus()
  26. editor.update(() => {
  27. const textNode = new CustomTextNode('/')
  28. $insertNodes([textNode])
  29. editor.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
  30. })
  31. }
  32. })
  33. return null
  34. }
  35. export default UpdateBlock