UNPKG

choerodon-ui

Version:

An enterprise-class UI design language and React-based implementation

131 lines (109 loc) 3.86 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import isNumber from 'lodash/isNumber'; import isString from 'lodash/isString'; import isNil from 'lodash/isNil'; import cssUnitConverter from 'css-unit-converter'; export function pxToRem(num) { if (num !== undefined && num !== null) { if (num === 0) { return '0'; } if (isNumber(num)) { return "".concat(num / 100, "rem"); } return num; } } var builtInHeight = ['auto', 'fit-content', 'max-content', 'min-content', 'inherit', 'initial', 'unset', 'revert', 'available', '-webkit-fit-content', '-moz-max-content', '-moz-min-content', '-moz-initial']; var calcReg = /^calc\(([^()]*)\)$/; var unitReg = /^([+-]?[\d]+(?:[.][\d]+)?(?:[Ee][+-]?[\d]+)?)([^\d.+-]+)$/; function defaultTo(value, callback) { if (isNil(value)) { return callback(); } return value; } export function isCalcSize(num) { return num.match(calcReg); } export function isPercentSize(num) { return num.indexOf('%') !== -1; } export function toPx(num, getRelationSize) { if (num !== undefined && num !== null) { if (isNumber(num)) { return num; } if (isString(num) && !builtInHeight.includes(num)) { var calcMatches = isCalcSize(num); if (calcMatches) { try { var list = calcMatches[1].split(' '); return list.slice(1).reduce(function (result, calc, index, array) { if (index % 2 === 1) { /* eslint-disable-next-line no-eval */ return eval("".concat(result).concat(array[index - 1]).concat(toPx(calc, getRelationSize))); } return result; }, toPx(list[0], getRelationSize)); } catch (e) { console.error("Invalid property value in \"".concat(num, "\".")); return undefined; } } var unitMatches = num.match(unitReg); if (unitMatches) { var _unitMatches = _slicedToArray(unitMatches, 3), n = _unitMatches[1], u = _unitMatches[2]; if (n) { var number = Number(n); if (u && u !== 'px') { switch (u) { case '%': { var parentPx = getRelationSize && getRelationSize('%'); if (parentPx !== undefined) { return parentPx * number / 100; } return undefined; } case 'vh': { var viewHeight = defaultTo(getRelationSize && getRelationSize('vh'), function () { return document.documentElement.clientHeight; }); return viewHeight * number / 100; } case 'vw': { var viewWidth = defaultTo(getRelationSize && getRelationSize('vw'), function () { return document.documentElement.clientWidth; }); return viewWidth * number / 100; } case 'rem': return number * defaultTo(toPx(window.getComputedStyle(document.documentElement).fontSize), function () { return 100; }); case 'em': return number * defaultTo(getRelationSize && getRelationSize('em'), function () { return defaultTo(toPx(window.getComputedStyle(document.body).fontSize), function () { return 12; }); }); default: try { return cssUnitConverter(number, u, 'px'); } catch (e) { return undefined; } } } return number; } } } } } //# sourceMappingURL=UnitConvertor.js.map