index.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {
  2. memo,
  3. useEffect,
  4. } from 'react'
  5. import {
  6. $insertNodes,
  7. COMMAND_PRIORITY_EDITOR,
  8. createCommand,
  9. } from 'lexical'
  10. import { mergeRegister } from '@lexical/utils'
  11. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  12. import type { WorkflowVariableBlockType } from '../../types'
  13. import {
  14. $createWorkflowVariableBlockNode,
  15. WorkflowVariableBlockNode,
  16. } from './node'
  17. import type { Node } from '@/app/components/workflow/types'
  18. export const INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND = createCommand('INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND')
  19. export const DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND = createCommand('DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND')
  20. export const CLEAR_HIDE_MENU_TIMEOUT = createCommand('CLEAR_HIDE_MENU_TIMEOUT')
  21. export const UPDATE_WORKFLOW_NODES_MAP = createCommand('UPDATE_WORKFLOW_NODES_MAP')
  22. export type WorkflowVariableBlockProps = {
  23. getWorkflowNode: (nodeId: string) => Node
  24. onInsert?: () => void
  25. onDelete?: () => void
  26. }
  27. const WorkflowVariableBlock = memo(({
  28. workflowNodesMap,
  29. onInsert,
  30. onDelete,
  31. }: WorkflowVariableBlockType) => {
  32. const [editor] = useLexicalComposerContext()
  33. useEffect(() => {
  34. editor.update(() => {
  35. editor.dispatchCommand(UPDATE_WORKFLOW_NODES_MAP, workflowNodesMap)
  36. })
  37. }, [editor, workflowNodesMap])
  38. useEffect(() => {
  39. if (!editor.hasNodes([WorkflowVariableBlockNode]))
  40. throw new Error('WorkflowVariableBlockPlugin: WorkflowVariableBlock not registered on editor')
  41. return mergeRegister(
  42. editor.registerCommand(
  43. INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND,
  44. (variables: string[]) => {
  45. editor.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
  46. const workflowVariableBlockNode = $createWorkflowVariableBlockNode(variables, workflowNodesMap)
  47. $insertNodes([workflowVariableBlockNode])
  48. if (onInsert)
  49. onInsert()
  50. return true
  51. },
  52. COMMAND_PRIORITY_EDITOR,
  53. ),
  54. editor.registerCommand(
  55. DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND,
  56. () => {
  57. if (onDelete)
  58. onDelete()
  59. return true
  60. },
  61. COMMAND_PRIORITY_EDITOR,
  62. ),
  63. )
  64. }, [editor, onInsert, onDelete, workflowNodesMap])
  65. return null
  66. })
  67. WorkflowVariableBlock.displayName = 'WorkflowVariableBlock'
  68. export { WorkflowVariableBlock }
  69. export { WorkflowVariableBlockNode } from './node'
  70. export { default as WorkflowVariableBlockReplacementBlock } from './workflow-variable-block-replacement-block'