overleaf/services/web/frontend/js/shared/hooks/use-detach-state.js
ilkin-overleaf ea2af56f7b Merge pull request #11122 from overleaf/ii-rollback-some-ts-hooks-to-js
[web] Revert detach hooks from TS to JS

GitOrigin-RevId: c108fe219d472f0c0b745dc8648fd15375f0e083
2023-01-10 09:06:14 +00:00

62 lines
1.4 KiB
JavaScript

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)
const {
role,
broadcastEvent,
lastDetachedConnectedAt,
addEventHandler,
deleteEventHandler,
} = useDetachContext()
const eventName = `state-${key}`
// lastDetachedConnectedAt is added as a dependency in order to re-broadcast
// all states when a new detached tab connects
useEffect(() => {
if (role === senderRole) {
broadcastEvent(eventName, { value })
}
}, [
role,
senderRole,
eventName,
value,
broadcastEvent,
lastDetachedConnectedAt,
])
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]
}