Path: blob/master/src/packages/frontend/editors/slate/patches.ts
1691 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { Editor, Node } from "slate";67// The version of isNodeList in slate is **insanely** slow, and this hack8// is likely to be sufficient for our use.9// This makes a MASSIVE different for larger documents!10Node.isNodeList = (value: any): value is Node[] => {11return Array.isArray(value) && (value?.length == 0 || Node.isNode(value[0]));12};1314// I have seen cocalc.com crash in production randomly when editing markdown15// when calling range. I think this happens when computing decorators, so16// it is way better to make it non-fatal for now.17export const withNonfatalRange = (editor) => {18const { range } = editor;1920editor.range = (editor, at, to?) => {21try {22return range(editor, at, to);23} catch (err) {24console.log(`WARNING: range error ${err}`);25const anchor = Editor.first(editor, []);26return { anchor, focus: anchor };27}28};2930return editor;31};3233// We patch the Editor.string command so that if the input34// location is invalid, it returns "" instead of crashing.35// This is useful, since Editor.string is mainly used36// for heuristic selection adjustment, copy, etc.37// In theory it should never get invalid input, but due to38// the loose nature of Slate, it's difficult to ensure this.39const unpatchedEditorString = Editor.string;40Editor.string = function (...args): string {41try {42return unpatchedEditorString(...args);43} catch (err) {44console.warn("WARNING: slate Editor.string -- invalid range", err);45return "";46}47};484950