@sinchsmb/mktheme
Version:
Util that allow to make frontend theme from Figma theme export file
64 lines (56 loc) • 1.61 kB
JavaScript
const _ = require('lodash');
const Color = require('color');
const hexRegExp = /(#[0-9a-f]{6}[0-9a-f]{0,2})/gi;
const hslaRegExp = /(hsla[^)]+\))/g;
const nestedRgbRegExp = /rgba\(rgb\((?<red>\d+), (?<green>\d+), (?<blue>\d+)\), (?<alpha>\d(.\d+)?)\)/g;
/**
* Fix some usual Figma Tokens color format issue
*
* @param {string} color Figma color token
* @return {string} HTML HEX color or gradient
*/
function normalizeColor(color) {
[hexRegExp, hslaRegExp].forEach((regExp) => {
color = color.replace(regExp, (match) => {
return new Color(match).rgb().toString();
});
});
color = color.replace(nestedRgbRegExp, (match, r, g, b, a) => {
return new Color({ r, g, b }).alpha(a).toString();
});
return color;
}
/**
* Fix some usual Figma Tokens font-weight format issue
*
* @param {string} value Figma font-weight token
* @return {string} CSS font-weight
*/
function normalizeFontWeight(value) {
switch (value) {
case 'Regular':
return '400';
case 'Medium':
return '500';
case 'Bold':
return '700';
default:
throw new Error(`Can't normalize font-weight ${value}`);
}
}
function normalizeValues(theme) {
return _.cloneDeepWith(theme, function (value, key, object) {
if (value && typeof value === 'string') {
if (object?.type === 'color' && key === 'value') {
return normalizeColor(value);
}
if (key === 'color') {
return normalizeColor(value);
}
if (key === 'fontWeight') {
return normalizeFontWeight(value);
}
}
});
}
module.exports = { normalizeValues };