forked from javascript-tutorial/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.js
More file actions
executable file
·66 lines (55 loc) · 1.36 KB
/
token.js
File metadata and controls
executable file
·66 lines (55 loc) · 1.36 KB
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
'use strict';
/**
* tokenAttrReplace(name, value)
*
* Replace all attributes with name `name` with one with the value `attrData`
**/
function attrReplace(token, name, value) {
let found;
let attrs = token.attrs;
if (attrs) {
// modify the existing attr is possible
for (let i = 0; i < attrs.length; i++) {
if (attrs[i][0] === name) {
if (!found) {
attrs[i][1] = value;
found = true;
} else {
// remove extra attrs with same name
attrs.splice(i, 1);
i--;
}
}
}
// add a new attribute with such name if none was found
if (!found) {
attrs.push([name, value]);
}
} else {
token.attrs = [ [name, value] ];
}
}
function addClass(token, value) {
let classAttr = attrGet(token, 'class');
if (classAttr.match(new RegExp(`\b${value}\b`))) return;
if (classAttr) {
classAttr += ' ' + value;
} else {
classAttr = value;
}
attrReplace(token, 'class', classAttr);
}
function attrGet(token, name) {
let idx = token.attrIndex(name);
if (idx == -1) return null;
return token.attrs[idx][1];
}
function attrDel(token, name) {
let idx = token.attrIndex(name);
if (idx == -1) return null;
token.attrs.splice(idx, 1);
}
exports.attrReplace = attrReplace;
exports.attrGet = attrGet;
exports.attrDel = attrDel;
exports.addClass = addClass;