Hey is a decentralized and permissionless social media app built with Lens Protocol 馃尶
at main 38 lines 1.3 kB view raw
1import rehypeParse from "rehype-parse"; 2import rehypeRemark from "rehype-remark"; 3import remarkHtml from "remark-html"; 4import remarkParse from "remark-parse"; 5import remarkStringify from "remark-stringify"; 6import { unified } from "unified"; 7import { rehypeJoinParagraph } from "./rehypeJoinParagraph"; 8import { customBreakHandler } from "./remarkBreakHandler"; 9import { remarkLinkProtocol } from "./remarkLinkProtocol"; 10 11// By default, remark-stringify escapes underscores (i.e. "_" => "\_"). We want 12// to disable this behavior so that we can have underscores in mention usernames. 13const unescapeUnderscore = (str: string) => { 14 return str.replace(/(^|[^\\])\\_/g, "$1_"); 15}; 16 17export const markdownFromHTML = (html: string): string => { 18 const markdown = unified() 19 .use(rehypeParse) 20 .use(rehypeJoinParagraph) 21 .use(rehypeRemark, { newlines: true }) 22 .use(remarkLinkProtocol) 23 .use(remarkStringify, { 24 handlers: { break: customBreakHandler, hardBreak: customBreakHandler } 25 }) 26 .processSync(html) 27 .toString(); 28 29 return unescapeUnderscore(markdown); 30}; 31 32export const htmlFromMarkdown = (markdown: string): string => { 33 return unified() 34 .use(remarkParse) 35 .use(remarkHtml) 36 .processSync(markdown) 37 .toString(); 38};