on-blur-or-focus-block.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import type { FC } from 'react'
  2. import { useEffect, useRef } from 'react'
  3. import {
  4. BLUR_COMMAND,
  5. COMMAND_PRIORITY_EDITOR,
  6. FOCUS_COMMAND,
  7. KEY_ESCAPE_COMMAND,
  8. } from 'lexical'
  9. import { mergeRegister } from '@lexical/utils'
  10. import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
  11. import { CLEAR_HIDE_MENU_TIMEOUT } from './workflow-variable-block'
  12. type OnBlurBlockProps = {
  13. onBlur?: () => void
  14. onFocus?: () => void
  15. }
  16. const OnBlurBlock: FC<OnBlurBlockProps> = ({
  17. onBlur,
  18. onFocus,
  19. }) => {
  20. const [editor] = useLexicalComposerContext()
  21. const ref = useRef<any>(null)
  22. useEffect(() => {
  23. return mergeRegister(
  24. editor.registerCommand(
  25. CLEAR_HIDE_MENU_TIMEOUT,
  26. () => {
  27. if (ref.current) {
  28. clearTimeout(ref.current)
  29. ref.current = null
  30. }
  31. return true
  32. },
  33. COMMAND_PRIORITY_EDITOR,
  34. ),
  35. editor.registerCommand(
  36. BLUR_COMMAND,
  37. () => {
  38. ref.current = setTimeout(() => {
  39. editor.dispatchCommand(KEY_ESCAPE_COMMAND, new KeyboardEvent('keydown', { key: 'Escape' }))
  40. }, 200)
  41. if (onBlur)
  42. onBlur()
  43. return true
  44. },
  45. COMMAND_PRIORITY_EDITOR,
  46. ),
  47. editor.registerCommand(
  48. FOCUS_COMMAND,
  49. () => {
  50. if (onFocus)
  51. onFocus()
  52. return true
  53. },
  54. COMMAND_PRIORITY_EDITOR,
  55. ),
  56. )
  57. }, [editor, onBlur, onFocus])
  58. return null
  59. }
  60. export default OnBlurBlock