css-variables.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. export var token2CSSVar = function token2CSSVar(token) {
  3. var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  4. return "--".concat(prefix ? "".concat(prefix, "-") : '').concat(token).replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, '$1-$2').replace(/([a-z])([A-Z0-9])/g, '$1-$2').toLowerCase();
  5. };
  6. export var serializeCSSVar = function serializeCSSVar(cssVars, hashId, options) {
  7. if (!Object.keys(cssVars).length) {
  8. return '';
  9. }
  10. return ".".concat(hashId).concat(options !== null && options !== void 0 && options.scope ? ".".concat(options.scope) : '', "{").concat(Object.entries(cssVars).map(function (_ref) {
  11. var _ref2 = _slicedToArray(_ref, 2),
  12. key = _ref2[0],
  13. value = _ref2[1];
  14. return "".concat(key, ":").concat(value, ";");
  15. }).join(''), "}");
  16. };
  17. export var transformToken = function transformToken(token, themeKey, config) {
  18. var cssVars = {};
  19. var result = {};
  20. Object.entries(token).forEach(function (_ref3) {
  21. var _config$preserve, _config$ignore;
  22. var _ref4 = _slicedToArray(_ref3, 2),
  23. key = _ref4[0],
  24. value = _ref4[1];
  25. if (config !== null && config !== void 0 && (_config$preserve = config.preserve) !== null && _config$preserve !== void 0 && _config$preserve[key]) {
  26. result[key] = value;
  27. } else if ((typeof value === 'string' || typeof value === 'number') && !(config !== null && config !== void 0 && (_config$ignore = config.ignore) !== null && _config$ignore !== void 0 && _config$ignore[key])) {
  28. var _config$unitless;
  29. var cssVar = token2CSSVar(key, config === null || config === void 0 ? void 0 : config.prefix);
  30. cssVars[cssVar] = typeof value === 'number' && !(config !== null && config !== void 0 && (_config$unitless = config.unitless) !== null && _config$unitless !== void 0 && _config$unitless[key]) ? "".concat(value, "px") : String(value);
  31. result[key] = "var(".concat(cssVar, ")");
  32. }
  33. });
  34. return [result, serializeCSSVar(cssVars, themeKey, {
  35. scope: config === null || config === void 0 ? void 0 : config.scope
  36. })];
  37. };