index.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 { ContextBlockType } from '../../types'
  13. import {
  14. $createContextBlockNode,
  15. ContextBlockNode,
  16. } from './node'
  17. export const INSERT_CONTEXT_BLOCK_COMMAND = createCommand('INSERT_CONTEXT_BLOCK_COMMAND')
  18. export const DELETE_CONTEXT_BLOCK_COMMAND = createCommand('DELETE_CONTEXT_BLOCK_COMMAND')
  19. export type Dataset = {
  20. id: string
  21. name: string
  22. type: string
  23. }
  24. const ContextBlock = memo(({
  25. datasets = [],
  26. onAddContext = () => {},
  27. onInsert,
  28. onDelete,
  29. canNotAddContext,
  30. }: ContextBlockType) => {
  31. const [editor] = useLexicalComposerContext()
  32. useEffect(() => {
  33. if (!editor.hasNodes([ContextBlockNode]))
  34. throw new Error('ContextBlockPlugin: ContextBlock not registered on editor')
  35. return mergeRegister(
  36. editor.registerCommand(
  37. INSERT_CONTEXT_BLOCK_COMMAND,
  38. () => {
  39. const contextBlockNode = $createContextBlockNode(datasets, onAddContext, canNotAddContext)
  40. $insertNodes([contextBlockNode])
  41. if (onInsert)
  42. onInsert()
  43. return true
  44. },
  45. COMMAND_PRIORITY_EDITOR,
  46. ),
  47. editor.registerCommand(
  48. DELETE_CONTEXT_BLOCK_COMMAND,
  49. () => {
  50. if (onDelete)
  51. onDelete()
  52. return true
  53. },
  54. COMMAND_PRIORITY_EDITOR,
  55. ),
  56. )
  57. }, [editor, datasets, onAddContext, onInsert, onDelete, canNotAddContext])
  58. return null
  59. })
  60. ContextBlock.displayName = 'ContextBlock'
  61. export { ContextBlock }
  62. export { ContextBlockNode } from './node'
  63. export { default as ContextBlockReplacementBlock } from './context-block-replacement-block'