-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
59 lines (47 loc) · 1.53 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
const fs = require('fs')
const cheerio = require('cheerio')
const isSVG = require('is-svg')
const uniq = require('lodash.uniq')
const compact = require('lodash.compact')
const chroma = require('chroma-js')
const hexy = /^#[0-9a-f]{3,6}$/i
function isColorString(str) {
if (!str) return false
if (str === 'none') return false
return (str.length === 4 || str.length === 7) && str.match(hexy)
}
function color(str) {
return isColorString(str) ? chroma(str) : null
}
module.exports = function getSvgColors(input, options) {
if (!isSVG(input)) {
input = fs.readFileSync(input, 'utf8')
}
const $ = cheerio.load(input)
// Find elements with a `fill` attribute
var fills = $('[fill]').map(function (i, el) {
return color($(this).attr('fill'))
}).get()
// Find elements with a `stroke` attribute
var strokes = $('[stroke]').map(function (i, el) {
return color($(this).attr('stroke'))
}).get()
// Find elements with a `stop-color` attribute (gradients)
var stops = $('[stop-color]').map(function (i, el) {
return color($(this).attr('stop-color'))
}).get()
// Find `fill`, `stroke` and `stops` within inline styles
$('[style]').each(function (i, el) {
fills.push(color($(this).css('fill')))
strokes.push(color($(this).css('stroke')))
stops.push(color($(this).css('stop-color')))
})
if (options && options.flat) {
return compact(uniq(fills.concat(strokes).concat(stops)))
}
return {
fills: compact(uniq(fills)),
strokes: compact(uniq(strokes)),
stops: compact(uniq(stops))
}
}