-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkeyframes-tool.js
264 lines (246 loc) · 8.58 KB
/
keyframes-tool.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*! Keyframes-Tool | The MIT License (MIT) | Copyright (c) 2017 GibboK */
const css = require('css');
const R = require('ramda');
const fs = require('fs');
const path = require('path');
let fileIn,
fileOut;
/**
* Check software requirements.
*/
let checkPrerequisites = () => {
return new Promise((fulfill, reject) => {
try {
// check node version
let getNodeVersion = strVersion => {
let numberPattern = /\d+/g;
return numVersion = Number(strVersion.match(numberPattern).join(''))
},
requiredVersion = getNodeVersion('v6.9.1'),
currentVersion = getNodeVersion(process.version);
if (currentVersion >= requiredVersion) {
fulfill();
} else {
throw ('you current version of node.js is not supported, please update to the latest version of node.js');
}
} catch (err) {
reject(err);
}
});
};
/**
* Get arguments passed by Node.js from terminal.
*/
let getNodeArguments = () => {
return new Promise((fulfill, reject) => {
try {
// check paths in arguments
let hasFileInOutArgs = process.argv.length === 4;
if (!hasFileInOutArgs) {
throw ('arguments for file-in and file-out must be provided');
}
// normalize paths
fileIn = path.resolve(path.normalize(process.argv[2])).toString();
fileOut = path.resolve(path.normalize(process.argv[3])).toString();
// check paths for extensions
let isFileInCss = fileIn.endsWith('.css'),
isFileOutJson = fileOut.endsWith('.json');
if (!isFileInCss) {
throw ('argument file-in must have extension .css');
}
if (!isFileOutJson) {
throw ('argument file-out must have extension .json');
}
fulfill();
} catch (err) {
reject(err);
}
});
};
/**
* Read CSS input file.
*/
let readInputFile = () => {
// read css file
return new Promise((fulfill, reject) => {
fs.readFile(fileIn, (err, data) => {
if (err) {
reject(err);
} else {
fulfill(data);
}
});
});
}
/**
* Parse content of CSS input file and create an AST tree.
*/
let parse = data => {
return new Promise((fulfill, reject) => {
try {
let parsedData = css.parse(data.toString(), { silent: false });
fulfill(parsedData);
} catch (err) {
reject(err);
}
});
};
/**
* Validate AST tree content.
*/
let validate = data => {
return new Promise((fulfill, reject) => {
try {
let isStylesheet = data.type === 'stylesheet',
hasNoParsingErrors = 'stylesheet' in data && data.stylesheet.parsingErrors.length === 0,
hasKeyframes = R.any((rule) => rule.type === 'keyframes', data.stylesheet.rules);
if (!isStylesheet || !hasNoParsingErrors || !hasKeyframes) {
if (!isStylesheet) {
throw 'ast is not of type stylesheet';
}
if (!hasNoParsingErrors) {
R.map(err => console.log(new Error(`error: ${err}`)), data.stylesheet.parsingErrors);
throw 'file has parse error';
}
if (!hasKeyframes) {
throw 'no keyframes rules found';
}
}
fulfill(data);
} catch (err) {
reject(err);
}
});
};
/**
* Process AST tree content and a new data structure valid for Web Animation API KeyframeEffect.
* The following code uses Ramda.js for traversing a complex AST tree,
* an alternative and simplified version is visible at http://codepen.io/gibbok/pen/PbRrxp
*/
let processAST = data => {
return new Promise((fulfill, reject) => {
try {
let processKeyframe = (vals, declarations) => [
// map each value
R.map(R.cond([
[R.equals('from'), R.always("0")],
[R.equals('to'), R.always("1")],
[R.T, R.pipe(
// covert `offset` to a string representing a decimal point
parseFloat, R.divide(R.__, 100),
R.toString()
)]
]), vals),
// collect all property value pairs and merge in one object
R.reduce(R.merge, {},
R.map(R.converge(R.objOf, [
R.prop('property'),
R.prop('value')
]), declarations))
];
let processAnimation = (offsets, transf) =>
// process offset property
R.map(R.pipe(
R.objOf('offset'),
R.merge(transf)), offsets);
let getContentOfKeyframes = R.map(R.pipe(
// process keyframes
R.converge(processKeyframe, [
R.prop('values'),
R.prop('declarations')
]),
// process animations
R.converge(processAnimation, [
R.nth(0),
R.nth(1)
])));
let transformAST = R.pipe(
// get `stylesheet.rules` property
R.path(['stylesheet', 'rules']),
// get only object whose `type` property is `keyframes`
R.filter(R.propEq('type', 'keyframes')),
// map each item in `keyframes` collection
// to an object `{name: keyframe.name, content: [contentOfkeyframes] }`
R.map((keyframe) => ({
name: keyframe.name,
content: getContentOfKeyframes(keyframe.keyframes)
})),
// make a new object using animation `name` as keys
// and using a flatten content as values
R.converge(R.zipObj, [
R.map(R.prop('name')),
R.map(R.pipe(R.prop('content'), R.flatten))
])
);
// order by property `offset` ascending
let orderByOffset = R.map(R.pipe(R.sortBy(R.prop('offset'))));
// convert hyphenated properties to camelCase
let convertToCamelCase = data => {
let mapKeys = R.curry((fn, obj) =>
R.fromPairs(R.map(R.adjust(fn, 0), R.toPairs(obj)))
),
camelCase = (str) => str.replace(/[-_]([a-z])/g, (m) => m[1].toUpperCase())
return R.map(R.map(mapKeys(camelCase)), data)
};
// convert `animationTimingFunction` to `easing` for compatibility with web animations api
// and assign `easing` default value to `ease` when `animation-timing-function` from css file is not provided
let convertToEasing = data => {
const convert = data => {
const ease = R.prop('animationTimingFunction', data) || 'ease';
return R.dissoc('animationTimingFunction', R.assoc('easing', ease, data));
};
let result = R.map(R.map(convert))(data);
return result;
};
// process
let process = R.pipe(
transformAST,
orderByOffset,
convertToCamelCase,
convertToEasing
);
let result = process(data);
fulfill(result);
} catch (err) {
reject(err);
}
});
};
/**
* Write JSON output file.
*/
let writeOutputFile = data => {
return new Promise((fulfill, reject) => {
data = JSON.stringify(data);
fs.writeFile(fileOut, data, (err) => {
if (err) {
reject(err);
} else {
fulfill(data);
}
});
});
};
/**
* Initiate conversion process.
*/
let init = () => {
checkPrerequisites().then(() => {
return getNodeArguments();
}).then(() => {
return readInputFile();
}).then(data => {
return parse(data);
}).then(data => {
return validate(data);
}).then(data => {
return processAST(data);
}).then(data => {
return writeOutputFile(data);
}).then(data => {
console.log('success: file created at: ' + fileOut);
}).catch(err => {
console.log('error: ' + err);
});
};
init();