stacker.news/lib/md.js

55 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-08-10 15:06:31 +00:00
import { gfmFromMarkdown } from 'mdast-util-gfm'
import { visit } from 'unist-util-visit'
2023-07-25 18:59:07 +00:00
import { gfm } from 'micromark-extension-gfm'
import { fromMarkdown } from 'mdast-util-from-markdown'
2022-08-10 15:06:31 +00:00
export function mdHas (md, test) {
2023-07-25 18:32:48 +00:00
if (!md) return []
2022-08-10 15:06:31 +00:00
const tree = fromMarkdown(md, {
2023-07-25 18:59:07 +00:00
extensions: [gfm()],
2022-08-10 15:06:31 +00:00
mdastExtensions: [gfmFromMarkdown()]
})
let found = false
visit(tree, test, () => {
found = true
return false
})
return found
}
2023-10-23 22:14:37 +00:00
export function rehypeInlineCodeProperty () {
return function (tree) {
visit(tree, { tagName: 'code' }, function (node, index, parent) {
if (parent && parent.tagName === 'pre') {
node.properties.inline = false
} else {
node.properties.inline = true
}
})
}
}
export function extractUrls (md) {
if (!md) return []
const tree = fromMarkdown(md, {
2023-07-25 18:59:07 +00:00
extensions: [gfm()],
mdastExtensions: [gfmFromMarkdown()]
})
const urls = new Set()
visit(tree, ({ type }) => {
2023-07-13 20:18:04 +00:00
return type === 'link' || type === 'image'
}, ({ url }) => {
urls.add(url)
})
return Array.from(urls)
}
export const quote = (orig) =>
orig.split('\n')
.map(line => `> ${line}`)
.join('\n') + '\n'