remark plugin for sub mentions

This commit is contained in:
keyan 2022-03-03 16:18:38 -06:00
parent 2afd1c437b
commit 2ad2ff6ff5
2 changed files with 40 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
/* Use `…/dist/cjs/…` if youre not in ESM! */
import { atomDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import mention from '../lib/remark-mention'
import sub from '../lib/remark-sub'
import remarkDirective from 'remark-directive'
import { visit } from 'unist-util-visit'
import reactStringReplace from 'react-string-replace'
@ -80,7 +81,7 @@ export default function Text ({ nofollow, children }) {
)
}
}}
remarkPlugins={[gfm, mention, remarkDirective, myRemarkPlugin]}
remarkPlugins={[gfm, mention, sub, remarkDirective, myRemarkPlugin]}
>
{children}
</ReactMarkdown>

38
lib/remark-sub.js Normal file
View File

@ -0,0 +1,38 @@
import findAndReplace from 'mdast-util-find-and-replace'
const subGroup = '[\\w_]+'
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
}
const node = { type: 'text', value: value }
return {
type: 'link',
title: null,
url: '/~' + sub,
children: [node]
}
}
}