stacker.news/lib/md.js

82 lines
2.0 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
}
})
}
}
2024-06-25 22:18:21 +00:00
export function rehypeStyler (startTag, endTag, className) {
return function (tree) {
visit(tree, 'element', (node) => {
for (let i = 0; i < node.children.length; i += 1) {
const start = node.children[i]
const text = node.children[i + 1]
const end = node.children[i + 2]
// is this a children slice wrapped with the tags we're looking for?
const isWrapped =
start?.type === 'raw' && start?.value === startTag &&
text?.type === 'text' &&
end?.type === 'raw' && end?.value === endTag
if (!isWrapped) continue
const newChildren = {
type: 'element',
tagName: 'span',
properties: { className: [className] },
children: [{ type: 'text', value: text.value }]
}
node.children.splice(i, 3, newChildren)
}
})
}
}
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'