aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files/src/store/keyboard.ts
blob: f2654933895f8410b3ed1f9b4ac21e1510ada5c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
import { defineStore } from 'pinia'
import Vue from 'vue'

/**
 * Observe various events and save the current
 * special keys states. Useful for checking the
 * current status of a key when executing a method.
 * @param {...any} args
 */
export const useKeyboardStore = function(...args) {
	const store = defineStore('keyboard', {
		state: () => ({
			altKey: false,
			ctrlKey: false,
			metaKey: false,
			shiftKey: false,
		}),

		actions: {
			onEvent(event: MouseEvent | KeyboardEvent) {
				if (!event) {
					event = window.event as MouseEvent | KeyboardEvent
				}
				Vue.set(this, 'altKey', !!event.altKey)
				Vue.set(this, 'ctrlKey', !!event.ctrlKey)
				Vue.set(this, 'metaKey', !!event.metaKey)
				Vue.set(this, 'shiftKey', !!event.shiftKey)
			},
		},
	})

	const keyboardStore = store(...args)
	// Make sure we only register the listeners once
	if (!keyboardStore._initialized) {
		window.addEventListener('keydown', keyboardStore.onEvent)
		window.addEventListener('keyup', keyboardStore.onEvent)
		window.addEventListener('mousemove', keyboardStore.onEvent)

		keyboardStore._initialized = true
	}

	return keyboardStore
}