UNPKG

2.28 kBJavaScriptView Raw
1/**
2 * Based on https://github.com/jsstyles/css-vendor, but without having to
3 * convert between different cases all the time.
4 *
5 * @flow
6 */
7
8import InlineStylePrefixer from 'inline-style-prefixer';
9
10function transformValues(style) {
11 return Object.keys(style).reduce(
12 (newStyle, key) => {
13 let value = style[key];
14 if (Array.isArray(value)) {
15 value = value.join(';' + key + ':');
16 } else if (
17 value &&
18 typeof value === 'object' &&
19 typeof value.toString === 'function'
20 ) {
21 value = value.toString();
22 }
23
24 newStyle[key] = value;
25 return newStyle;
26 },
27 {},
28 );
29}
30
31let _hasWarnedAboutUserAgent = false;
32let _lastUserAgent;
33let _cachedPrefixer;
34
35function getPrefixer(
36 userAgent: ?string,
37): {
38 +prefix: (style: Object) => Object,
39 prefixedKeyframes: string,
40} {
41 const actualUserAgent = userAgent ||
42 (global && global.navigator && global.navigator.userAgent);
43
44 if (process.env.NODE_ENV !== 'production') {
45 if (!actualUserAgent && !_hasWarnedAboutUserAgent) {
46 /* eslint-disable no-console */
47 console.warn(
48 'Radium: userAgent should be supplied for server-side rendering. See ' +
49 'https://github.com/FormidableLabs/radium/tree/master/docs/api#radium ' +
50 'for more information.',
51 );
52 /* eslint-enable no-console */
53 _hasWarnedAboutUserAgent = true;
54 }
55 }
56
57 if (!_cachedPrefixer || actualUserAgent !== _lastUserAgent) {
58 if (actualUserAgent === 'all') {
59 _cachedPrefixer = {
60 prefix: InlineStylePrefixer.prefixAll,
61 prefixedKeyframes: 'keyframes',
62 };
63 } else {
64 _cachedPrefixer = new InlineStylePrefixer({userAgent: actualUserAgent});
65 }
66 _lastUserAgent = actualUserAgent;
67 }
68 return _cachedPrefixer;
69}
70
71export function getPrefixedKeyframes(userAgent?: ?string): string {
72 return getPrefixer(userAgent).prefixedKeyframes;
73}
74
75// Returns a new style object with vendor prefixes added to property names
76// and values.
77export function getPrefixedStyle(style: Object, userAgent?: ?string): Object {
78 const styleWithFallbacks = transformValues(style);
79 const prefixer = getPrefixer(userAgent);
80 const prefixedStyle = prefixer.prefix(styleWithFallbacks);
81 return prefixedStyle;
82}