Path: blob/master/src/packages/frontend/editors/slate/markdown-to-slate/handle-no-children.ts
1698 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import { Text } from "slate";6import { getMarkdownToSlate } from "../elements/register";7import { replace_all } from "@cocalc/util/misc";8import { Marks } from "./types";9import { register } from "./register";10import { DEFAULT_CHILDREN } from "../util";11import getSource from "./source";12import { setCache } from "./cache";1314export function handleNoChildren({ token, state, cache }) {15if (token.children != null && token.children.length > 0) {16throw Error(17`handleNoChildren -- the token must not have children ${JSON.stringify(18token19)}`20);21}2223// Handle inline code as a leaf node with style24if (token.type == "code_inline") {25if (token.content == "") {26// Empty text nodes get deleted by the normalization process27// unless they are the first/last children next to inline nodes,28// and our code adds those back in all cases anyways.29return [];30}31return [mark({ text: token.content, code: true }, state.marks)];32}3334if (token.type == "text" || token.type == "inline") {35if (token.content == "") return [];36// text37return [mark({ text: token.content }, state.marks)];38} else {39// everything else -- via our element plugin mechanism.40const markdownToSlate = getMarkdownToSlate(token.type);41const node = markdownToSlate({42type: token.type,43token,44children: DEFAULT_CHILDREN,45state,46isEmpty: false,47});48if (node != null) {49if (cache != null && token.level === 0 && token.map != null) {50setCache({51cache,52node,53markdown: getSource({54start: token.map[0],55end: token.map[1],56lines: state.lines,57}),58});59}60return [node];61} else {62// node == undefied/null means that we want no node63// at all; markdown-it sometimes uses tokens to64// convey state but nothing that should be included65// in the slate doc tree.66return [];67}68}69}7071register(handleNoChildren);7273function mark(text: Text, marks: Marks): Text {74if (!text.text) {75// don't mark empty string76return text;77}7879// unescape dollar signs (in markdown we have to escape them so they aren't interpreted as math).80text.text = replace_all(text.text, "\\$", "$");8182for (const mark in marks) {83if (marks[mark]) {84text[mark] = true;85}86}87return text;88}899091