style-to-object
Version:
Parse CSS inline style to JavaScript object.
1 lines • 1.77 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type { Declaration } from 'inline-style-parser';\nimport parse from 'inline-style-parser';\n\nexport { Declaration };\n\nexport type StyleObject = Record<string, string>;\n\ntype Iterator = (\n property: string,\n value: string,\n declaration: Declaration,\n) => void;\n\n/**\n * Parses inline style to object.\n *\n * @param style - Inline style.\n * @param iterator - Iterator.\n * @returns - Style object or null.\n *\n * @example Parsing inline style to object:\n *\n * ```js\n * import parse from 'style-to-object';\n * parse('line-height: 42;'); // { 'line-height': '42' }\n * ```\n */\nexport default function StyleToObject(\n style: string,\n iterator?: Iterator,\n): StyleObject | null {\n let styleObject: StyleObject | null = null;\n\n if (!style || typeof style !== 'string') {\n return styleObject;\n }\n\n const declarations = parse(style);\n const hasIterator = typeof iterator === 'function';\n\n declarations.forEach((declaration) => {\n if (declaration.type !== 'declaration') {\n return;\n }\n\n const { property, value } = declaration;\n\n if (hasIterator) {\n iterator(property, value, declaration);\n } else if (value) {\n styleObject = styleObject ?? {};\n styleObject[property] = value;\n }\n });\n\n return styleObject;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,SAAwB,cACtB,OACA,UACoB;CACpB,IAAI,cAAkC;CAEtC,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAGT,MAAM,eAAe,MAAM,KAAK;CAChC,MAAM,cAAc,OAAO,aAAa;CAExC,aAAa,SAAS,gBAAgB;EACpC,IAAI,YAAY,SAAS,eACvB;EAGF,MAAM,EAAE,UAAU,UAAU;EAE5B,IAAI,aACF,SAAS,UAAU,OAAO,WAAW;OAChC,IAAI,OAAO;GAChB,cAAc,eAAe,CAAC;GAC9B,YAAY,YAAY;EAC1B;CACF,CAAC;CAED,OAAO;AACT"}