Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/__tests__/native/units.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,28 @@ test("rem - inline override", () => {
});
});

test("rem - css root font-size override", () => {
registerCSS(`
:root { font-size: 16px; }
.my-class { font-size: 10rem; }
`);

const { result } = renderHook(() => {
return useNativeCss(View, { className: "my-class" });
});

expect(result.current.type).toBe(VariableContext.Provider);
expect(result.current.props.value).toStrictEqual({
[VAR_SYMBOL]: true,
[emVariableName]: 160,
});

expect(result.current.props.children.type).toBe(View);
expect(result.current.props.children.props).toStrictEqual({
style: { fontSize: 160 },
});
});

test("rem - css override", () => {
registerCSS(
`
Expand Down
17 changes: 14 additions & 3 deletions src/compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,28 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) {

const vars = new Map<string, UniqueVarInfo>();

// Determine the effective rem multiplier for compile-time inlining.
// If inlineRem is explicitly set, use that. Otherwise, scan for
// :root { font-size: Npx } in the CSS to allow CSS-based configuration.
let effectiveRem: number | false = options.inlineRem ?? undefined!;
if (effectiveRem === undefined) {
const css = typeof code === "string" ? code : code.toString();
const match = css.match(/:root\s*\{[^}]*font-size:\s*([\d.]+)px/);
effectiveRem = match?.[1] ? parseFloat(match[1]) : 14;
}

const firstPassVisitor: Visitor<CustomAtRules> = {};

if (options.inlineRem !== false) {
if (effectiveRem !== false) {
const remMultiplier = effectiveRem;
firstPassVisitor.Length = (length) => {
if (length.unit !== "rem" || options.inlineRem === false) {
if (length.unit !== "rem") {
return length;
}

return {
unit: "px",
value: round(length.value * (options.inlineRem ?? 14)),
value: round(length.value * remMultiplier),
};
};
}
Expand Down
Loading