This repository has been archived by the owner on Dec 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
76 lines (63 loc) · 2.01 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const parser = require('postcss-selector-parser');
const anyAnyLinkMatch = /:any-link/;
/**
* @param {{preserve?: boolean}} opts
* @returns {import('postcss').Plugin}
*/
module.exports = function creator(opts) {
const preserve = 'preserve' in Object(opts) ? Boolean(opts.preserve) : true;
return {
postcssPlugin: 'postcss-pseudo-class-any-link',
Rule(rule) {
if (!anyAnyLinkMatch.test(rule.selector)) {
return;
}
const rawSelector = rule.raws.selector && rule.raws.selector.raw || rule.selector;
// workaround for https://github.com/postcss/postcss-selector-parser/issues/28#issuecomment-171910556
if (rawSelector[rawSelector.length - 1] !== ':') {
// update the selector
const updatedSelector = parser(selectors => {
// cache variables
let node;
let nodeIndex;
let selector;
let selectorLink;
let selectorVisited;
// cache the selector index
let selectorIndex = -1;
// for each selector
while (selector = selectors.nodes[++selectorIndex]) {
// reset the node index
nodeIndex = -1;
// for each node
while (node = selector.nodes[++nodeIndex]) {
// if the node value matches the any-link value
if (node.value === ':any-link') {
// clone the selector
selectorLink = selector.clone();
selectorVisited = selector.clone();
// update the matching clone values
selectorLink.nodes[nodeIndex].value = ':link';
selectorVisited.nodes[nodeIndex].value = ':visited';
// replace the selector with the clones and roll back the selector index
selectors.nodes.splice(selectorIndex--, 1, selectorLink, selectorVisited);
// stop updating the selector
break;
}
}
}
}).processSync(rawSelector);
if (updatedSelector !== rawSelector) {
if (preserve) {
rule.cloneBefore({
selector: updatedSelector
});
} else {
rule.selector = updatedSelector;
}
}
}
}
}
}
module.exports.postcss = true;