overleaf/services/web/frontend/js/features/pdf-preview/hooks/use-compile-triggers.js
Alf Eaton 65b0fd73ea Improve "compile" keyboard shortcut handling (#10624)
* Improve "compile" keypress handling
* Remove "compile" keypress handling from PDF preview
* Remove compile shortcuts from CM6
* Use an event for Vim keybindings
* Remove event handlers from Angular/Ace
* Move useCompileTriggers into DetachCompileProvider

GitOrigin-RevId: 7f0e667b5106a849458e06ebb0f7a413d5d63430
2022-11-29 09:04:04 +00:00

58 lines
1.6 KiB
JavaScript

import { useCallback, useEffect } from 'react'
import useEventListener from '../../../shared/hooks/use-event-listener'
import useDetachAction from '../../../shared/hooks/use-detach-action'
export const startCompileKeypress = event => {
if (event.shiftKey || event.altKey) {
return false
}
if (event.ctrlKey) {
// Ctrl+s / Ctrl+Enter / Ctrl+.
if (event.key === 's' || event.key === 'Enter' || event.key === '.') {
return true
}
} else if (event.metaKey) {
// Cmd+s / Cmd+Enter
if (event.key === 's' || event.key === 'Enter') {
return true
}
}
}
export default function useCompileTriggers(startCompile, setChangedAt) {
const handleKeyDown = useCallback(
event => {
if (startCompileKeypress(event)) {
event.preventDefault()
startCompile()
}
},
[startCompile]
)
const handleStartCompile = useCallback(() => {
startCompile()
}, [startCompile])
useEventListener('pdf:recompile', handleStartCompile)
useEffect(() => {
document.body.addEventListener('keydown', handleKeyDown)
return () => {
document.body.removeEventListener('keydown', handleKeyDown)
}
}, [handleKeyDown])
// record doc changes when notified by the editor
const setOrTriggerChangedAt = useDetachAction(
'set-changed-at',
setChangedAt,
'detacher',
'detached'
)
const setChangedAtHandler = useCallback(() => {
setOrTriggerChangedAt(Date.now())
}, [setOrTriggerChangedAt])
useEventListener('doc:changed', setChangedAtHandler)
useEventListener('doc:saved', setChangedAtHandler) // TODO: store this separately?
}