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
133 changes: 133 additions & 0 deletions src/__tests__/compiler/visitor-returns.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,136 @@ test("the first pass hands back only the lengths it converts", () => {
{ unit: "px", value: 28 },
]);
});

function containsNull(value: unknown): boolean {
if (value === null) return true;
if (Array.isArray(value)) return value.some(containsNull);
if (value && typeof value === "object") {
return Object.values(value).some(containsNull);
}
return false;
}

function containsUnsafeF32Node(value: unknown): boolean {
if (Array.isArray(value)) return value.some(containsUnsafeF32Node);
if (!value || typeof value !== "object") return false;

const record = value as Record<string, unknown>;
const type = record.type;
if (
type === "length" ||
type === "angle" ||
type === "time" ||
type === "resolution"
) {
const inner = record.value as { value?: unknown } | undefined;
if (
typeof inner?.value === "number" &&
((Number.isInteger(inner.value) &&
(inner.value < -32768 || inner.value > 65535)) ||
!Number.isFinite(inner.value))
) {
return true;
}
}

return Object.values(record).some(containsUnsafeF32Node);
}

test("the first pass never hands a StyleSheet back, with or without variable inlining", () => {
const css = `
:root { --a: 10px; }
.a { width: var(--a); border-style: var(--tw-border-style); border-radius: calc(infinity * 1px); }
`;

compile(css);
compile(css, { inlineVariables: false });

const sheetCalls = calls.filter(
(call) =>
call.pass === 1 &&
(call.visitor === "StyleSheet" || call.visitor === "StyleSheetExit"),
);

expect(sheetCalls.length).toBeGreaterThan(0);
expect(sheetCalls.filter((call) => call.returned !== undefined)).toEqual([]);
});

test("the first pass hands nothing back for untouched declarations", () => {
compile(`
@layer { .border { border-style: var(--tw-border-style); } }
.rounded-full { border-radius: calc(infinity * 1px); width: 99999px; }
`);

const firstPassReturned = calls.filter(
(call) => call.pass === 1 && call.returned !== undefined,
);

expect(firstPassReturned).toEqual([]);
});

test("declarations returned by the first pass contain no null Option fields", () => {
compile(`
:root { --a: 10px; --b: var(--missing); }
.mixed {
margin: var(--a) var(--unknown);
padding: var(--a) env(safe-area-inset-top);
border-width: var(--unknown, var(--a));
top: var(--b);
}
`);

const returnedDecls = calls
.filter(
(call) =>
call.pass === 1 &&
call.visitor === "Declaration" &&
call.returned !== undefined,
)
.map((call) => call.returned);

expect(returnedDecls.length).toBeGreaterThan(0);
expect(returnedDecls.some(containsNull)).toBe(false);
});

test("declarations returned by the first pass rewrite out-of-range integer dimensions as raw dimension tokens", () => {
const sheet = compile(`
:root { --big: 99999px; --neg: -99999px; --rem-big: 70000rem; }
.vars { border-radius: var(--big); margin-left: var(--neg); width: var(--rem-big); }
.transforms { translate: 99999px 0px; rotate: 0 0 1 99999deg; }
`).stylesheet();

const returnedDecls = calls
.filter(
(call) =>
call.pass === 1 &&
call.visitor === "Declaration" &&
call.returned !== undefined,
)
.map((call) => call.returned);

expect(returnedDecls.length).toBeGreaterThan(0);
expect(returnedDecls.some(containsUnsafeF32Node)).toBe(false);

const varsRule = sheet.s?.find(([name]) => name === "vars")?.[1]?.[0];
expect(varsRule?.d).toContainEqual({
borderRadius: 99999,
marginLeft: -99999,
width: 980000,
});
});

test("same-block variable folding stays scoped to its keyframe block", () => {
const sheet = compile(`
@keyframes grow {
from { --x: 10px; width: var(--x); }
to { height: var(--x); }
}
`).stylesheet();

const fromDecls = sheet.k?.[0]?.[1]?.find(([key]) => key === "from")?.[1];
const toDecls = sheet.k?.[0]?.[1]?.find(([key]) => key === "to")?.[1];

expect(fromDecls).toContainEqual(expect.objectContaining({ width: 10 }));
expect(toDecls).toContainEqual([[{}, "var", "x", 1], "height"]);
});
102 changes: 90 additions & 12 deletions src/compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ import {
round,
} from "./declarations";
import { unparseIndividualTransform } from "./individual-transforms";
import { inlineVariables } from "./inline-variables";
import {
blockLocalVarNames,
declarationCount,
foldDeclaration,
planVariableInlining,
type VariableInliningPlan,
} from "./inline-variables";
import { extractKeyFrames } from "./keyframes";
import { lightningcssLoader } from "./lightningcss-loader";
import { parseMediaQuery } from "./media-query";
Expand Down Expand Up @@ -121,23 +127,30 @@ export function compile(

const inlining = options.inlineVariables;

let inliningPlan: VariableInliningPlan | undefined;
let currentLocals: ReadonlySet<string> | undefined;
let remainingInBlock = 0;
let keyframeQueue:
| { locals: ReadonlySet<string> | undefined; remaining: number }[]
| undefined;
let keyframeIndex = 0;

const firstPassVisitor: Visitor<CustomAtRules> = {
// Registered from the first pass, since lightningcss prints only the last @property of a name, valid or not
StyleSheetExit(sheet) {
// Registered from the first pass, since lightningcss prints only the last @property of a name, valid or not.
// Returns nothing so lightningcss never deserializes untouched rules back across the visitor boundary.
StyleSheet(sheet) {
const nonInheriting = registerProperties(
collectRegistrations(sheet.rules),
builder,
);

if (inlining === false) {
return sheet;
if (inlining !== false) {
inliningPlan = planVariableInlining(
sheet,
inlining?.exclude ?? [],
nonInheriting,
);
}

return inlineVariables(
sheet,
inlining?.exclude ?? [],
nonInheriting,
);
},
Rule(rule) {
if (
Expand Down Expand Up @@ -168,6 +181,41 @@ export function compile(
"Class-qualified :root selectors are unsupported on native. Use @media (prefers-color-scheme: dark) for dark mode, and React Native Appearance.setColorScheme() for manual selection.",
);
}

if (!inliningPlan) return;

if (rule.type === "style" || rule.type === "nested-declarations") {
keyframeQueue = undefined;
const count = declarationCount(rule.value.declarations);
currentLocals =
count > 0
? blockLocalVarNames(rule.value.declarations, inliningPlan)
: undefined;
remainingInBlock = currentLocals ? count : 0;
} else if (rule.type === "keyframes") {
currentLocals = undefined;
remainingInBlock = 0;
keyframeQueue = undefined;
let anyLocals = false;
const queue: {
locals: ReadonlySet<string> | undefined;
remaining: number;
}[] = [];
for (const keyframe of rule.value.keyframes) {
const count = declarationCount(keyframe.declarations);
if (count === 0) continue;
const locals = blockLocalVarNames(
keyframe.declarations,
inliningPlan,
);
if (locals) anyLocals = true;
queue.push({ locals, remaining: count });
}
if (anyLocals) {
keyframeQueue = queue;
keyframeIndex = 0;
}
}
},
};

Expand All @@ -186,7 +234,37 @@ export function compile(
}

firstPassVisitor.Declaration = (decl) => {
return unparseIndividualTransform(decl);
let locals: ReadonlySet<string> | undefined;
if (keyframeQueue !== undefined) {
const entry = keyframeQueue[keyframeIndex];
if (entry) {
locals = entry.locals;
entry.remaining--;
if (entry.remaining === 0) {
keyframeIndex++;
if (keyframeIndex >= keyframeQueue.length) {
keyframeQueue = undefined;
}
}
}
} else if (remainingInBlock > 0) {
locals = currentLocals;
remainingInBlock--;
if (remainingInBlock === 0) {
currentLocals = undefined;
}
}

const unparsed = unparseIndividualTransform(decl);
if (unparsed) {
return unparsed;
}

if (inliningPlan) {
return foldDeclaration(decl, inliningPlan, locals);
}

return undefined;
};

const { code: firstPass, warnings: firstPassWarnings } = lightningcss({
Expand Down
38 changes: 35 additions & 3 deletions src/compiler/individual-transforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,35 @@ function numberOrPercentageToken(value: NumberOrPercentage): TokenOrValue {
: percentageToken(value.value);
}

// lightningcss >= 1.30.2 fails to deserialize integers outside i16/u16 bounds into f32 enum variants (parcel-bundler/lightningcss#1188).
// Emitting a raw dimension token avoids the buffered f32 deserializer while printing identically.
export function needsDimensionToken(value: number): boolean {
return (
(Number.isInteger(value) && (value < -32768 || value > 65535)) ||
!Number.isFinite(value)
);
}

// No token holds a calc(), which React Native cannot take anyway: the compiler warns for one and ignores the declaration
function lengthToken(
value: Length | DimensionPercentageFor_LengthValue,
): TokenOrValue | undefined {
switch (value.type) {
case "value":
case "dimension":
return { type: "length", value: value.value };
case "dimension": {
const length = value.value;
if (needsDimensionToken(length.value)) {
return {
type: "token",
value: {
type: "dimension",
value: length.value,
unit: length.unit,
},
};
}
return { type: "length", value: length };
}
case "percentage":
return percentageToken(value.value);
case "calc":
Expand All @@ -110,11 +131,22 @@ function translateTokens(value: Translate): TokenOrValue[] | undefined {
}

function rotateTokens(value: Rotate): TokenOrValue[] {
const angleToken: TokenOrValue = needsDimensionToken(value.angle.value)
? {
type: "token",
value: {
type: "dimension",
value: value.angle.value,
unit: value.angle.type,
},
}
: { type: "angle", value: value.angle };

return spaceSeparated([
numberToken(value.x),
numberToken(value.y),
numberToken(value.z),
{ type: "angle", value: value.angle },
angleToken,
]);
}

Expand Down
Loading
Loading