getThemeVariable.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const sass = require('node-sass');
  2. const sassUtils = require('node-sass-utils')(sass);
  3. const { getTheme } = require('../../packages/grafana-ui/src/theme');
  4. const { get } = require('lodash');
  5. const tinycolor = require('tinycolor2');
  6. const units = ['rem', 'em', 'vh', 'vw', 'vmin', 'vmax', 'ex', '%', 'px', 'cm', 'mm', 'in', 'pt', 'pc', 'ch'];
  7. const matchDimension = value => value.match(/[a-zA-Z]+|[0-9]+/g);
  8. const isHex = value => {
  9. const hexRegex = /^((0x){0,1}|#{0,1})([0-9A-F]{8}|[0-9A-F]{6})$/gi;
  10. return hexRegex.test(value);
  11. };
  12. const isDimension = value => {
  13. if( typeof value !== "string") {
  14. return false;
  15. }
  16. const [val, unit] = matchDimension(value);
  17. return units.indexOf(unit) > -1
  18. };
  19. /**
  20. * @param {SassString} variablePath
  21. * @param {"dark"|"light"} themeName
  22. */
  23. function getThemeVariable(variablePath, themeName) {
  24. const theme = getTheme(themeName.getValue());
  25. const variable = get(theme, variablePath.getValue());
  26. if (!variable) {
  27. throw new Error(`${variablePath} is not defined fo ${themeName}`);
  28. }
  29. if (isHex(variable)) {
  30. const rgb = new tinycolor(variable).toRgb();
  31. const color = sass.types.Color(rgb.r, rgb.g, rgb.b);
  32. return color;
  33. }
  34. if (isDimension(variable)) {
  35. const [value, unit] = matchDimension(variable)
  36. const tmp = new sassUtils.SassDimension(parseInt(value,10), unit);
  37. // debugger
  38. return sassUtils.castToSass(tmp)
  39. }
  40. return sassUtils.castToSass(variable);
  41. }
  42. module.exports = getThemeVariable;