summaryrefslogtreecommitdiff
path: root/packages/integrations/markdoc/src/html/css/parse-inline-css-to-react.ts
blob: 3b67f9a3250c2558e1872389411775646efe877a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

import { styleToObject } from "./style-to-object.js";

export function parseInlineCSSToReactLikeObject(css: string | undefined | null): React.CSSProperties | undefined {
  if (typeof css === "string") {
    const cssObject: Record<string, string> = {};
    styleToObject(css, (originalCssDirective: string, value: string) => {
      const reactCssDirective = convertCssDirectiveNameToReactCamelCase(originalCssDirective);
      cssObject[reactCssDirective] = value;
    });
    return cssObject;
  }

  return undefined;
}

function convertCssDirectiveNameToReactCamelCase(original: string): string {
  // capture group 1 is the character to capitalize, the hyphen is omitted by virtue of being outside the capture group
  const replaced = original.replace(/-([a-z0-9])/ig, (_match, char) => {
    return char.toUpperCase();
  });
  return replaced;
}