All files / rsuite-theme/lib/util color.js

96.67% Statements 29/30
83.33% Branches 5/6
100% Functions 9/9
100% Lines 26/26
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    26x           1x 1x             1x 2x 2x 20x                 1x 2x 2x 6x                 1x 2x                 20x 20x 20x 20x 20x 20x 20x                 6x       6x 6x 6x 6x 6x  
'use strict';
 
function _toConsumableArray(arr) { Eif (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
 
/**
 * Created by Godfery on 2016/8/10 0010.
 */
 
var less = require('less');
var Color = less.tree.Color;
 
/**
 *
 * @param {Sting} baseColor - 基色
 * @returns {Array}
 */
module.exports.computeColors = function (baseColor) {
  var levels = [0.9, 0.7, 0.5, 0.333, 0.166, 0, -0.125, -0.25, -0.375, -0.5];
  return levels.map(function (level) {
    return shadeColor(baseColor, level);
  });
};
 
/**
 * less颜色转换
 * @param baseColor
 * @returns {Array}
 */
module.exports.lessComputeColors = function (baseColor) {
  var levels = [5, 10, 17];
  return levels.map(function (level) {
    return darkenColor(baseColor, level);
  });
};
 
/**
 * 计算色阶
 * @param baseColor - 基色
 * @returns {*[]}
 */
module.exports.calcColors = function (baseColor) {
  return [].concat(_toConsumableArray(module.exports.computeColors(baseColor)), _toConsumableArray(module.exports.lessComputeColors(baseColor)));
};
 
/*
 * Color utility functions
 * Source: http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors
 * Github: https://github.com/mbitson/mcg
 */
function shadeColor(color, percent) {
  var f = parseInt(color.slice(1), 16),
      t = percent < 0 ? 0 : 255,
      p = percent < 0 ? percent * -1 : percent,
      R = f >> 16,
      G = f >> 8 & 0x00FF,
      B = f & 0x0000FF;
  return "#" + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1);
}
 
/***
 * 获取less的function
 * @param name
 * @returns {*}
 */
function lessFunc(name) {
  return less.functions.functionRegistry.get(name);
}
 
function darkenColor(baseColor, amount) {
  baseColor = baseColor.split('#').join('');
  baseColor = new Color(baseColor);
  var darken = lessFunc('darken');
  baseColor = '#' + darken(baseColor, { value: amount }).toARGB().substr(3, 9);
  return baseColor;
}