WIP Enable js defined theme to be used in SASS

This commit is contained in:
Dominik Prokop
2019-02-04 17:28:57 +01:00
parent 9e33f8b7c4
commit 7626ce9922
14 changed files with 506 additions and 123 deletions
+53
View File
@@ -0,0 +1,53 @@
const sass = require('node-sass');
const sassUtils = require('node-sass-utils')(sass);
const { getTheme } = require('../../packages/grafana-ui/src/theme');
const { get } = require('lodash');
const tinycolor = require('tinycolor2');
const units = ['rem', 'em', 'vh', 'vw', 'vmin', 'vmax', 'ex', '%', 'px', 'cm', 'mm', 'in', 'pt', 'pc', 'ch'];
const matchDimension = value => value.match(/[a-zA-Z]+|[0-9]+/g);
const isHex = value => {
const hexRegex = /^((0x){0,1}|#{0,1})([0-9A-F]{8}|[0-9A-F]{6})$/gi;
return hexRegex.test(value);
};
const isDimension = value => {
if( typeof value !== "string") {
return false;
}
const [val, unit] = matchDimension(value);
return units.indexOf(unit) > -1
};
/**
* @param {SassString} variablePath
* @param {"dark"|"light"} themeName
*/
function getThemeVariable(variablePath, themeName) {
const theme = getTheme(themeName.getValue());
const variable = get(theme, variablePath.getValue());
if (!variable) {
throw new Error(`${variablePath} is not defined fo ${themeName}`);
}
if (isHex(variable)) {
const rgb = new tinycolor(variable).toRgb();
const color = sass.types.Color(rgb.r, rgb.g, rgb.b);
return color;
}
if (isDimension(variable)) {
const [value, unit] = matchDimension(variable)
const tmp = new sassUtils.SassDimension(parseInt(value,10), unit);
// debugger
return sassUtils.castToSass(tmp)
}
return sassUtils.castToSass(variable);
}
module.exports = getThemeVariable;
+11 -2
View File
@@ -1,6 +1,7 @@
'use strict';
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const getThemeVariable = require('./getThemeVariable');
module.exports = function(options) {
return {
@@ -23,7 +24,15 @@ module.exports = function(options) {
config: { path: __dirname + '/postcss.config.js' },
},
},
{ loader: 'sass-loader', options: { sourceMap: options.sourceMap } },
{
loader: 'sass-loader',
options: {
sourceMap: options.sourceMap,
functions: {
'getThemeVariable($themeVar, $themeName: dark)': getThemeVariable,
},
},
},
],
};
};
+9 -1
View File
@@ -8,6 +8,7 @@ const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const IgnoreNotFoundExportPlugin = require("./IgnoreNotFoundExportPlugin.js");
const getThemeVariable = require("./getThemeVariable");
module.exports = merge(common, {
entry: {
@@ -85,7 +86,14 @@ module.exports = merge(common, {
config: { path: __dirname + '/postcss.config.js' },
},
},
'sass-loader', // compiles Sass to CSS
{
loader: 'sass-loader',
options: {
functions: {
"getThemeVariable($themeVar, $themeName: dark)": getThemeVariable
}
}
}
],
},
{