83 lines
1.8 KiB
JavaScript
83 lines
1.8 KiB
JavaScript
// Copyright (c) 2014 Rafael Caricio. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
|
|
var GradientParser = (GradientParser || {});
|
|
|
|
GradientParser.stringify = (function() {
|
|
|
|
var visitor = {
|
|
|
|
'visit_linear-gradient': function(node) {
|
|
var orientation = visitor.visit(node.orientation);
|
|
if (orientation) {
|
|
orientation += ', ';
|
|
}
|
|
|
|
return 'linear-gradient('+ orientation + visitor.visit(node.colorStops) + ')';
|
|
},
|
|
|
|
visit_literal: function(node) {
|
|
return node.value;
|
|
},
|
|
|
|
visit_angular: function(node) {
|
|
return node.value + 'deg';
|
|
},
|
|
|
|
visit_hex: function(node) {
|
|
return '#' + node.value;
|
|
},
|
|
|
|
visit_rgb: function(node) {
|
|
return 'rgb(' + node.value.join(', ') + ')';
|
|
},
|
|
|
|
visit_rgba: function(node) {
|
|
return 'rgba(' + node.value.join(', ') + ')';
|
|
},
|
|
|
|
visit_directional: function(node) {
|
|
return 'to ' + node.value;
|
|
},
|
|
|
|
visit_array: function(elements) {
|
|
var result = '',
|
|
size = elements.length;
|
|
|
|
elements.forEach(function(element, i) {
|
|
result += visitor.visit(element);
|
|
if (i < size - 1) {
|
|
result += ', ';
|
|
}
|
|
});
|
|
|
|
return result;
|
|
},
|
|
|
|
visit: function(element) {
|
|
if (!element) {
|
|
return '';
|
|
}
|
|
|
|
if (element instanceof Array) {
|
|
return visitor.visit_array(element, result);
|
|
} else if (element.type) {
|
|
var nodeVisitor = visitor['visit_' + element.type];
|
|
if (nodeVisitor) {
|
|
return nodeVisitor(element);
|
|
} else {
|
|
throw Error('Missing visitor visit_' + element.type);
|
|
}
|
|
} else {
|
|
throw Error('Invalid node.');
|
|
}
|
|
}
|
|
|
|
};
|
|
|
|
return function(root) {
|
|
return visitor.visit(root);
|
|
};
|
|
})();
|