use-detach-action.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useCallback, useEffect } from 'react'
  2. import { useDetachContext } from '../context/detach-context'
  3. import getMeta from '../../utils/meta'
  4. import { debugConsole } from '@/utils/debugging'
  5. const debugPdfDetach = getMeta('ol-debugPdfDetach')
  6. export default function useDetachAction(
  7. actionName,
  8. actionFunction,
  9. senderRole,
  10. targetRole
  11. ) {
  12. const { role, broadcastEvent, addEventHandler, deleteEventHandler } =
  13. useDetachContext()
  14. const eventName = `action-${actionName}`
  15. const triggerFn = useCallback(
  16. (...args) => {
  17. if (role === senderRole) {
  18. broadcastEvent(eventName, { args })
  19. } else {
  20. return actionFunction(...args)
  21. }
  22. },
  23. [role, senderRole, eventName, actionFunction, broadcastEvent]
  24. )
  25. const handleActionEvent = useCallback(
  26. message => {
  27. if (message.event !== eventName) {
  28. return
  29. }
  30. if (role !== targetRole) {
  31. return
  32. }
  33. if (debugPdfDetach) {
  34. debugConsole.warn(`Do ${actionFunction.name} on event ${eventName}`)
  35. }
  36. actionFunction(...message.data.args)
  37. },
  38. [role, targetRole, eventName, actionFunction]
  39. )
  40. useEffect(() => {
  41. addEventHandler(handleActionEvent)
  42. return () => deleteEventHandler(handleActionEvent)
  43. }, [addEventHandler, deleteEventHandler, handleActionEvent])
  44. return triggerFn
  45. }