1 | var split = require('../../../utils/split');
|
---|
2 | var startsAsUrl = require('./starts-as-url');
|
---|
3 |
|
---|
4 | var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel;
|
---|
5 |
|
---|
6 | var EXPRESSION_PATTERN = /^expression\(.*\)$/;
|
---|
7 | var ANY_FUNCTION_PATTERN = /^(-(?:moz|ms|o|webkit)-[a-z-]+|[a-z-]+)\((.+)\)$/;
|
---|
8 | var TOKEN_SEPARATOR_PATTERN = /([\s,/])/;
|
---|
9 |
|
---|
10 | var DOT_ZERO_PATTERN = /(^|\D)\.0+(\D|$)/g;
|
---|
11 | var FRACTION_PATTERN = /\.([1-9]*)0+(\D|$)/g;
|
---|
12 | var LEADING_ZERO_FRACTION_PATTERN = /(^|\D)0\.(\d)/g;
|
---|
13 | var MINUS_ZERO_FRACTION_PATTERN = /([^\w\d-]|^)-0([^.]|$)/g;
|
---|
14 | var ZERO_PREFIXED_UNIT_PATTERN = /(^|\s)0+([1-9])/g;
|
---|
15 |
|
---|
16 | function optimizeRecursively(value) {
|
---|
17 | var functionTokens;
|
---|
18 | var tokens;
|
---|
19 |
|
---|
20 | if (startsAsUrl(value)) {
|
---|
21 | return value;
|
---|
22 | }
|
---|
23 |
|
---|
24 | if (EXPRESSION_PATTERN.test(value)) {
|
---|
25 | return value;
|
---|
26 | }
|
---|
27 |
|
---|
28 | functionTokens = ANY_FUNCTION_PATTERN.exec(value);
|
---|
29 |
|
---|
30 | if (!functionTokens) {
|
---|
31 | return optimizeFractions(value);
|
---|
32 | }
|
---|
33 |
|
---|
34 | tokens = split(functionTokens[2], TOKEN_SEPARATOR_PATTERN)
|
---|
35 | .map(function(token) { return optimizeRecursively(token); });
|
---|
36 |
|
---|
37 | return functionTokens[1] + '(' + tokens.join('') + ')';
|
---|
38 | }
|
---|
39 |
|
---|
40 | function optimizeFractions(value) {
|
---|
41 | if (value.indexOf('0') == -1) {
|
---|
42 | return value;
|
---|
43 | }
|
---|
44 |
|
---|
45 | if (value.indexOf('-') > -1) {
|
---|
46 | value = value
|
---|
47 | .replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2')
|
---|
48 | .replace(MINUS_ZERO_FRACTION_PATTERN, '$10$2');
|
---|
49 | }
|
---|
50 |
|
---|
51 | return value
|
---|
52 | .replace(ZERO_PREFIXED_UNIT_PATTERN, '$1$2')
|
---|
53 | .replace(DOT_ZERO_PATTERN, '$10$2')
|
---|
54 | .replace(FRACTION_PATTERN, function(match, nonZeroPart, suffix) {
|
---|
55 | return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
|
---|
56 | })
|
---|
57 | .replace(LEADING_ZERO_FRACTION_PATTERN, '$1.$2');
|
---|
58 | }
|
---|
59 |
|
---|
60 | var plugin = {
|
---|
61 | level1: {
|
---|
62 | value: function fraction(name, value, options) {
|
---|
63 | if (!options.level[OptimizationLevel.One].replaceZeroUnits) {
|
---|
64 | return value;
|
---|
65 | }
|
---|
66 |
|
---|
67 | return optimizeRecursively(value);
|
---|
68 | }
|
---|
69 | }
|
---|
70 | };
|
---|
71 |
|
---|
72 | module.exports = plugin;
|
---|