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. $createHistoryBlockNode,
  12. HistoryBlockNode,
  13. } from './node'
  14. export const INSERT_HISTORY_BLOCK_COMMAND = createCommand('INSERT_HISTORY_BLOCK_COMMAND')
  15. export const DELETE_HISTORY_BLOCK_COMMAND = createCommand('DELETE_HISTORY_BLOCK_COMMAND')
  16. export type RoleName = {
  17. user: string
  18. assistant: string
  19. }
  20. export type HistoryBlockProps = {
  21. roleName: RoleName
  22. onEditRole: () => void
  23. onInsert?: () => void
  24. onDelete?: () => void
  25. }
  26. const HistoryBlock: FC<HistoryBlockProps> = ({
  27. roleName,
  28. onEditRole,
  29. onInsert,
  30. onDelete,
  31. }) => {
  32. const [editor] = useLexicalComposerContext()
  33. useEffect(() => {
  34. if (!editor.hasNodes([HistoryBlockNode]))
  35. throw new Error('HistoryBlockPlugin: HistoryBlock not registered on editor')
  36. return mergeRegister(
  37. editor.registerCommand(
  38. INSERT_HISTORY_BLOCK_COMMAND,
  39. () => {
  40. const historyBlockNode = $createHistoryBlockNode(roleName, onEditRole)
  41. $insertNodes([historyBlockNode])
  42. if (onInsert)
  43. onInsert()
  44. return true
  45. },
  46. COMMAND_PRIORITY_EDITOR,
  47. ),
  48. editor.registerCommand(
  49. DELETE_HISTORY_BLOCK_COMMAND,
  50. () => {
  51. if (onDelete)
  52. onDelete()
  53. return true
  54. },
  55. COMMAND_PRIORITY_EDITOR,
  56. ),
  57. )
  58. }, [editor, roleName, onEditRole, onInsert, onDelete])
  59. return null
  60. }
  61. export default HistoryBlock