dc09.ru/remark-post-meta.mjs

29 lines
854 B
JavaScript

// Adds metadata to a Markdown page:
// description -- text extracted from the first paragraph
// readingTime -- reading time of the whole text, in float (not integer)
import { select } from 'unist-util-select'
import { visit } from 'unist-util-visit'
import getReadingTime from 'reading-time'
export default function remarkPostMeta() {
return (tree, { data }) => {
const firstPara = select(':not(heading) paragraph:first-of-type', tree)
const firstParaText = mdToString(firstPara)
const articleText = mdToString(tree)
const readingTime = getReadingTime(articleText)
data.astro.frontmatter.readingTime = readingTime.minutes
data.astro.frontmatter.description = firstParaText
}
}
function mdToString(tree) {
let str = ''
visit(tree, 'text', node => {
str += node.value
str += ' '
})
return str.trimEnd()
}