Path: blob/master/src/packages/frontend/editors/slate/keyboard/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 the enter key.67import { Editor, Element, Transforms } from "slate";8import { isElementOfType } from "../elements";9import { emptyParagraph, isWhitespaceParagraph } from "../padding";10import { register } from "./register";11import {12isAtBeginningOfBlock,13isAtEndOfBlock,14moveCursorToBeginningOfBlock,15} from "../control";16import { containingBlock } from "../slate-util";17import { markdownAutoformat } from "../format/auto-format";1819register({ key: "Enter" }, ({ editor }) => {20markdownAutoformat(editor);21const fragment = editor.getFragment();22const x = fragment?.[0];2324if (isElementOfType(x, "heading")) {25// If you hit enter in a heading,26Transforms.insertNodes(editor, [emptyParagraph()], {27match: (node) => isElementOfType(node, "heading"),28});29return true;30}3132if (isElementOfType(x, "paragraph")) {33// If you hit enter in a paragraph, the default behavior is creating34// another empty paragraph. We do a bunch of special cases so that35// our document corresponds much more closely to what markdown36// actually supports.3738if (isWhitespaceParagraph(containingBlock(editor)?.[0])) {39return true;40}41const prev = Editor.previous(editor);42if (prev == null) return false;43if (isWhitespaceParagraph(prev[0])) {44return true;45}46return false;47}4849if (isElementOfType(x, ["bullet_list", "ordered_list"])) {50const atEnd = isAtEndOfBlock(editor, { mode: "lowest" });51const atBeginning = isAtBeginningOfBlock(editor, { mode: "lowest" });52Transforms.insertNodes(53editor,54[{ type: "list_item", children: [{ text: "" }] } as Element],55{56match: (node) => isElementOfType(node, "list_item"),57mode: "lowest",58}59);60if (atBeginning) {61// done62Transforms.move(editor, { distance: 1, unit: "line" });63return true;64}65if (atEnd) {66// done67return true;68}69// Not at beginning or end, so above insertNodes actually70// splits the list item so we end up71// with an extra blank one, which we now remove.72Transforms.removeNodes(editor, {73match: (node) => isElementOfType(node, "list_item"),74});75moveCursorToBeginningOfBlock(editor);76return true;77}78return false;79});808182