/
remark-jsDoc-link.js
115 lines (104 loc) · 2.71 KB
/
remark-jsDoc-link.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
const findAndReplace = require('mdast-util-find-and-replace');
const markdownLineEnding = require('micromark/dist/character/markdown-line-ending');
const link = '@link';
const tutorial = '@tutorial';
function tokenizeJsDoclink(effects, ok, nok) {
let index = 0;
let focus = link;
function atext(code) {
if (index !== link.length) {
if (focus.charCodeAt(index) === code) {
effects.consume(code);
index++;
return atext;
} else if (tutorial.charCodeAt(index) === code) {
focus = tutorial;
}
return nok(code);
}
if (code === 125) {
effects.consume(code);
effects.exit('literalJsDoclink');
return ok(code);
}
if (markdownLineEnding(code)) {
return nok(code);
}
effects.consume(code);
return atext;
}
return function (code) {
effects.enter('literalJsDoclink');
effects.consume(code);
return atext;
};
}
const text = {};
text[123] = {
tokenize: tokenizeJsDoclink,
previous(code) {
return code === null || code === 32 || markdownLineEnding(code);
}
};
const linkRegExp = /\{@link\s+(.+?)(?:[\s|](.*?))?\}/;
const tutorialRegExp = /\{@tutorial\s+(.+?)(?:[\s|](.*?))?\}/;
/**
* A remark plugin that installs
* for JSDoc inline `{@link}` and `{@tutorial}` tags.
*
* This does not handle the `[text]({@link url})` and `[text]({@tutorial url})` forms of these tags.
* That's a JSDoc misfeature; just use regular markdown syntax instead: `[text](url)`.
*
* @returns {Function}
*/
module.exports = function () {
const data = this.data();
function replace(type) {
return (match, matchUrl, matchValue) => {
return {
type,
url: matchUrl,
title: null,
jsdoc: true,
children: [
{
type: 'text',
value: matchValue || matchUrl
}
]
};
};
}
add('micromarkExtensions', { text });
add('fromMarkdownExtensions', {
transforms: [
function (markdownAST) {
return findAndReplace(markdownAST, [
[new RegExp(linkRegExp.source, 'g'), replace('link')],
[new RegExp(tutorialRegExp.source, 'g'), replace('tutorial')]
]);
}
],
enter: {
literalJsDoclink(token) {
const str = this.sliceSerialize(token);
let match = null;
if (str.startsWith('{@link')) {
match = linkRegExp.exec(str);
} else {
match = tutorialRegExp.exec(str);
}
this.enter(replace('link')(...match), token);
}
},
exit: {
literalJsDoclink(token) {
this.exit(token);
}
}
});
function add(field, value) {
if (data[field]) data[field].push(value);
else data[field] = [value];
}
};