Line data Source code
1 : import { tryOnScopeDispose, useEventListener } from '@vueuse/core'
2 : import { shallowRef } from 'vue'
3 :
4 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
5 :
6 9725 : export function useShiftKeySync() {
7 9725 : const shiftKeyState = shallowRef(false)
8 9725 : let canvasEl: HTMLCanvasElement | null = null
9 :
10 : /**
11 : * Synchronizes shift key state to LiteGraph canvas by dispatching synthetic keyboard events.
12 : *
13 : * Only dispatches events when shift state actually changes to minimize overhead.
14 : * Canvas reference is lazily initialized on first sync.
15 : *
16 : * @param isShiftPressed - Current shift key state to synchronize
17 : */
18 47 : function syncShiftState(isShiftPressed: boolean) {
19 47 : if (isShiftPressed === shiftKeyState.value) return
20 :
21 : // Lazy-initialize canvas reference on first use
22 0 : if (!canvasEl) {
23 0 : canvasEl = useCanvasStore().canvas?.canvas ?? null
24 0 : if (!canvasEl) return // Canvas not ready yet
25 : }
26 :
27 0 : shiftKeyState.value = isShiftPressed
28 47 : canvasEl.dispatchEvent(
29 : new KeyboardEvent(isShiftPressed ? 'keydown' : 'keyup', {
30 : key: 'Shift',
31 : shiftKey: isShiftPressed,
32 : bubbles: true
33 : })
34 : )
35 : }
36 :
37 : /**
38 : * Tracks shift key state during drag/resize operations and synchronizes to canvas.
39 : *
40 : * Attaches window-level keyboard event listeners for the duration of the operation.
41 : * Listeners are automatically cleaned up when the returned function is called.
42 : *
43 : * @param initialShiftKey - Shift state when drag/resize begins
44 : * @returns Cleanup function that removes event listeners - must be called when operation ends
45 : *
46 : * @example
47 : * ```ts
48 : * function startDrag(event: PointerEvent) {
49 : * const stopTracking = trackShiftKey(event.shiftKey)
50 : *
51 : * const handlePointerUp = () => {
52 : * stopTracking() // Cleanup listeners
53 : * }
54 : * }
55 : * ```
56 : */
57 47 : function trackShiftKey(initialShiftKey: boolean): () => void {
58 : // Sync initial shift state
59 47 : syncShiftState(initialShiftKey)
60 :
61 : // Listen for shift key press/release during the operation
62 47 : const handleKeyEvent = (e: KeyboardEvent) => {
63 3 : if (e.key !== 'Shift') return
64 0 : syncShiftState(e.shiftKey)
65 : }
66 :
67 47 : const stopKeydown = useEventListener(window, 'keydown', handleKeyEvent, {
68 : passive: true
69 : })
70 47 : const stopKeyup = useEventListener(window, 'keyup', handleKeyEvent, {
71 : passive: true
72 : })
73 :
74 : // Return cleanup function that stops both listeners
75 47 : return () => {
76 47 : stopKeydown()
77 47 : stopKeyup()
78 : }
79 : }
80 :
81 : // Cleanup on component unmount
82 9725 : tryOnScopeDispose(() => {
83 6162 : shiftKeyState.value = false
84 6162 : canvasEl = null
85 : })
86 :
87 9725 : return { trackShiftKey }
88 : }
|