UNPKG

@zhsz/cool-design-dv

Version:

111 lines (110 loc) 2.93 kB
import colorKeywords from "./keywords.mjs"; const hexReg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; const rgbReg = /^(rgb|rgba|RGB|RGBA)/; const rgbaReg = /^(rgba|RGBA)/; function validator(color) { const isHex = hexReg.test(color); const isRgb = rgbReg.test(color); if (isHex || isRgb) return color; color = getColorByKeyword(color); if (!color) { console.error("Color: Invalid color!"); return false; } return color; } function getColorByKeyword(keyword) { if (!keyword) { console.error("getColorByKeywords: Missing parameters!"); return false; } if (!colorKeywords.has(keyword)) return false; return colorKeywords.get(keyword); } function getRgbValue(color) { if (!color) { console.error("getRgbValue: Missing parameters!"); return false; } color = validator(color); if (!color) return false; const isHex = hexReg.test(color); const isRgb = rgbReg.test(color); const lowerColor = color.toLowerCase(); if (isHex) return getRgbValueFromHex(lowerColor); if (isRgb) return getRgbValueFromRgb(lowerColor); } function getRgbValueFromHex(color) { color = color.replace("#", ""); if (color.length === 3) color = Array.from(color).map((hexNum) => hexNum + hexNum).join(""); color = color.split(""); return new Array(3).fill(0).map((t, i) => parseInt(`0x${color[i * 2]}${color[i * 2 + 1]}`)); } function getRgbValueFromRgb(color) { return color.replace(/rgb\(|rgba\(|\)/g, "").split(",").slice(0, 3).map((n) => parseInt(n)); } function getRgbaValue(color) { if (!color) { console.error("getRgbaValue: Missing parameters!"); return false; } const colorValue = getRgbValue(color); if (!colorValue) return false; colorValue.push(getOpacity(color)); return colorValue; } function getOpacity(color) { if (!color) { console.error("getOpacity: Missing parameters!"); return false; } color = validator(color); if (!color) return false; const isRgba = rgbaReg.test(color); if (!isRgba) return 1; color = color.toLowerCase(); return Number( color.split(",").slice(-1)[0].replace(/[)|\s]/g, "") ); } function getColorFromRgbValue(value) { if (!value) { console.error("getColorFromRgbValue: Missing parameters!"); return false; } const valueLength = value.length; if (valueLength !== 3 && valueLength !== 4) { console.error("getColorFromRgbValue: Value is illegal!"); return false; } let color = valueLength === 3 ? "rgb(" : "rgba("; color += value.join(",") + ")"; return color; } function fade(color, percent = 100) { if (!color) { console.error("fade: Missing parameters!"); return false; } const rgbValue = getRgbValue(color); if (!rgbValue) return false; const rgbaValue = [...rgbValue, percent / 100]; return getColorFromRgbValue(rgbaValue); } export { fade, getColorFromRgbValue, getOpacity, getRgbValue, getRgbaValue };