-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathtype-scale.js
More file actions
43 lines (33 loc) · 1.14 KB
/
Copy pathtype-scale.js
File metadata and controls
43 lines (33 loc) · 1.14 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
const postcss = require('postcss')
const defaults = {
rootSelector: ':root',
typeRatio: 1.2,
ratioProperty: '--type-ratio'
}
module.exports = postcss.plugin('type-scale', (opts = defaults) => {
const options = Object.assign(defaults, opts)
return css => {
const typeRatio = getTypeRatio(css, options)
css.walkDecls('font-size', decl => {
// Replace only if it's a unitless value
if (/\d+$/.test(decl.value)) decl.value = getSize(decl.value, typeRatio)
})
}
})
function getTypeRatio (css, opts) {
// Start with the default ratio
let typeRatio = opts.typeRatio
// 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-size rules
rule.walkDecls(opts.ratioProperty, decl => {
typeRatio = parseFloat(decl.value)
})
})
return typeRatio
}
function getSize(val, ratio) {
return parseFloat(Math.pow(ratio, parseInt(val) - 2).toFixed(4)) + 'rem'
}