UNPKG

style-to-js

Version:

Parses CSS inline style to JavaScript object (camelCased).

46 lines (45 loc) 1.52 kB
import StyleToObject from "style-to-object"; //#region src/utilities.ts const CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/; const HYPHEN_REGEX = /-([a-z])/g; const NO_HYPHEN_REGEX = /^[^-]+$/; const VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/; const MS_VENDOR_PREFIX_REGEX = /^-(ms)-/; /** * Checks whether to skip camelCase. */ const skipCamelCase = (property) => !property || NO_HYPHEN_REGEX.test(property) || CUSTOM_PROPERTY_REGEX.test(property); /** * Replacer that capitalizes first character. */ const capitalize = (match, character) => character.toUpperCase(); /** * Replacer that removes beginning hyphen of vendor prefix property. */ const trimHyphen = (match, prefix) => `${prefix}-`; /** * CamelCases a CSS property. */ const camelCase = (property, options = {}) => { if (skipCamelCase(property)) return property; property = property.toLowerCase(); if (options.reactCompat) property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen); else property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen); return property.replace(HYPHEN_REGEX, capitalize); }; //#endregion //#region src/index.ts /** * Parses CSS inline style to JavaScript object (camelCased). */ function StyleToJS(style, options) { const output = {}; if (!style || typeof style !== "string") return output; StyleToObject(style, (property, value) => { if (property && value) output[camelCase(property, options)] = value; }); return output; } //#endregion export { StyleToJS as default }; //# sourceMappingURL=index.mjs.map