Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/keyboard/register.ts
6011 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
// Plugin system for keyboarding handlers.
7
8
export { IS_MACOS } from "@cocalc/frontend/feature";
9
10
import { SlateEditor } from "../editable-markdown";
11
import { Actions } from "../types";
12
import { SearchHook } from "../search";
13
14
interface Key {
15
key: string;
16
shift?: boolean;
17
ctrl?: boolean;
18
meta?: boolean;
19
alt?: boolean;
20
}
21
22
function EventToString(e): string {
23
// e is a keyboard event
24
return `${e.shiftKey}${e.ctrlKey}${e.metaKey}${e.altKey}${e.key}`;
25
}
26
27
function KeyToString(k: Key): string {
28
return `${!!k.shift}${!!k.ctrl}${!!k.meta}${!!k.alt}${k.key}`;
29
}
30
31
// Function that returns true if it handles the key
32
// or false-ish to fallback to default behavior.
33
export type KeyHandler = (opts: {
34
editor: SlateEditor;
35
extra: { actions: Actions; id: string; search: SearchHook };
36
}) => boolean;
37
38
const keyHandlers: { [x: string]: KeyHandler } = {};
39
40
export function register(
41
key: Partial<Key> | Partial<Key>[],
42
handler: KeyHandler,
43
): void {
44
const handlerNoThrow = (opts) => {
45
try {
46
return handler(opts);
47
} catch (err) {
48
// making this a warning -- there's a number of situations where the
49
// it's best to just not do anything special, rather than crash cocalc.
50
console.log("slate key handler throw ", key, err);
51
return false;
52
}
53
};
54
55
if (key[0] != null) {
56
for (const k of key as Partial<Key>[]) {
57
register(k, handlerNoThrow);
58
}
59
return;
60
}
61
62
const s = KeyToString(key as Key);
63
if (keyHandlers[s] != null) {
64
// making this a warning to support hot module reloading.
65
console.warn(`WARNING: there is already a handler registered for ${s}`);
66
}
67
keyHandlers[s] = handlerNoThrow;
68
}
69
70
export function getHandler(event): KeyHandler | undefined {
71
// console.log(event.key);
72
return keyHandlers[EventToString(event)];
73
}
74
75