UNPKG

style-to-css

Version:
95 lines (83 loc) 2.64 kB
import toSlugCase from 'to-slug-case'; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ // https://raw.githubusercontent.com/facebook/react/3b96650e39ddda5ba49245713ef16dbc52d25e9e/src/renderers/dom/shared/CSSProperty.js /** * CSS properties which accept numbers but are not in units of "px". */ const isUnitlessNumber = { animationIterationCount: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, stopOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ const prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); const isTouch = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch; const important = isTouch ? '' : '!important'; function toCSS(obj) { return Object.keys(obj).map(rawKey => { let key = toSlugCase(rawKey); if (/^webkit/.test(key) || /^moz/.test(key) || /^ms/.test(key)) { key = `-${ key }`; } let value = obj[rawKey]; if (typeof value === 'number' && !(isUnitlessNumber.hasOwnProperty(key) && isUnitlessNumber[key])) { value = `${ value }px`; } return `${ key }:${ value } ${ important };`; }).join(''); } export default toCSS;