Path: blob/master/src/packages/frontend/editors/slate/keyboard/register.ts
6011 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// Plugin system for keyboarding handlers.67export { IS_MACOS } from "@cocalc/frontend/feature";89import { SlateEditor } from "../editable-markdown";10import { Actions } from "../types";11import { SearchHook } from "../search";1213interface Key {14key: string;15shift?: boolean;16ctrl?: boolean;17meta?: boolean;18alt?: boolean;19}2021function EventToString(e): string {22// e is a keyboard event23return `${e.shiftKey}${e.ctrlKey}${e.metaKey}${e.altKey}${e.key}`;24}2526function KeyToString(k: Key): string {27return `${!!k.shift}${!!k.ctrl}${!!k.meta}${!!k.alt}${k.key}`;28}2930// Function that returns true if it handles the key31// or false-ish to fallback to default behavior.32export type KeyHandler = (opts: {33editor: SlateEditor;34extra: { actions: Actions; id: string; search: SearchHook };35}) => boolean;3637const keyHandlers: { [x: string]: KeyHandler } = {};3839export function register(40key: Partial<Key> | Partial<Key>[],41handler: KeyHandler,42): void {43const handlerNoThrow = (opts) => {44try {45return handler(opts);46} catch (err) {47// making this a warning -- there's a number of situations where the48// it's best to just not do anything special, rather than crash cocalc.49console.log("slate key handler throw ", key, err);50return false;51}52};5354if (key[0] != null) {55for (const k of key as Partial<Key>[]) {56register(k, handlerNoThrow);57}58return;59}6061const s = KeyToString(key as Key);62if (keyHandlers[s] != null) {63// making this a warning to support hot module reloading.64console.warn(`WARNING: there is already a handler registered for ${s}`);65}66keyHandlers[s] = handlerNoThrow;67}6869export function getHandler(event): KeyHandler | undefined {70// console.log(event.key);71return keyHandlers[EventToString(event)];72}737475