Files
zhdiary/packages/nuxt/scripts/make-html.ts
T
2020-12-15 16:27:52 +07:00

68 lines
1.5 KiB
TypeScript

import crypto from 'crypto'
import scopeCss from '@patarapolw/scope-css'
import cheerio from 'cheerio'
import showdown from 'showdown'
export class MakeHTML {
$ = cheerio.load('');
mdConverter = new showdown.Converter({
noHeaderId: true,
parseImgDimensions: true,
simplifiedAutoLink: true,
// literalMidWordUnderscores: true,
strikethrough: true,
tables: true,
tasklists: true,
simpleLineBreaks: true,
openLinksInNewWindow: true,
backslashEscapesHTMLTags: true,
emoji: true,
underline: true,
metadata: true
});
constructor (private slug: string) {
/**
* ! For some reasons default underscore italic fails to render...
*/
this.mdConverter.addExtension(
{
type: 'lang',
regex: /([^\\])_{1}(.*?[^\\])_{1}/g,
replace: '$1<i>$2</i>'
},
'underscore-italic'
)
}
parse (md: string): string {
const id =
'md-' +
crypto
.createHash('sha256')
.update(this.slug || md)
.digest()
.toString('hex')
.substr(8)
const $div = this.$(`<div id="${id}">`)
$div.html(this.mdConverter.makeHtml(md))
$div.find('style').each((_, el) => {
const $el = this.$(el)
$el.html(scopeCss($el.html(), `#${id}`))
})
return this.$('<div>').append($div).html()
}
clean (md: string): string {
const $div = this.$('<div>')
$div.html(this.mdConverter.makeHtml(md))
$div.remove('style')
return $div.html()
}
}