summaryrefslogtreecommitdiff
path: root/packages/integrations/markdoc/src/html/css/parse-inline-css-to-react.ts
blob: c35376641fa4839d5504527e4ca76dc8d9c17953 (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
24
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-z\d])/gi, (_match, char) => {
		return char.toUpperCase();
	});
	return replaced;
}