-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (75 loc) · 2.51 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
var postcss = require('postcss');
/**
* Add number padding
* @param {Integer} number Number to modify
* @param {Integer} targetLength Digits count
* @return {String} Number with padding
*/
function leftPad(number, targetLength) {
var output = number + '';
while (output.length < targetLength) {
output = '0' + output;
}
return output;
};
/**
* Dash string generator
* @param {Integer} count Dashes count
* @return {String} Dashes string
*/
function generateDashes(count) {
return (new Array((Math.max(count, 0) - 0) + 1).join('-'));
};
module.exports = postcss.plugin('postcss-toc', plugin);
function plugin(opts) {
opts = opts || {};
return function (css, result) {
var tableLength = 50;
var comments = [];
var table = [];
var majorCommentIdx = 0;
var header = '\tTable of Contents';
css.walkComments(function(comment) {
var majorCommentRegExp = /-*\s\*\\[\n\r]\s*(.*?)[\n\r]+\\\*\s-*/;
var commentRaw = comment.source.input.css;
if (comment.text.match(majorCommentRegExp)) {
var commentText = comment.text.match(majorCommentRegExp)[1];
comments.push({
text: commentText,
type: 'major',
isRoman: commentText.match(/^[\I\V\X]*\.\s/)
});
} else {
if (/^[A-Z]/.test(comment.text)) {
comments.push({
text: comment.text,
type: 'minor'
});
}
}
});
for (var i = 0; i < comments.length; i++) {
var commentPrefix = '';
var tableText = '';
if (comments[i].type === 'major') {
if(!comments[i].isRoman) {
majorCommentIdx += 1;
commentPrefix = ' ' + leftPad(majorCommentIdx, 2) + '. ';
} else {
majorCommentIdx = 0;
};
} else {
commentPrefix = ' ';
}
tableText = commentPrefix + comments[i].text;
table.push(tableText + ' ' + generateDashes(tableLength - tableText.length));
}
css.prepend({
text: '\n' + header + '\n\n' + table.join('\n') + '\n'
});
if (css.first && css.first.next()) {
css.first.next().raws.before = '\n\n';
}
};
}