Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

1.7 KB
Raw Blame
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { $getRoot, $insertNodes } from 'lexical'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { textToEditorState } from '../utils'
import { CustomTextNode } from './custom-text/node'

export const PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER =
  'PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER'
export const PROMPT_EDITOR_INSERT_QUICKLY = 'PROMPT_EDITOR_INSERT_QUICKLY'

type UpdateBlockProps = {
  instanceId?: string
}
const UpdateBlock = ({ instanceId }: UpdateBlockProps) => {
  const { eventEmitter } = useEventEmitterContextContext()
  const [editor] = useLexicalComposerContext()

  eventEmitter?.useSubscription((v: any) => {
    if (v.type === PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER && v.instanceId === instanceId) {
      const editorState = editor.parseEditorState(textToEditorState(v.payload))
      editor.setEditorState(editorState)
      // Commit synchronously so both onChange reports fire before the emitter's caller writes its
      // own state. A deferred commit could report after that write from a stale render and undo it.
      editor.update(
        () => {
          $getRoot()
            .getAllTextNodes()
            .forEach((node) => {
              if (node instanceof CustomTextNode) node.markDirty()
            })
        },
        { discrete: true },
      )
    }
  })

  eventEmitter?.useSubscription((v: any) => {
    if (v.type === PROMPT_EDITOR_INSERT_QUICKLY && v.instanceId === instanceId) {
      editor.focus()
      editor.update(() => {
        const textNode = new CustomTextNode('/')
        $insertNodes([textNode])
      })
    }
  })

  return null
}

export default UpdateBlock