forked from ConciseCSS/concise.css
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlh.js
More file actions
45 lines (35 loc) · 1.35 KB
/
lh.js
File metadata and controls
45 lines (35 loc) · 1.35 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
const postcss = require('postcss')
const defaults = {
rootSelector: ':root',
unit: 'lh',
lineHeight: 1.5
}
module.exports = postcss.plugin('lh', (opts = defaults) => {
const options = Object.assign(defaults, opts)
return css => {
const lineHeight = getLineHeight(css, options)
const lhReg = new RegExp('\\d*\\.?\\d+' + options.unit, 'gi')
css.replaceValues(lhReg, { fast: options.unit }, (val) => {
return lhToRem(parseFloat(val), lineHeight)
})
}
})
function getLineHeight (css, opts) {
// Start with the default line-height
let lineHeight = opts.lineHeight
// Walk over all the root selectors
css.walkRules(opts.rootSelector, rule => {
// Omit the process if the selector is inside a print media query
if (rule.parent && rule.parent.params === 'print') return
// Walk over all the font or line-height properties
rule.walkDecls(/font$|line-height/, decl => {
// Matches {$1:font-size}{$2:unit}/{$3:line-height} when the property is 'font'
const fontProps = decl.value.match(/(\d+|\d+?\.\d+)(r?em|px|%)(?:\s*\/\s*)(\d+|\d+?\.\d+)\s+/) || []
lineHeight = fontProps[3] || decl.value
})
})
return lineHeight
}
function lhToRem(val, lineHeight) {
return parseFloat((lineHeight * val).toFixed(3)) + 'rem'
}