2021-11-30 09:54:14 -05:00
|
|
|
import { useCallback, useEffect } from 'react'
|
|
|
|
import { useDetachContext } from '../context/detach-context'
|
|
|
|
import getMeta from '../../utils/meta'
|
2023-01-09 09:33:43 -05:00
|
|
|
import { DetachRole, DetachTargetRole, Message } from './use-detach-state'
|
2021-11-30 09:54:14 -05:00
|
|
|
|
|
|
|
const debugPdfDetach = getMeta('ol-debugPdfDetach')
|
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
function useDetachAction<
|
|
|
|
A,
|
|
|
|
S extends DetachRole,
|
|
|
|
T extends DetachTargetRole<S>
|
|
|
|
>(
|
|
|
|
actionName: string,
|
|
|
|
actionFunction: (...args: A[]) => void,
|
|
|
|
senderRole: S,
|
|
|
|
targetRole: T
|
2021-11-30 09:54:14 -05:00
|
|
|
) {
|
2022-01-10 05:23:05 -05:00
|
|
|
const { role, broadcastEvent, addEventHandler, deleteEventHandler } =
|
|
|
|
useDetachContext()
|
2021-11-30 09:54:14 -05:00
|
|
|
|
2023-01-09 09:33:43 -05:00
|
|
|
const eventName: Message['event'] = `action-${actionName}`
|
2021-11-30 09:54:14 -05:00
|
|
|
|
|
|
|
const triggerFn = useCallback(
|
2023-01-09 09:33:43 -05:00
|
|
|
(...args: A[]) => {
|
2021-11-30 09:54:14 -05:00
|
|
|
if (role === senderRole) {
|
|
|
|
broadcastEvent(eventName, { args })
|
|
|
|
} else {
|
|
|
|
actionFunction(...args)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
[role, senderRole, eventName, actionFunction, broadcastEvent]
|
|
|
|
)
|
|
|
|
|
|
|
|
const handleActionEvent = useCallback(
|
2023-01-09 09:33:43 -05:00
|
|
|
(message: Message<A>) => {
|
2021-11-30 09:54:14 -05:00
|
|
|
if (message.event !== eventName) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (role !== targetRole) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (debugPdfDetach) {
|
|
|
|
console.log(`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
|
|
|
|
}
|
2023-01-09 09:33:43 -05:00
|
|
|
|
|
|
|
export default useDetachAction
|