2021-02-11 12:02:53 +00:00
|
|
|
import * as h2m from 'h2m'
|
|
|
|
import { htmlDecode } from 'js-htmlencode'
|
|
|
|
|
2021-02-12 11:19:48 +00:00
|
|
|
export const trim = (html: string = ''): string => html
|
2021-02-11 12:19:26 +00:00
|
|
|
.replace(/ /g, ' ')
|
2021-02-11 12:02:53 +00:00
|
|
|
.split('>')
|
|
|
|
.map((token) => token.trim())
|
|
|
|
.join('>')
|
|
|
|
.split('</')
|
|
|
|
.map((token) => token.trim())
|
|
|
|
.join('</')
|
|
|
|
|
2021-02-11 13:30:42 +00:00
|
|
|
interface Node {
|
|
|
|
name: string
|
|
|
|
attrs: { [key: string]: string }
|
|
|
|
isInPreNode: boolean
|
|
|
|
md: string
|
|
|
|
}
|
|
|
|
const converter = 'MarkdownExtra'
|
|
|
|
const overides = {
|
|
|
|
a: (node: Node) => `[${node.md}](${node.attrs.href})`,
|
|
|
|
}
|
|
|
|
|
2021-02-11 12:02:53 +00:00
|
|
|
export const toMarkdown = (html: string): string => {
|
|
|
|
const trimmed = trim(html)
|
2021-02-11 13:30:42 +00:00
|
|
|
const markdown = h2m(trimmed, { overides, converter })
|
2021-02-11 12:02:53 +00:00
|
|
|
const decoded = htmlDecode(markdown)
|
|
|
|
return decoded
|
|
|
|
}
|