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