@acusti/css-values
Version:
Utilities for parsing different types of CSS values with or without their units
56 lines (55 loc) • 2.05 kB
JavaScript
const CSS_UNIT_REGEX = Object.freeze({
// https://developer.mozilla.org/en-US/docs/Web/CSS/angle
angle: /(deg|grad|rad|turn)\s*$/i,
// https://developer.mozilla.org/en-US/docs/Web/CSS/integer
integer: /$/i,
// https://developer.mozilla.org/en-US/docs/Web/CSS/length with addition of %
length: /(em|rem|ch|ex|vh|vw|vmin|vmax|px|cm|mm|in|pc|pt|%)\s*$/i,
// custom (non-spec-defined) value type that only allows percentages
percent: /(%)\s*$/,
// https://developer.mozilla.org/en-US/docs/Web/CSS/time
time: /(s|ms)\s*$/i
});
const DEFAULT_CSS_VALUE_TYPE = "length";
const DEFAULT_UNIT_BY_CSS_VALUE_TYPE = Object.freeze({
angle: "deg",
integer: "",
length: "px",
percent: "%",
time: "s"
});
const roundToPrecision = (value, precision) => parseFloat(value.toFixed(precision));
const getUnitFromCSSValue = ({
cssValueType,
defaultUnit = DEFAULT_UNIT_BY_CSS_VALUE_TYPE[cssValueType],
value
}) => {
if (typeof value === "number") return defaultUnit;
const matchedUnit = CSS_UNIT_REGEX[cssValueType].exec(value);
return matchedUnit === null || !matchedUnit[1] ? defaultUnit : matchedUnit[1];
};
const getCSSValueAsNumber = (value) => typeof value === "number" ? value : parseFloat(value);
const getCSSValueWithUnit = (payload) => {
const valueAsNumber = getCSSValueAsNumber(payload.value);
if (Number.isNaN(valueAsNumber)) return payload.value.toString().trim();
return `${valueAsNumber}${getUnitFromCSSValue(payload)}`;
};
const getMillisecondsFromCSSValue = (value) => {
if (!value) return 0;
if (typeof value === "number") return value;
if (!CSS_UNIT_REGEX.time.test(value)) return 0;
const valueAsNumber = getCSSValueAsNumber(value);
if (Number.isNaN(valueAsNumber)) return 0;
const multiplier = /[^m]s/i.test(value) ? 1e3 : 1;
return valueAsNumber * multiplier;
};
export {
DEFAULT_CSS_VALUE_TYPE,
DEFAULT_UNIT_BY_CSS_VALUE_TYPE,
getCSSValueAsNumber,
getCSSValueWithUnit,
getMillisecondsFromCSSValue,
getUnitFromCSSValue,
roundToPrecision
};
//# sourceMappingURL=index.js.map