Line data Source code
1 : import type { Ref } from 'vue'
2 : import { ref } from 'vue'
3 : import { useMaskEditorStore } from './maskEditorStore'
4 :
5 0 : function isTextEntryTarget(element: Element | null): boolean {
6 0 : return (
7 : element instanceof HTMLInputElement ||
8 : element instanceof HTMLTextAreaElement ||
9 : (element instanceof HTMLElement && element.isContentEditable)
10 : )
11 : }
12 :
13 29 : export function useKeyboard(containerRef?: Ref<HTMLElement | undefined>) {
14 29 : const store = useMaskEditorStore()
15 :
16 29 : const keysDown = ref<string[]>([])
17 :
18 29 : const isKeyDown = (key: string): boolean => {
19 209 : return keysDown.value.includes(key)
20 : }
21 :
22 29 : const clearKeys = (): void => {
23 0 : keysDown.value = []
24 : }
25 :
26 29 : const handleSpaceKey = (event: KeyboardEvent): void => {
27 0 : const activeElement = document.activeElement
28 0 : const isStuckInsideEditor =
29 : activeElement !== null && !!containerRef?.value?.contains(activeElement)
30 0 : if (isTextEntryTarget(activeElement) && !isStuckInsideEditor) return
31 :
32 0 : event.preventDefault()
33 0 : if (activeElement instanceof HTMLElement) {
34 0 : activeElement.blur()
35 : }
36 : }
37 :
38 29 : const handleKeyDown = (event: KeyboardEvent): void => {
39 4 : if (!keysDown.value.includes(event.key)) {
40 4 : keysDown.value.push(event.key)
41 : }
42 :
43 4 : if (event.key === ' ') {
44 0 : handleSpaceKey(event)
45 : }
46 :
47 4 : if ((event.ctrlKey || event.metaKey) && !event.altKey) {
48 4 : const key = event.key.toUpperCase()
49 :
50 4 : if ((key === 'Y' && !event.shiftKey) || (key === 'Z' && event.shiftKey)) {
51 0 : store.canvasHistory.redo()
52 4 : } else if (key === 'Z' && !event.shiftKey) {
53 2 : store.canvasHistory.undo()
54 : }
55 : }
56 : }
57 :
58 29 : const handleKeyUp = (event: KeyboardEvent): void => {
59 4 : keysDown.value = keysDown.value.filter((key) => key !== event.key)
60 : }
61 :
62 29 : const addListeners = (): void => {
63 : // Capture phase: the Mask Editor content root carries `@keydown.stop`
64 : // (MaskEditorContent.vue), so a bubble-phase listener never sees keydowns
65 : // that originate inside it. Under the Reka dialog the focus trap keeps
66 : // focus on an in-editor input, so Ctrl+Z/Y (undo/redo) and the space-pan
67 : // blur were swallowed. Capturing runs this before that stopPropagation.
68 29 : document.addEventListener('keydown', handleKeyDown, true)
69 29 : document.addEventListener('keyup', handleKeyUp)
70 29 : window.addEventListener('blur', clearKeys)
71 : }
72 :
73 29 : const removeListeners = (): void => {
74 7 : document.removeEventListener('keydown', handleKeyDown, true)
75 7 : document.removeEventListener('keyup', handleKeyUp)
76 7 : window.removeEventListener('blur', clearKeys)
77 : }
78 :
79 29 : return {
80 : isKeyDown,
81 : addListeners,
82 : removeListeners
83 : }
84 : }
|