Created
September 2, 2021 08:24
-
-
Save vnugent/0d48f51b8cdb07e6cede52b97fa363b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { unified } from "unified"; | |
import markdown from "remark-parse"; | |
import slate, { defaultNodeTypes, serialize } from "remark-slate"; | |
const DEFAULT_HEADINGS = { | |
1: "h1", | |
2: "h2", | |
3: "h3", | |
4: "h4", | |
5: "h5", | |
6: "h6", | |
}; | |
const DESERIALIZE_OPTS = { | |
nodeTypes: { | |
...defaultNodeTypes, | |
paragraph: "p", | |
heading: { ...DEFAULT_HEADINGS }, | |
link: "a", | |
}, | |
linkDestinationKey: 'url', | |
}; | |
const SERIALIZE_OPTS = { | |
nodeTypes: { | |
...defaultNodeTypes, | |
paragraph: "p", | |
link: "a", | |
heading: { ...DEFAULT_HEADINGS }, | |
}, | |
}; | |
export const md_to_slate = (md_str) => { | |
if (!md_str) { | |
return null | |
} | |
const processor = unified().use(markdown).use(slate, DESERIALIZE_OPTS); | |
return processor.processSync(md_str).result; | |
}; | |
export const slate_to_md = (ast) => { | |
return ast ? ast.map((v) => serialize(v, SERIALIZE_OPTS)).join("") : ""; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment