forked from arve0/markdown-it-attrs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
278 lines (241 loc) · 7.51 KB
/
utils.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* parse {.class #id key=val} strings
* @param {string} str: string to parse
* @param {int} start: where to start parsing (including {)
* @returns {2d array}: [['key', 'val'], ['class', 'red']]
*/
exports.getAttrs = function (str, start, options) {
// not tab, line feed, form feed, space, solidus, greater than sign, quotation mark, apostrophe and equals sign
const allowedKeyChars = /[^\t\n\f />"'=]/;
const pairSeparator = ' ';
const keySeparator = '=';
const classChar = '.';
const idChar = '#';
const attrs = [];
let key = '';
let value = '';
let parsingKey = true;
let valueInsideQuotes = false;
// read inside {}
// start + left delimiter length to avoid beginning {
// breaks when } is found or end of string
for (let i = start + options.leftDelimiter.length; i < str.length; i++) {
if (str.slice(i, i + options.rightDelimiter.length) === options.rightDelimiter) {
if (key !== '') { attrs.push([key, value]); }
break;
}
const char_ = str.charAt(i);
// switch to reading value if equal sign
if (char_ === keySeparator && parsingKey) {
parsingKey = false;
continue;
}
// {.class} {..css-module}
if (char_ === classChar && key === '') {
if (str.charAt(i + 1) === classChar) {
key = 'css-module';
i += 1;
} else {
key = 'class';
}
parsingKey = false;
continue;
}
// {#id}
if (char_ === idChar && key === '') {
key = 'id';
parsingKey = false;
continue;
}
// {value="inside quotes"}
if (char_ === '"' && value === '' && !valueInsideQuotes) {
valueInsideQuotes = true;
continue;
}
if (char_ === '"' && valueInsideQuotes) {
valueInsideQuotes = false;
continue;
}
// read next key/value pair
if ((char_ === pairSeparator && !valueInsideQuotes)) {
if (key === '') {
// beginning or ending space: { .red } vs {.red}
continue;
}
attrs.push([key, value]);
key = '';
value = '';
parsingKey = true;
continue;
}
// continue if character not allowed
if (parsingKey && char_.search(allowedKeyChars) === -1) {
continue;
}
// no other conditions met; append to key/value
if (parsingKey) {
key += char_;
continue;
}
value += char_;
}
if (options.allowedAttributes && options.allowedAttributes.length) {
const allowedAttributes = options.allowedAttributes;
return attrs.filter(function (attrPair) {
const attr = attrPair[0];
function isAllowedAttribute (allowedAttribute) {
return (attr === allowedAttribute
|| (allowedAttribute instanceof RegExp && allowedAttribute.test(attr))
);
}
return allowedAttributes.some(isAllowedAttribute);
});
}
return attrs;
};
/**
* add attributes from [['key', 'val']] list
* @param {array} attrs: [['key', 'val']]
* @param {token} token: which token to add attributes
* @returns token
*/
exports.addAttrs = function (attrs, token) {
for (let j = 0, l = attrs.length; j < l; ++j) {
const key = attrs[j][0];
if (key === 'class') {
token.attrJoin('class', attrs[j][1]);
} else if (key === 'css-module') {
token.attrJoin('css-module', attrs[j][1]);
} else {
token.attrPush(attrs[j]);
}
}
return token;
};
/**
* Does string have properly formatted curly?
*
* start: '{.a} asdf'
* end: 'asdf {.a}'
* only: '{.a}'
*
* @param {string} where to expect {} curly. start, end or only.
* @return {function(string)} Function which testes if string has curly.
*/
exports.hasDelimiters = function (where, options) {
if (!where) {
throw new Error('Parameter `where` not passed. Should be "start", "end" or "only".');
}
/**
* @param {string} str
* @return {boolean}
*/
return function (str) {
// we need minimum three chars, for example {b}
const minCurlyLength = options.leftDelimiter.length + 1 + options.rightDelimiter.length;
if (!str || typeof str !== 'string' || str.length < minCurlyLength) {
return false;
}
function validCurlyLength (curly) {
const isClass = curly.charAt(options.leftDelimiter.length) === '.';
const isId = curly.charAt(options.leftDelimiter.length) === '#';
return (isClass || isId)
? curly.length >= (minCurlyLength + 1)
: curly.length >= minCurlyLength;
}
let start, end, slice, nextChar;
const rightDelimiterMinimumShift = minCurlyLength - options.rightDelimiter.length;
switch (where) {
case 'start':
// first char should be {, } found in char 2 or more
slice = str.slice(0, options.leftDelimiter.length);
start = slice === options.leftDelimiter ? 0 : -1;
end = start === -1 ? -1 : str.indexOf(options.rightDelimiter, rightDelimiterMinimumShift);
// check if next character is not one of the delimiters
nextChar = str.charAt(end + options.rightDelimiter.length);
if (nextChar && options.rightDelimiter.indexOf(nextChar) !== -1) {
end = -1;
}
break;
case 'end':
// last char should be }
start = str.lastIndexOf(options.leftDelimiter);
end = start === -1 ? -1 : str.indexOf(options.rightDelimiter, start + rightDelimiterMinimumShift);
end = end === str.length - options.rightDelimiter.length ? end : -1;
break;
case 'only':
// '{.a}'
slice = str.slice(0, options.leftDelimiter.length);
start = slice === options.leftDelimiter ? 0 : -1;
slice = str.slice(str.length - options.rightDelimiter.length);
end = slice === options.rightDelimiter ? str.length - options.rightDelimiter.length : -1;
break;
default:
throw new Error(`Unexpected case ${where}, expected 'start', 'end' or 'only'`);
}
return start !== -1 && end !== -1 && validCurlyLength(str.substring(start, end + options.rightDelimiter.length));
};
};
/**
* Removes last curly from string.
*/
exports.removeDelimiter = function (str, options) {
const start = escapeRegExp(options.leftDelimiter);
const end = escapeRegExp(options.rightDelimiter);
const curly = new RegExp(
'[ \\n]?' + start + '[^' + start + end + ']+' + end + '$'
);
const pos = str.search(curly);
return pos !== -1 ? str.slice(0, pos) : str;
};
/**
* Escapes special characters in string s such that the string
* can be used in `new RegExp`. For example "[" becomes "\\[".
*
* @param {string} s Regex string.
* @return {string} Escaped string.
*/
function escapeRegExp (s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
exports.escapeRegExp = escapeRegExp;
/**
* find corresponding opening block
*/
exports.getMatchingOpeningToken = function (tokens, i) {
if (tokens[i].type === 'softbreak') {
return false;
}
// non closing blocks, example img
if (tokens[i].nesting === 0) {
return tokens[i];
}
const level = tokens[i].level;
const type = tokens[i].type.replace('_close', '_open');
for (; i >= 0; --i) {
if (tokens[i].type === type && tokens[i].level === level) {
return tokens[i];
}
}
return false;
};
/**
* from https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.js
*/
const HTML_ESCAPE_TEST_RE = /[&<>"]/;
const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
const HTML_REPLACEMENTS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"'
};
function replaceUnsafeChar(ch) {
return HTML_REPLACEMENTS[ch];
}
exports.escapeHtml = function (str) {
if (HTML_ESCAPE_TEST_RE.test(str)) {
return str.replace(HTML_ESCAPE_REPLACE_RE, replaceUnsafeChar);
}
return str;
};