Path: blob/master/src/packages/frontend/editors/slate/keyboard/shift-enter.ts
1697 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// What happens when you hit shift+enter key.67import { Editor, Node, Transforms } from "slate";8import { isElementOfType } from "../elements";9import { register } from "./register";10import { hardbreak } from "../elements/break";11import { isWhitespaceParagraph, isWhitespaceText } from "../padding";1213register({ key: "Enter", shift: true }, ({ editor, extra }) => {14// Configured editor so shift+enter does some action, e.g., "submit chat".15// In this case, we do that instead of the various things below involving16// newlines, which can instead be done with control+enter.17const shiftEnter = extra?.actions?.shiftEnter;18if (shiftEnter != null) {19shiftEnter(editor.getMarkdownValue());20return true;21}22return softBreak({ editor });23});2425function softBreak({ editor }) {26// In a table, the only option is to insert a <br/>.27const fragment = editor.getFragment();28if (isElementOfType(fragment?.[0], "table")) {29const br = {30isInline: true,31isVoid: true,32type: "html_inline",33html: "<br />",34children: [{ text: " " }],35} as Node;36Transforms.insertNodes(editor, [br]);37// Also, move cursor forward so it is *after* the br.38Transforms.move(editor, { distance: 1 });39return true;40}4142// Not in a table, so possibly insert a hard break instead of a new43// paragraph...44const prev = Editor.previous(editor);45if (prev == null) return false;46if (isWhitespaceParagraph(prev[0])) {47// do nothing.48return true;49}50if (isElementOfType(prev[0], "hardbreak")) {51// do nothing52return true;53}54if (isWhitespaceText(prev[0])) {55const prev2 = Editor.previous(editor, { at: prev[1] });56if (prev2 != null && isElementOfType(prev2[0], "hardbreak")) {57// do nothing58return true;59}60}61Transforms.insertNodes(editor, [hardbreak()]);62Transforms.move(editor, { distance: 1 });63return true;64}6566register({ key: "Enter", ctrl: true }, softBreak);676869