stacker.news/lib/remark-sub.js

39 lines
770 B
JavaScript
Raw Normal View History

2023-07-25 01:03:56 +00:00
import { findAndReplace } from 'mdast-util-find-and-replace'
2022-03-03 22:18:38 +00:00
const subGroup = '[A-Za-z][\\w_]+'
2022-03-03 22:18:38 +00:00
const subRegex = new RegExp(
'~(' + subGroup + '(?:\\/' + subGroup + ')?)',
'gi'
)
export default function mention (options) {
return function transformer (tree) {
findAndReplace(
tree,
[
[subRegex, replaceSub]
],
{ ignore: ['link', 'linkReference'] }
)
}
function replaceSub (value, sub, match) {
if (
/[\w`]/.test(match.input.charAt(match.index - 1)) ||
/[/\w`]/.test(match.input.charAt(match.index + value.length))
) {
return false
}
2023-07-25 01:03:56 +00:00
const node = { type: 'text', value }
2022-03-03 22:18:38 +00:00
return {
type: 'link',
title: null,
url: '/~' + sub,
children: [node]
}
}
}