index.tsx 1.7 KB

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