Path: blob/master/src/packages/frontend/editors/slate/format/delete-backward.ts
1698 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { Range, Editor, Element, Path, Point, Text, Transforms } from "slate";67export const withDeleteBackward = (editor) => {8const { deleteBackward } = editor;910editor.deleteBackward = (...args) => {11if (!customDeleteBackwards(editor)) {12// no custom handling, so just do the default:13deleteBackward(...args);14}15};1617return editor;18};1920function customDeleteBackwards(editor: Editor): boolean | undefined {21// Figure out first if we should so something special:22const { selection } = editor;23if (selection == null || !Range.isCollapsed(selection)) return;2425const above = Editor.above(editor, {26match: (node) => Element.isElement(node) && Editor.isBlock(editor, node) && node.type != "paragraph",27});28if (above == null) return;29const [block, path] = above;30if (Editor.isEditor(block) || !Element.isElement(block)) {31return;32}33const start = Editor.start(editor, path);34if (!Point.equals(selection.anchor, start)) return;3536// This is where we actually might do something special, finally.37// Cursor is at the beginning of a non-paragraph block-level38// element, so maybe do something special.39switch (block.type) {40case "heading":41deleteBackwardsHeading(editor, block, path);42return true;43}44}4546// Special handling at beginning of heading.47function deleteBackwardsHeading(editor: Editor, block: Element, path: Path) {48if (Text.isText(block.children[0])) {49Transforms.setNodes(50editor,51{52type: "paragraph",53},54{ at: path }55);56} else {57Transforms.unwrapNodes(editor, {58match: (node) => Element.isElement(node),59split: true,60mode: "lowest",61at: path,62});63}64}656667