overleaf/services/web/frontend/js/features/pdf-preview/hooks/use-compile-triggers.js
Alf Eaton 50df230846 [web] Upgrade Prettier to match version in monorepo root (#6231)
GitOrigin-RevId: 02f97af1b9704782eee77a0b7dfc477ada23e34d
2022-01-11 09:03:23 +00:00

65 lines
2.1 KiB
JavaScript

import { useCallback, useEffect } from 'react'
import getMeta from '../../../utils/meta'
import { useCompileContext } from '../../../shared/context/compile-context'
import { useDetachContext } from '../../../shared/context/detach-context'
import useEventListener from '../../../shared/hooks/use-event-listener'
import useDetachAction from '../../../shared/hooks/use-detach-action'
import usePreviousValue from '../../../shared/hooks/use-previous-value'
const showPdfDetach = getMeta('ol-showPdfDetach')
const debugPdfDetach = getMeta('ol-debugPdfDetach')
export default function useCompileTriggers() {
const { startCompile, setChangedAt, cleanupCompileResult, setError } =
useCompileContext()
const { role: detachRole } = useDetachContext()
// recompile on key press
const startOrTriggerCompile = useDetachAction(
'start-compile',
startCompile,
'detacher',
'detached'
)
const compileHandler = useCallback(
event => {
showPdfDetach
? startOrTriggerCompile(event.detail)
: startCompile(event.detail)
},
[startOrTriggerCompile, startCompile]
)
useEventListener('pdf:recompile', compileHandler)
// record doc changes when notified by the editor
const setOrTriggerChangedAt = useDetachAction(
'set-changed-at',
setChangedAt,
'detacher',
'detached'
)
const setChangedAtHandler = useCallback(() => {
showPdfDetach ? setOrTriggerChangedAt(Date.now()) : setChangedAt(Date.now())
}, [setOrTriggerChangedAt, setChangedAt])
useEventListener('doc:changed', setChangedAtHandler)
useEventListener('doc:saved', setChangedAtHandler)
// clear preview and recompile when the detach role is reset
const previousDetachRole = usePreviousValue(detachRole)
useEffect(() => {
if (previousDetachRole && !detachRole) {
if (debugPdfDetach) {
console.log('Recompile on reattach', { previousDetachRole, detachRole })
}
cleanupCompileResult()
setError()
startCompile()
}
}, [
cleanupCompileResult,
setError,
startCompile,
previousDetachRole,
detachRole,
])
}