Files
cinny/src/app/components/editor/keyboard.ts
T

64 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-12 21:15:23 +10:00
import { isHotkey } from 'is-hotkey';
import { KeyboardEvent } from 'react';
import { Editor } from 'slate';
2023-10-18 13:15:30 +11:00
import { isAnyMarkActive, isBlockActive, removeAllMark, toggleBlock, toggleMark } from './utils';
import { BlockType, MarkType } from './types';
2023-06-12 21:15:23 +10:00
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+7': BlockType.OrderedList,
2023-06-12 21:15:23 +10:00
'mod+shift+8': BlockType.UnorderedList,
"mod+shift+'": BlockType.BlockQuote,
'mod+shift+;': BlockType.CodeBlock,
};
const BLOCK_KEYS = Object.keys(BLOCK_HOTKEYS);
2023-06-14 03:47:18 +10:00
/**
* @return boolean true if shortcut is toggled.
*/
export const toggleKeyboardShortcut = (editor: Editor, event: KeyboardEvent<Element>): boolean => {
if (isHotkey('mod+e', event)) {
2023-06-14 03:47:18 +10:00
if (isAnyMarkActive(editor)) {
removeAllMark(editor);
return true;
}
2023-06-14 03:47:18 +10:00
if (!isBlockActive(editor, BlockType.Paragraph)) {
toggleBlock(editor, BlockType.Paragraph);
return true;
}
return false;
}
const blockToggled = BLOCK_KEYS.find((hotkey) => {
2023-06-12 21:15:23 +10:00
if (isHotkey(hotkey, event)) {
event.preventDefault();
toggleBlock(editor, BLOCK_HOTKEYS[hotkey]);
2023-06-14 03:47:18 +10:00
return true;
2023-06-12 21:15:23 +10:00
}
2023-06-14 03:47:18 +10:00
return false;
2023-06-12 21:15:23 +10:00
});
2023-06-14 03:47:18 +10:00
if (blockToggled) return true;
2023-06-12 21:15:23 +10:00
2023-06-14 03:47:18 +10:00
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;
2023-06-12 21:15:23 +10:00
};