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

93 lines
2.2 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
// describes which keys should auto-focus the message field
function shouldFocusMessageField(code) {
// should focus on alphanumeric values, and backspace
if (code.startsWith('Key')) {
return true;
}
if (code.startsWith('Digit')) {
return true;
}
if (code === 'Backspace') {
return true;
}
// do not focus if super key is pressed
if (code.startsWith('Meta')) { // chrome
return false;
}
if (code.startsWith('OS')) { // firefox
return false;
}
// do not focus on F keys
if (/^F\d+$/.test(code)) {
return false;
}
// do not focus on numlock/scroll lock
if (code === 'NumLock' || code === 'ScrollLock') {
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-12 04:28:19 -07:00
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') {
const msgTextarea = document.getElementById('message-textarea');
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;
2021-12-13 21:05:37 +05:30
if (['text', 'textarea'].includes(document.activeElement.type)) {
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 };