index.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import type { FC } from 'react'
  2. import { useEffect } from 'react'
  3. import {
  4. $insertNodes,
  5. COMMAND_PRIORITY_EDITOR,
  6. createCommand,
  7. } from 'lexical'
  8. import { mergeRegister } from '@lexical/utils'
  9. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  10. import {
  11. $createQueryBlockNode,
  12. QueryBlockNode,
  13. } from './node'
  14. export const INSERT_QUERY_BLOCK_COMMAND = createCommand('INSERT_QUERY_BLOCK_COMMAND')
  15. export const DELETE_QUERY_BLOCK_COMMAND = createCommand('DELETE_QUERY_BLOCK_COMMAND')
  16. export type QueryBlockProps = {
  17. onInsert?: () => void
  18. onDelete?: () => void
  19. }
  20. const QueryBlock: FC<QueryBlockProps> = ({
  21. onInsert,
  22. onDelete,
  23. }) => {
  24. const [editor] = useLexicalComposerContext()
  25. useEffect(() => {
  26. if (!editor.hasNodes([QueryBlockNode]))
  27. throw new Error('QueryBlockPlugin: QueryBlock not registered on editor')
  28. return mergeRegister(
  29. editor.registerCommand(
  30. INSERT_QUERY_BLOCK_COMMAND,
  31. () => {
  32. const contextBlockNode = $createQueryBlockNode()
  33. $insertNodes([contextBlockNode])
  34. if (onInsert)
  35. onInsert()
  36. return true
  37. },
  38. COMMAND_PRIORITY_EDITOR,
  39. ),
  40. editor.registerCommand(
  41. DELETE_QUERY_BLOCK_COMMAND,
  42. () => {
  43. if (onDelete)
  44. onDelete()
  45. return true
  46. },
  47. COMMAND_PRIORITY_EDITOR,
  48. ),
  49. )
  50. }, [editor, onInsert, onDelete])
  51. return null
  52. }
  53. export default QueryBlock