53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
// * Packages
|
|
import { CSSProperties } from "react";
|
|
|
|
/**
|
|
* Convert CSS string into React style object.
|
|
*
|
|
* @param styleString string|null|undefined
|
|
* @return CSSProperties
|
|
*/
|
|
export function parseStyleString(
|
|
styleString: string | null | undefined,
|
|
): CSSProperties {
|
|
if (!styleString) return {};
|
|
|
|
const style = {} as Record<string, string>;
|
|
|
|
styleString.split(";").forEach((rule) => {
|
|
const [property, value] = rule.split(":").map((s) => s.trim());
|
|
if (property && value) {
|
|
// Conversion kebab-case → camelCase.
|
|
const camelProperty = property.replace(/-([a-z])/g, (g) =>
|
|
g[1].toUpperCase(),
|
|
);
|
|
style[camelProperty] = value;
|
|
}
|
|
});
|
|
|
|
return style as CSSProperties;
|
|
}
|
|
|
|
/**
|
|
* Convert React style object to CSS string.
|
|
*
|
|
* @param style CSSProperties|null|undefined
|
|
* @return string
|
|
*/
|
|
export function serializeStyleObject(
|
|
style: CSSProperties | null | undefined,
|
|
): string {
|
|
if (!style || typeof style !== "object") return "";
|
|
|
|
const rules: string[] = [];
|
|
|
|
Object.entries(style).forEach(([property, value]) => {
|
|
if (value !== undefined && value !== null) {
|
|
// Conversion camelCase → kebab-case.
|
|
const kebabProperty = property.replace(/([A-Z])/g, "-$1").toLowerCase();
|
|
rules.push(`${kebabProperty}:${String(value)}`);
|
|
}
|
|
});
|
|
|
|
return rules.join(";");
|
|
}
|