Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/slate-to-markdown.ts
1691 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
import { Node, Element, Text } from "slate";
6
import { serializeLeaf } from "./leaf-to-markdown";
7
import { serializeElement } from "./element-to-markdown";
8
import type { References } from "./elements/references";
9
10
export interface Info {
11
parent?: Node; // the parent of the node being serialized (if there is a parent)
12
index?: number; // index of this node among its siblings
13
no_escape: boolean; // if true, do not escape text in this node.
14
hook?: (Node) => undefined | ((string) => string);
15
lastChild: boolean; // true if this is the last child among its siblings.
16
cache?;
17
noCache?: Set<number>; // never use cache for these top-level nodes
18
topLevel?: number; // top-level block that contains this node.
19
references?: References;
20
}
21
22
export function serialize(node: Node, info: Info): string {
23
if (Text.isText(node)) {
24
return serializeLeaf(node, info);
25
} else if (Element.isElement(node)) {
26
return serializeElement(node, info);
27
} else {
28
throw Error(
29
`bug: node must be Text or Element -- ${JSON.stringify(node)}`
30
);
31
}
32
}
33
34
export function slate_to_markdown(
35
slate: Node[],
36
options?: {
37
no_escape?: boolean;
38
hook?: (Node) => undefined | ((string) => string);
39
cache?;
40
noCache?: Set<number>;
41
}
42
): string {
43
// const t = Date.now();
44
45
let markdown = "";
46
let references: References | undefined = undefined;
47
for (let i = slate.length - 1; i >= 0; i--) {
48
if (slate[i]?.["type"] == "references") {
49
references = slate[i]?.["value"];
50
break;
51
}
52
}
53
for (let i = 0; i < slate.length; i++) {
54
markdown += serialize(slate[i], {
55
no_escape: !!options?.no_escape,
56
hook: options?.hook,
57
index: i,
58
topLevel: i,
59
lastChild: i == slate.length - 1,
60
cache: options?.cache,
61
noCache: options?.noCache,
62
references,
63
});
64
}
65
66
//console.log("time: slate_to_markdown ", Date.now() - t, "ms");
67
//console.log("slate_to_markdown", { slate, markdown });
68
return markdown;
69
}
70
71