utils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { GlobalToken } from "antd";
  2. import { baseColorPalettes, neutralColors, prefix, productLevelColorSystem } from "./constants";
  3. /**
  4. * 16 进制颜色值转 RGB 颜色值,因为 16 进制的颜色值在 tailwind 中不支持透明度,比如无法使用 bg-blue-500/20
  5. * @see https://tailwindcss.com/docs/customizing-colors#using-css-variables
  6. */
  7. export function hexToRGB(hex: string) {
  8. // 移除可能存在的 # 号
  9. hex = hex.replace("#", "");
  10. // 获取 R、G、B 的值
  11. const r = Number.parseInt(hex.substring(0, 2), 16);
  12. const g = Number.parseInt(hex.substring(2, 4), 16);
  13. const b = Number.parseInt(hex.substring(4, 6), 16);
  14. return `${r} ${g} ${b}`;
  15. }
  16. // 判断是否是 RGB 颜色值
  17. export function isRGBColor(color: string) {
  18. return color.trim().startsWith("rgb");
  19. }
  20. export function getCSSVariablesByTokens(tokens: GlobalToken) {
  21. return Object.entries(tokens)
  22. .reduce((acc, [key, value]): string => {
  23. // 功能色系,不包含中性色系
  24. if (productLevelColorSystem.includes(key)) {
  25. const rgb = hexToRGB(value);
  26. return `${acc}--${prefix}-${key}:${rgb};`;
  27. }
  28. // 中性色系
  29. if (neutralColors.includes(key)) {
  30. // 如果颜色值是 rgb 格式,则直接使用
  31. const rgb = isRGBColor(value) ? value : `rgb(${hexToRGB(value)})`;
  32. return `${acc}--${prefix}-${key}:${rgb};`;
  33. }
  34. // 色板
  35. return baseColorPalettes.includes(key) ? `${acc}--${prefix}-${key}:${hexToRGB(value)};` : acc;
  36. }, "");
  37. }