-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
94 lines (76 loc) · 2.25 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
var postcss = require('postcss');
/**
* Convert unit to unitless px value.
* @param {Number} value
* @param {String} unit
* @return {Number}
*/
var toPx = function (value, unit) {
if (unit === 'em' || unit === 'rem') {
return parseFloat(value) * 16;
} else if (unit === '%') {
return parseFloat(value) / 100 * 16;
}
// This will be a px value, thanks to strict regex.
return value;
};
/**
* Calculate unitless px line-height based on font-size + line-height.
* @param {Array} fontProps
* @return {Number}
*/
var calcLineHeight = function (fontProps) {
var fontSize = fontProps[1];
var fontUnit = fontProps[2];
var lineHeight = fontProps[3];
return toPx(fontSize, fontUnit) * lineHeight;
};
/**
* Gets the font declaration properties.
* @param {Object} decl
* @return {Array}
*/
var getProps = function (decl) {
// Matches {$1:font-size}{$2:unit}/{$3:line-height}.
var fontProps = decl.value.match(/(\d+|\d+?\.\d+)(r?em|px|%)(?:\s*\/\s*)(\d+|\d+?\.\d+)\s+/);
// Make sure font delcaration is valid.
if (!fontProps) {
throw decl.error('Font declaration is invalid.');
}
return fontProps;
};
/**
* Gets the rhythm value.
* @param {Number} declValue
* @return {Number}
*/
var getRhythmValue = function (declValue, rhythmValue) {
var val = parseFloat(declValue) || 1;
return rhythmValue * val;
};
module.exports = postcss.plugin('postcss-vertical-rhythm', function (opts) {
opts = opts || {};
var rootSelector = opts.rootSelector || 'body';
var rhythmUnit = 'vr';
var rhythmValue;
return function (css) {
css.walkDecls(function transformDecl (decl) {
// Check for root font-size.
if (decl.parent.selector === rootSelector) {
if (decl.prop === 'font') {
var props = getProps(decl);
rhythmValue = calcLineHeight(props);
}
}
// Calculate ryhthm value.
if (decl.value.indexOf(rhythmUnit) !== -1) {
// Use new RegExp to capture var.
var regexp = new RegExp('(\\d*\\.?\\d+)' + rhythmUnit, 'gi');
// Replace each vr unit value in the decl.value, e.g. shorthand properties.
decl.value = decl.value.replace(regexp, function ($1) {
return getRhythmValue($1, rhythmValue) + 'px';
});
}
});
};
});