Files
cinny/src/client/event/hotkeys.js
T

87 lines
2.3 KiB
JavaScript
Raw Normal View History

import { openSearch, toggleRoomSettings } from '../action/navigation';
2021-12-11 10:50:34 +05:30
import navigation from '../state/navigation';
2022-03-18 09:09:14 +05:30
import { markAsRead } from '../action/notifications';
2021-12-11 10:50:34 +05:30
2022-05-12 04:28:19 -07:00
function shouldFocusMessageField(code) {
// do not focus on F keys
2022-05-13 15:38:18 +05:30
if (/^F\d+$/.test(code)) return false;
2022-05-12 04:28:19 -07:00
// do not focus on numlock/scroll lock
2022-05-13 15:38:18 +05:30
if (
code.metaKey
|| code.startsWith('OS')
|| code.startsWith('Meta')
|| code.startsWith('Shift')
|| code.startsWith('Alt')
|| code.startsWith('Control')
|| code.startsWith('Arrow')
|| code === 'Tab'
|| code === 'Space'
|| code === 'Enter'
|| code === 'NumLock'
|| code === 'ScrollLock'
) {
2022-05-12 04:28:19 -07:00
return false;
}
return true;
}
2021-12-11 10:50:34 +05:30
function listenKeyboard(event) {
2022-03-11 14:14:57 +05:30
// Ctrl/Cmd +
if (event.ctrlKey || event.metaKey) {
2022-05-12 04:28:19 -07:00
// open search modal
if (event.code === 'KeyK') {
2021-12-11 10:50:34 +05:30
event.preventDefault();
2022-05-14 08:24:21 +05:30
if (navigation.isRawModalVisible) return;
2021-12-11 10:50:34 +05:30
openSearch();
}
2022-05-12 04:28:19 -07:00
// focus message field on paste
if (event.code === 'KeyV') {
2022-05-14 08:24:21 +05:30
if (navigation.isRawModalVisible) return;
2022-05-12 04:28:19 -07:00
const msgTextarea = document.getElementById('message-textarea');
2022-05-14 20:05:43 +05:30
const { activeElement } = document;
if (activeElement !== msgTextarea
&& ['input', 'textarea'].includes(activeElement.tagName.toLowerCase())
) return;
2022-05-12 04:28:19 -07:00
msgTextarea?.focus();
}
2021-12-11 10:50:34 +05:30
}
2021-12-22 20:18:32 +05:30
2022-05-12 04:28:19 -07:00
if (!event.ctrlKey && !event.altKey && !event.metaKey) {
if (navigation.isRawModalVisible) return;
2022-05-14 20:05:43 +05:30
if (['input', 'textarea'].includes(document.activeElement.tagName.toLowerCase())) {
return;
}
2022-05-12 04:28:19 -07:00
if (event.code === 'Escape') {
2022-03-18 09:09:14 +05:30
if (navigation.isRoomSettings) {
toggleRoomSettings();
return;
}
if (navigation.selectedRoomId) {
markAsRead(navigation.selectedRoomId);
return;
}
}
2022-05-12 04:28:19 -07:00
// focus the text field on most keypresses
if (shouldFocusMessageField(event.code)) {
// press any key to focus and type in message field
const msgTextarea = document.getElementById('message-textarea');
msgTextarea?.focus();
}
}
2021-12-11 10:50:34 +05:30
}
function initHotkeys() {
document.body.addEventListener('keydown', listenKeyboard);
}
function removeHotkeys() {
document.body.removeEventListener('keydown', listenKeyboard);
}
export { initHotkeys, removeHotkeys };