overleaf/services/web/frontend/js/shared/hooks/use-detach-action.js
Jakob Ackermann 1213709578 Merge pull request #14980 from overleaf/jpa-debug-console
[web] migrate frontend logging to debugConsole

GitOrigin-RevId: b03ff9030b03fff059738d2270bc4b4912e79f16
2023-09-28 08:04:12 +00:00

52 lines
1.3 KiB
JavaScript

import { useCallback, useEffect } from 'react'
import { useDetachContext } from '../context/detach-context'
import getMeta from '../../utils/meta'
import { debugConsole } from '@/utils/debugging'
const debugPdfDetach = getMeta('ol-debugPdfDetach')
export default function useDetachAction(
actionName,
actionFunction,
senderRole,
targetRole
) {
const { role, broadcastEvent, addEventHandler, deleteEventHandler } =
useDetachContext()
const eventName = `action-${actionName}`
const triggerFn = useCallback(
(...args) => {
if (role === senderRole) {
broadcastEvent(eventName, { args })
} else {
actionFunction(...args)
}
},
[role, senderRole, eventName, actionFunction, broadcastEvent]
)
const handleActionEvent = useCallback(
message => {
if (message.event !== eventName) {
return
}
if (role !== targetRole) {
return
}
if (debugPdfDetach) {
debugConsole.warn(`Do ${actionFunction.name} on event ${eventName}`)
}
actionFunction(...message.data.args)
},
[role, targetRole, eventName, actionFunction]
)
useEffect(() => {
addEventHandler(handleActionEvent)
return () => deleteEventHandler(handleActionEvent)
}, [addEventHandler, deleteEventHandler, handleActionEvent])
return triggerFn
}