Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/editors/slate/element-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
6
import { Element } from "slate";
7
import { Info, serialize } from "./slate-to-markdown";
8
import { getChildInfoHook, getSlateToMarkdown } from "./elements";
9
import stringify from "json-stable-stringify";
10
11
export interface ChildInfo extends Info {
12
// Child info is like info, but we all any other property -- see
13
// https://stackoverflow.com/questions/33836671/typescript-interface-that-allows-other-properties
14
// We want this since the getChildInfoHook conveys info to children
15
// by setting arbitrary fields of this Info object.
16
[field: string]: any;
17
}
18
19
export function serializeElement(node: Element, info: Info): string {
20
if (!Element.isElement(node)) {
21
// make typescript happier.
22
throw Error("BUG -- serializeElement takes an element as input");
23
}
24
25
if (
26
info.noCache === undefined ||
27
info.topLevel === undefined ||
28
!info.noCache.has(info.topLevel)
29
) {
30
const cachedMarkdown = info.cache?.[stringify(node)!];
31
if (cachedMarkdown != null) {
32
return cachedMarkdown;
33
}
34
}
35
36
const childInfo = {
37
...info,
38
...{ parent: node },
39
} as ChildInfo;
40
41
const childInfoHook = getChildInfoHook(node["type"]);
42
if (childInfoHook != null) {
43
childInfoHook({ node, childInfo });
44
}
45
const v: string[] = [];
46
for (let index = 0; index < node.children.length; index++) {
47
v.push(
48
serialize(node.children[index], {
49
...childInfo,
50
...{ index, lastChild: index == node.children.length - 1 },
51
})
52
);
53
}
54
55
let children = v.join("");
56
const slateToMarkdown = getSlateToMarkdown(node["type"]);
57
const md = slateToMarkdown({ node, children, info, childInfo });
58
const hook = info.hook?.(node);
59
if (hook !== undefined) {
60
return hook(md);
61
}
62
return md;
63
}
64
65