-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (52 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'use strict'
var visit = require('unist-util-visit')
var is = require('unist-util-is')
module.exports = altProt
// TODO: split out divergent regex patterns when the next exception comes along and make this a map
const protocols = ['hyper', 'dat', 'cabal', 'hypergraph', 'hypermerge']
var protocolsUsed = protocols
function altProt (options) {
var settings = options || {}
var exclusions = settings.exclusions
if (exclusions) {
exclusions.forEach(function (item) {
protocolsUsed.splice(protocolsUsed.indexOf(item), 1)
})
}
return transformer
function transformer (tree) {
// console.dir(tree, { depth: null })
visit(tree, 'paragraph', visitor)
// console.log('After:')
// console.dir(tree, { depth: null })
}
function visitor (node) {
var children = node.children
children.forEach(function (child, index) {
if (is(child, 'text')) {
var protListStr = protocols.join('|')
var mergePtrn = (protocols.includes('hypermerge')) ? '|(hypermerge://[-a-zA-Z0-9]*\\b([-a-zA-Z0-9@:%_+.~#?&//=]*))' : ''
var ptrn = new RegExp('((' + protListStr + '){1}://[-a-zA-Z0-9]{64}\\b([-a-zA-Z0-9@:%_+.~#?&//=]*))' + mergePtrn, 'g')
var matches = child.value.matchAll(ptrn)
var origVal = child.value
var pos = 0
var newChildren = []
for (const match of matches) {
newChildren.push({ type: 'text', value: origVal.substr(pos, match.index - pos) })
var altLink = { type: 'link', url: match[0], children: [{ type: 'text', value: match[0] }] }
newChildren.push(altLink)
pos = match.index + match[0].length
}
// get any trailing text
newChildren.push({ type: 'text', value: origVal.substr(pos) })
children.splice(index, 1, ...newChildren)
// Merge into current
// var cnPos = 0
// for (const cn of newChildren) {
// children.splice(index + cnPos, 0, cn)
// cnPos++
// }
}
})
}
}