2021-11-30 09:54:14 -05:00
|
|
|
import { useEffect, useState, useCallback } from 'react'
|
|
|
|
import { useDetachContext } from '../context/detach-context'
|
|
|
|
import getMeta from '../../utils/meta'
|
|
|
|
|
|
|
|
const debugPdfDetach = getMeta('ol-debugPdfDetach')
|
|
|
|
|
|
|
|
export default function useDetachState(
|
|
|
|
key,
|
|
|
|
defaultValue,
|
|
|
|
senderRole,
|
|
|
|
targetRole
|
|
|
|
) {
|
|
|
|
const [value, setValue] = useState(defaultValue)
|
|
|
|
|
2022-03-31 07:22:36 -04:00
|
|
|
const {
|
|
|
|
role,
|
|
|
|
broadcastEvent,
|
|
|
|
lastDetachedConnectedAt,
|
|
|
|
addEventHandler,
|
|
|
|
deleteEventHandler,
|
|
|
|
} = useDetachContext()
|
2021-11-30 09:54:14 -05:00
|
|
|
|
|
|
|
const eventName = `state-${key}`
|
|
|
|
|
2022-03-31 07:22:36 -04:00
|
|
|
// lastDetachedConnectedAt is added as a dependency in order to re-broadcast
|
|
|
|
// all states when a new detached tab connects
|
2021-11-30 09:54:14 -05:00
|
|
|
useEffect(() => {
|
|
|
|
if (role === senderRole) {
|
|
|
|
broadcastEvent(eventName, { value })
|
|
|
|
}
|
2022-03-31 07:22:36 -04:00
|
|
|
}, [
|
|
|
|
role,
|
|
|
|
senderRole,
|
|
|
|
eventName,
|
|
|
|
value,
|
|
|
|
broadcastEvent,
|
|
|
|
lastDetachedConnectedAt,
|
|
|
|
])
|
2021-11-30 09:54:14 -05:00
|
|
|
|
|
|
|
const handleStateEvent = useCallback(
|
|
|
|
message => {
|
|
|
|
if (message.event !== eventName) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (role !== targetRole) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (debugPdfDetach) {
|
|
|
|
console.log(`Set ${message.data.value} for ${eventName}`)
|
|
|
|
}
|
|
|
|
setValue(message.data.value)
|
|
|
|
},
|
|
|
|
[role, targetRole, eventName, setValue]
|
|
|
|
)
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
addEventHandler(handleStateEvent)
|
|
|
|
return () => deleteEventHandler(handleStateEvent)
|
|
|
|
}, [addEventHandler, deleteEventHandler, handleStateEvent])
|
|
|
|
|
|
|
|
return [value, setValue]
|
|
|
|
}
|