polished
Version:
A lightweight toolset for writing styles in Javascript.
63 lines (60 loc) • 2.92 kB
JavaScript
exports.__esModule = true;
exports["default"] = toColorString;
var _hsl = _interopRequireDefault(require("./hsl"));
var _hsla = _interopRequireDefault(require("./hsla"));
var _rgb = _interopRequireDefault(require("./rgb"));
var _rgba = _interopRequireDefault(require("./rgba"));
var _errors = _interopRequireDefault(require("../internalHelpers/_errors"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var isRgb = function isRgb(color) {
return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');
};
var isRgba = function isRgba(color) {
return typeof color.red === 'number' && typeof color.green === 'number' && typeof color.blue === 'number' && typeof color.alpha === 'number';
};
var isHsl = function isHsl(color) {
return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && (typeof color.alpha !== 'number' || typeof color.alpha === 'undefined');
};
var isHsla = function isHsla(color) {
return typeof color.hue === 'number' && typeof color.saturation === 'number' && typeof color.lightness === 'number' && typeof color.alpha === 'number';
};
/**
* Converts a RgbColor, RgbaColor, HslColor or HslaColor object to a color string.
* This util is useful in case you only know on runtime which color object is
* used. Otherwise we recommend to rely on `rgb`, `rgba`, `hsl` or `hsla`.
*
* @example
* // Styles as object usage
* const styles = {
* background: toColorString({ red: 255, green: 205, blue: 100 }),
* background: toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 }),
* background: toColorString({ hue: 240, saturation: 1, lightness: 0.5 }),
* background: toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 }),
* }
*
* // styled-components usage
* const div = styled.div`
* background: ${toColorString({ red: 255, green: 205, blue: 100 })};
* background: ${toColorString({ red: 255, green: 205, blue: 100, alpha: 0.72 })};
* background: ${toColorString({ hue: 240, saturation: 1, lightness: 0.5 })};
* background: ${toColorString({ hue: 360, saturation: 0.75, lightness: 0.4, alpha: 0.72 })};
* `
*
* // CSS in JS Output
* element {
* background: "#ffcd64";
* background: "rgba(255,205,100,0.72)";
* background: "#00f";
* background: "rgba(179,25,25,0.72)";
* }
*/
function toColorString(color) {
if (typeof color !== 'object') throw new _errors["default"](8);
if (isRgba(color)) return (0, _rgba["default"])(color);
if (isRgb(color)) return (0, _rgb["default"])(color);
if (isHsla(color)) return (0, _hsla["default"])(color);
if (isHsl(color)) return (0, _hsl["default"])(color);
throw new _errors["default"](8);
}
module.exports = exports.default;
;