xinny/src/app/components/editor/keyboard.ts
Ajay Bura 2883b4c35b
Fix editor bugs (#1281)
* focus editor on reply click

* fix emoji and sticker img object-fit

* fix cursor not moving with autocomplete

* stop sanitizing sending plain text body

* improve autocomplete query parsing

* add escape to turn off active editor toolbar item
2023-06-13 23:17:18 +05:30

64 lines
1.9 KiB
TypeScript

import { isHotkey } from 'is-hotkey';
import { KeyboardEvent } from 'react';
import { Editor } from 'slate';
import { isAnyMarkActive, isBlockActive, removeAllMark, toggleBlock, toggleMark } from './common';
import { BlockType, MarkType } from './Elements';
export const INLINE_HOTKEYS: Record<string, MarkType> = {
'mod+b': MarkType.Bold,
'mod+i': MarkType.Italic,
'mod+u': MarkType.Underline,
'mod+shift+u': MarkType.StrikeThrough,
'mod+[': MarkType.Code,
'mod+h': MarkType.Spoiler,
};
const INLINE_KEYS = Object.keys(INLINE_HOTKEYS);
export const BLOCK_HOTKEYS: Record<string, BlockType> = {
'mod+shift+0': BlockType.OrderedList,
'mod+shift+8': BlockType.UnorderedList,
"mod+shift+'": BlockType.BlockQuote,
'mod+shift+;': BlockType.CodeBlock,
};
const BLOCK_KEYS = Object.keys(BLOCK_HOTKEYS);
/**
* @return boolean true if shortcut is toggled.
*/
export const toggleKeyboardShortcut = (editor: Editor, event: KeyboardEvent<Element>): boolean => {
if (isHotkey('escape', event)) {
if (isAnyMarkActive(editor)) {
removeAllMark(editor);
return true;
}
console.log(isBlockActive(editor, BlockType.Paragraph));
if (!isBlockActive(editor, BlockType.Paragraph)) {
toggleBlock(editor, BlockType.Paragraph);
return true;
}
return false;
}
const blockToggled = BLOCK_KEYS.find((hotkey) => {
if (isHotkey(hotkey, event)) {
event.preventDefault();
toggleBlock(editor, BLOCK_HOTKEYS[hotkey]);
return true;
}
return false;
});
if (blockToggled) return true;
const inlineToggled = isBlockActive(editor, BlockType.CodeBlock)
? false
: INLINE_KEYS.find((hotkey) => {
if (isHotkey(hotkey, event)) {
event.preventDefault();
toggleMark(editor, INLINE_HOTKEYS[hotkey]);
return true;
}
return false;
});
return !!inlineToggled;
};