recognize nostr entities

This commit is contained in:
k00b 2024-09-28 18:56:37 -05:00
parent f7010ee3f7
commit 80a7c24e54
1 changed files with 38 additions and 3 deletions

View File

@ -8,6 +8,7 @@ const subGroup = '[A-Za-z][\\w_]+'
const mentionRegex = new RegExp('@(' + userGroup + '(?:\\/' + userGroup + ')?)', 'gi')
const subRegex = new RegExp('~(' + subGroup + '(?:\\/' + subGroup + ')?)', 'gi')
const nostrIdRegex = /\b((npub1|nevent1|nprofile1|note1|naddr1)[02-9ac-hj-np-z]+)\b/g
export default function rehypeSN (options = {}) {
const { stylers = [] } = options
@ -120,12 +121,37 @@ export default function rehypeSN (options = {}) {
lastIndex = combinedRegex.lastIndex
}
if (lastIndex < text.length) {
newChildren.push({ type: 'text', value: text.slice(lastIndex) })
if (newChildren.length > 0) {
if (lastIndex < text.length) {
newChildren.push({ type: 'text', value: text.slice(lastIndex) })
}
parent.children.splice(index, childrenConsumed, ...newChildren)
return index + newChildren.length
}
}
// Handle Nostr IDs
if (node.type === 'text') {
const newChildren = []
let lastIndex = 0
let match
while ((match = nostrIdRegex.exec(node.value)) !== null) {
if (lastIndex < match.index) {
newChildren.push({ type: 'text', value: node.value.slice(lastIndex, match.index) })
}
newChildren.push(replaceNostrId(match[0], match[0]))
lastIndex = nostrIdRegex.lastIndex
}
if (lastIndex < node.value.length) {
newChildren.push({ type: 'text', value: node.value.slice(lastIndex) })
}
if (newChildren.length > 0) {
parent.children.splice(index, childrenConsumed, ...newChildren)
parent.children.splice(index, 1, ...newChildren)
return index + newChildren.length
}
}
@ -238,4 +264,13 @@ export default function rehypeSN (options = {}) {
return misleading
}
function replaceNostrId (value, id) {
return {
type: 'element',
tagName: 'a',
properties: { href: `https://njump.me/${id}` },
children: [{ type: 'text', value }]
}
}
}