Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/markdown-to-slate/handle-no-children.ts
1698 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { Text } from "slate";
7
import { getMarkdownToSlate } from "../elements/register";
8
import { replace_all } from "@cocalc/util/misc";
9
import { Marks } from "./types";
10
import { register } from "./register";
11
import { DEFAULT_CHILDREN } from "../util";
12
import getSource from "./source";
13
import { setCache } from "./cache";
14
15
export function handleNoChildren({ token, state, cache }) {
16
if (token.children != null && token.children.length > 0) {
17
throw Error(
18
`handleNoChildren -- the token must not have children ${JSON.stringify(
19
token
20
)}`
21
);
22
}
23
24
// Handle inline code as a leaf node with style
25
if (token.type == "code_inline") {
26
if (token.content == "") {
27
// Empty text nodes get deleted by the normalization process
28
// unless they are the first/last children next to inline nodes,
29
// and our code adds those back in all cases anyways.
30
return [];
31
}
32
return [mark({ text: token.content, code: true }, state.marks)];
33
}
34
35
if (token.type == "text" || token.type == "inline") {
36
if (token.content == "") return [];
37
// text
38
return [mark({ text: token.content }, state.marks)];
39
} else {
40
// everything else -- via our element plugin mechanism.
41
const markdownToSlate = getMarkdownToSlate(token.type);
42
const node = markdownToSlate({
43
type: token.type,
44
token,
45
children: DEFAULT_CHILDREN,
46
state,
47
isEmpty: false,
48
});
49
if (node != null) {
50
if (cache != null && token.level === 0 && token.map != null) {
51
setCache({
52
cache,
53
node,
54
markdown: getSource({
55
start: token.map[0],
56
end: token.map[1],
57
lines: state.lines,
58
}),
59
});
60
}
61
return [node];
62
} else {
63
// node == undefied/null means that we want no node
64
// at all; markdown-it sometimes uses tokens to
65
// convey state but nothing that should be included
66
// in the slate doc tree.
67
return [];
68
}
69
}
70
}
71
72
register(handleNoChildren);
73
74
function mark(text: Text, marks: Marks): Text {
75
if (!text.text) {
76
// don't mark empty string
77
return text;
78
}
79
80
// unescape dollar signs (in markdown we have to escape them so they aren't interpreted as math).
81
text.text = replace_all(text.text, "\\$", "$");
82
83
for (const mark in marks) {
84
if (marks[mark]) {
85
text[mark] = true;
86
}
87
}
88
return text;
89
}
90
91