This repository has been archived by the owner on Feb 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.coffee
98 lines (76 loc) · 2.2 KB
/
index.coffee
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
95
96
97
98
fs = require 'fs'
path = require 'path'
mkdirp = require 'mkdirp'
fsp = require 'fs-promise'
Mustache = require 'mustache'
{parseString} = require 'xml2js'
# Defaults
defaults = {
base64: false,
cwd: './',
templateCSS: "#{__dirname}/templateCSS.mst",
templateSCSS: "#{__dirname}/templateSCSS.mst",
spriteFileName: 'svg'
style: 'css'
}
pmkdirp = (dir) ->
new Promise (resolve, reject) ->
mkdirp(dir, (error) ->
return reject(error) if (error)
return resolve(dir)
)
_extend = (object, properties) ->
for key, val of properties
object[key] = val
object
_merge = (options, overrides) ->
_extend ( _extend {}, options), overrides
getTemplate = (options) ->
fsp.readFile(
if options.style.toLowerCase() == 'scss' then options.templateSCSS
else options.templateCSS
'utf8')
write = (rendered, cwd, dest) ->
pmkdirp(cwd).then(() -> fsp.writeFile("#{cwd}#{dest}", rendered).then(() -> return rendered) )
spriteName = (options) ->
return options.sprite if options.sprite?
options.spriteFileName + '.' + options.style.toLowerCase()
render = (files, template) -> Mustache.render(template, { files: files })
fixAppendix = (string) ->
return string if string.indexOf("px") == -1
string.slice(0,string.lastIndexOf("px"))
addMeasurements = (file) ->
new Promise (resolve, reject) ->
parseString(file.data, (err, result) =>
if(result.svg.$.width and result.svg.$.height)
file.width = fixAppendix(result.svg.$.width)
file.height = fixAppendix(result.svg.$.height)
resolve file
)
encode = (data, base64) ->
if base64 == true
return new Buffer(data).toString('base64')
return encodeURIComponent(data)
readFile = (filename, base64) ->
fsp.readFile(filename, 'utf8').then((data) ->
return {
name: path.basename(filename, '.svg')
data: data
encoded: encode(data, base64)
base64: base64
}
).then(addMeasurements)
module.exports = {
defaults: defaults
encode: (files, params) ->
options = _merge(defaults, params)
Promise.all(readFile(file, options.base64) for file in [].concat(files))
.then( (files) ->
getTemplate(options)
.then((template) ->
render(files, template)
)
).then((rendered) ->
write(rendered, options.cwd, spriteName(options))
)
}