getThemeVariable.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const sass = require('node-sass');
  2. const sassUtils = require('node-sass-utils')(sass);
  3. const { get } = require('lodash');
  4. const tinycolor = require('tinycolor2');
  5. const { getTheme } = require('@grafana/ui/src/themes');
  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 dimension = new sassUtils.SassDimension(parseInt(value, 10), unit);
  37. return sassUtils.castToSass(dimension);
  38. }
  39. return sassUtils.castToSass(variable);
  40. }
  41. module.exports = getThemeVariable;