vcc-ui
Version:
VCC UI is a collection of React UI Components that can be used for developing front-end applications at Volvo Car Corporation.
90 lines (76 loc) • 2.61 kB
JavaScript
import { createRenderer } from 'fela';
import webPreset from 'fela-preset-web';
import rtl from 'fela-plugin-rtl';
import hexToRgba from 'hex-to-rgba';
import sortClassnames from 'fela-sort-classnames';
import sortMediaQueryMobileFirst from 'fela-sort-media-query-mobile-first';
import { deprecate } from './deprecate';
export function styleRenderer({ isRtl, ...rest } = {}) {
deprecate(
'Using the "isRtl" prop is deprecated and will cause no effect in the next major update. Use the "theme.direction" key instead. See https://github.com/rofrischmann/fela/tree/master/packages/fela-plugin-rtl#theme-based-mode',
isRtl !== undefined
);
const options = rest || {};
return createRenderer({
...options,
enhancers: [
sortClassnames(),
sortMediaQueryMobileFirst(),
...(options.enhancers || []),
],
plugins: [
...webPreset,
themeFontsPlugin,
hexToRgbaPlugin,
rtl(isRtl ? 'rtl' : 'ltr'),
...(options.plugins || []),
].filter(Boolean),
});
}
function themeFontsPlugin(style, type, renderer, props) {
const fonts = (props.theme && props.theme.fonts) || [];
const fontsPath = (props.theme && props.theme.fontsPath) || '';
for (const property in style) {
const value = style[property];
// TODO: maybe we wanna cache already rendered fonts
// but no high prio as Fela does that as well
if (typeof value === 'string' && property === 'fontFamily') {
// check each alternative font value
const fontValues = value.split(',');
const usedFonts = fonts.filter(
font => fontValues.indexOf(font.fontFamily) !== -1
);
if (usedFonts.length > 0) {
usedFonts.forEach(({ fontFamily, src, ...fontProps }) =>
renderer.renderFont(
fontFamily,
src.map(
// allow absolute files with http prefix
file => (file.indexOf('http') === -1 ? fontsPath : '') + file
),
fontProps
)
);
}
} else if (typeof value === 'object' && !Array.isArray(value)) {
themeFontsPlugin(value, type, renderer, props);
}
}
return style;
}
// TODO: move to fela repo as an official plugin
function hexToRgbaPlugin(style) {
for (const property in style) {
const value = style[property];
if (
typeof value === 'string' &&
value.indexOf('#') === 0 &&
value.length === 9
) {
style[property] = hexToRgba(value);
} else if (typeof value === 'object' && !Array.isArray(value)) {
hexToRgbaPlugin(value);
}
}
return style;
}