UNPKG

@uiw/react-textarea-code-editor

Version:
66 lines 2.09 kB
import { stopPropagation } from "./utils.js"; import { SelectionText } from "./SelectionText.js"; export default function shortcuts(e, indentWidth) { if (indentWidth === void 0) { indentWidth = 2; } var api = new SelectionText(e.target); /** * Support of shortcuts for React v16 * https://github.com/uiwjs/react-textarea-code-editor/issues/128 * https://blog.saeloun.com/2021/04/23/react-keyboard-event-code.html */ var code = (e.code || e.nativeEvent.code).toLocaleLowerCase(); var indent = ' '.repeat(indentWidth); if (code === 'tab') { stopPropagation(e); if (api.start === api.end) { if (e.shiftKey) { api.lineStarRemove(indent); } else { api.insertText(indent).position(api.start + indentWidth, api.end + indentWidth); } } else if (api.getSelectedValue().indexOf('\n') > -1 && e.shiftKey) { api.lineStarRemove(indent); } else if (api.getSelectedValue().indexOf('\n') > -1) { api.lineStarInstert(indent); } else { api.insertText(indent).position(api.start + indentWidth, api.end); } api.notifyChange(); } else if (code === 'enter') { stopPropagation(e); var _indent = "\n" + api.getIndentText(); api.insertText(_indent).position(api.start + _indent.length, api.start + _indent.length); api.notifyChange(); } else if (code && /^(quote|backquote|bracketleft|digit9|comma)$/.test(code) && api.getSelectedValue()) { stopPropagation(e); var val = api.getSelectedValue(); var txt = ''; switch (code) { case 'quote': txt = "'" + val + "'"; if (e.shiftKey) { txt = "\"" + val + "\""; } break; case 'backquote': txt = "`" + val + "`"; break; case 'bracketleft': txt = "[" + val + "]"; if (e.shiftKey) { txt = "{" + val + "}"; } break; case 'digit9': txt = "(" + val + ")"; break; case 'comma': txt = "<" + val + ">"; break; } api.insertText(txt); api.notifyChange(); } }