-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
54 lines (52 loc) · 2.43 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
const easingCoordinates = require('easing-coordinates')
const postcss = require('postcss')
const valueParser = require('postcss-value-parser')
const getColorStops = require('./lib/colorStops.js')
const helpers = require('./lib/helpers.js')
/**
* The easing gradient function is a postcss plugin which supports the in /.helpers mentioned gradient types.
*/
module.exports = postcss.plugin('easing-gradient', (options = {}) => {
return function (css) {
css.walkRules((rule) => {
rule.walkDecls((decl) => {
// If declaration value contains a linear-gradient.
if (decl.value.includes('linear-gradient')) {
// Parse the declaration and walk through the nodes - https://github.com/TrySound/postcss-value-parser.
const parsedValue = valueParser(decl.value)
parsedValue.walk((node) => {
// Only modify gradient as the value can contain more e.g. 'linear-gradient(black, pink) center'.
if (node.value === 'linear-gradient') {
// Get a sensible array of gradient parameters where e.g. a function is split into multiple array items
const gradientParams = valueParser
.stringify(helpers.divToSemiColon(node.nodes))
.split(';')
.map(str => str.trim())
gradientParams.forEach((param, i) => {
if (helpers.isTimingFunction(param)) {
try {
const colors = [gradientParams[i - 1], gradientParams[i + 1]]
const coordinates = easingCoordinates.easingCoordinates(param, options.precision)
const colorStops = getColorStops(colors, coordinates, options.alphaDecimals)
// Update node
node.type = 'word'
// Assume if it has 4 params it's because the first one is the direction
if (gradientParams.length === 4) {
node.value = `linear-gradient(${gradientParams[0]}, ${colorStops.join(', ')})`
} else {
node.value = `linear-gradient(${colorStops.join(', ')})`
}
// Update our declaration value
decl.value = parsedValue.toString()
} catch (error) {
console.log(helpers.errorMsg(decl.value))
}
}
})
}
})
}
})
})
}
})