2026-04-05 18:31:16 -07:00
|
|
|
import { CSSProperties } from 'react';
|
2026-07-12 12:06:16 -07:00
|
|
|
import { escapeAttr, safeUrl } from './escape';
|
2026-04-05 18:31:16 -07:00
|
|
|
|
|
|
|
|
const camelToKebab = (str: string): string =>
|
|
|
|
|
str.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase());
|
|
|
|
|
|
2026-07-12 12:06:16 -07:00
|
|
|
const URL_RE = /url\(\s*(['"]?)([\s\S]*?)\1\s*\)/gi;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sanitizes a single CSS declaration value so it can never terminate the
|
|
|
|
|
* `style="..."` attribute early, inject an extra declaration via a stray
|
|
|
|
|
* `;`, or smuggle a `javascript:`/`vbscript:`/`data:text/html` URL through
|
|
|
|
|
* a `url(...)` reference. Legitimate multi-part values (box-shadow,
|
|
|
|
|
* gradients, etc.) that contain none of these characters pass through
|
|
|
|
|
* unchanged.
|
|
|
|
|
*/
|
|
|
|
|
function sanitizeCssValue(raw: string): string {
|
|
|
|
|
// Neutralize url(...) references: validate/strip the scheme and re-wrap
|
|
|
|
|
// in single quotes with the contents escaped for attribute safety.
|
|
|
|
|
let val = raw.replace(URL_RE, (_m, _q, inner) => `url('${escapeAttr(safeUrl(inner.trim()))}')`);
|
|
|
|
|
// A `;` in a CSS value is never legitimate (declarations are separated by
|
|
|
|
|
// it) -- stray semicolons are how a breakout injects a second property.
|
|
|
|
|
val = val.replace(/;/g, '');
|
|
|
|
|
// Any remaining raw `"` would close the `style="..."` attribute early.
|
|
|
|
|
val = val.replace(/"/g, '"');
|
|
|
|
|
return val;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 18:31:16 -07:00
|
|
|
export function cssPropsToString(style: CSSProperties | undefined): string {
|
|
|
|
|
if (!style) return '';
|
|
|
|
|
return Object.entries(style)
|
|
|
|
|
.filter(([, v]) => v !== undefined && v !== null && v !== '')
|
2026-07-12 12:06:16 -07:00
|
|
|
.map(([k, v]) => `${camelToKebab(k)}:${typeof v === 'string' ? sanitizeCssValue(v) : v}`)
|
2026-04-05 18:31:16 -07:00
|
|
|
.join(';');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function mergeStyles(...styles: (CSSProperties | undefined)[]): CSSProperties {
|
|
|
|
|
return Object.assign({}, ...styles.filter(Boolean));
|
|
|
|
|
}
|