aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files/src/store/keyboard.ts
blob: 6bd40a6dfa73f04d7946a44bc11700d15aafd632 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * @copyright Copyright (c) 2023 John Molakvoæ <skjnldsv@protonmail.com>
 *
 * @author John Molakvoæ <skjnldsv@protonmail.com>
 *
 * @license AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */
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.
 */
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
}