From 5ad6875ab7a45f6f2ff0bc53254c0c8d32bea6f0 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 21:03:43 +0300 Subject: [PATCH 01/17] fix(transforms): give every transform entry one property React Native's transform validator requires exactly one property per entry and throws otherwise. A resolver returns a group for a two-operand scale() or translate(), the compiler emits one for translate(10px), and an unsupported function such as scale3d() leaves an empty one, so each reached React Native as a nested array. The transform shorthand now spreads a group into the list, which also drops the empty one and keeps its neighbours. --- src/__tests__/native/transform.test.tsx | 60 +++++++++++++++++++++++ src/native/styles/shorthands/transform.ts | 9 ++-- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 7a59b816..a9b0c70b 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -154,3 +154,63 @@ describe("transform", () => { }); }); }); + +function renderStyle(css: string): unknown { + registerCSS(css); + + return render( + , + ).getByTestId(testID).props.style; +} + +// A second definition keeps each variable from being inlined, so it resolves at runtime +const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; }`; + +// React Native requires exactly one property per transform object, and its validator throws otherwise +describe("one property per entry", () => { + // Chromium 153, Firefox 155 and WebKit 26.6 scale each axis by its own operand + test.each([ + ["75%", "50%", [{ scaleX: 0.75 }, { scaleY: 0.5 }]], + ["2", "3", [{ scaleX: 2 }, { scaleY: 3 }]], + ])( + "transform: scale(var(--sx), var(--sy)) with %s and %s renders an entry per axis", + (sx, sy, transform) => { + expect( + renderStyle( + `${decoy} .my-class { --sx: ${sx}; --sy: ${sy}; transform: scale(var(--sx), var(--sy)); }`, + ), + ).toStrictEqual({ transform }); + }, + ); + + test("a two-operand translate() renders an entry per axis, beside a sibling", () => { + expect( + renderStyle( + `${decoy} .my-class { --t: 10px; transform: translate(var(--t), var(--t)) rotate(45deg); }`, + ), + ).toStrictEqual({ + transform: [{ translateX: 10 }, { translateY: 10 }, { rotate: "45deg" }], + }); + }); + + test.each([ + "transform: scale3d(1, 2, 3);", + "transform: scaleZ(2);", + "transform: matrix(1, 0, 0, 1, 0, 0);", + ])( + "%s, which React Native has no form for, renders no entry", + (declaration) => { + expect(renderStyle(`.my-class { ${declaration} }`)).toStrictEqual({ + transform: [], + }); + }, + ); + + test("a function React Native has no form for leaves its neighbour", () => { + expect( + renderStyle( + `.my-class { transform: translateX(10px) scale3d(1, 2, 3); }`, + ), + ).toStrictEqual({ transform: [{ translateX: 10 }] }); + }); +}); diff --git a/src/native/styles/shorthands/transform.ts b/src/native/styles/shorthands/transform.ts index ef603dd8..49a32369 100644 --- a/src/native/styles/shorthands/transform.ts +++ b/src/native/styles/shorthands/transform.ts @@ -11,9 +11,12 @@ export const transform: StyleFunctionResolver = ( const transforms = resolveValue(transformDescriptor[2]); if (Array.isArray(transforms)) { - return transforms.filter( - (transform) => transform !== undefined && transform !== "initial", - ) as unknown; + // React Native takes one property per transform object, so a resolver's group of entries is spread into the list + return transforms + .flat() + .filter( + (transform) => transform !== undefined && transform !== "initial", + ) as unknown; } else if (transforms) { // If it's a single transform, wrap it in an array return [transforms]; From 81af42bac0e66acc66255dbfebadccb00a18ca3a Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 21:04:11 +0300 Subject: [PATCH 02/17] fix(transforms): a transform value React Native cannot take leaves none MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A transform function or longhand whose var() leaves it no valid value reached React Native as an entry it rejects: `scaleX(var(--missing))` and `rotate: var(--missing)` as an undefined value, `scale(var(--s))` with `--s: none` as the string "none", and `scale: initial`, `translate: initial` or a longhand with two missing operands as the placeholder `true`. Each throws in the transform validator. Browsers treat each declaration as invalid at computed-value time (css-variables-1 §3.1): a function without a valid argument leaves no transform, and a longhand without a value is none. A resolver now returns null for an operand it cannot use, the transform shorthand turns that into an empty list, and a longhand that resolves to nothing removes its entries. A scale factor is a number or nothing, and a one-operand translate() translates along x, as translate(x) is translate(x, 0). --- src/__tests__/native/transform.test.tsx | 59 ++++++++++++++++ src/native/objects.ts | 44 +++++++----- .../styles/functions/transform-functions.ts | 70 ++++++++----------- src/native/styles/resolve.ts | 18 ++--- src/native/styles/scale-factor.ts | 13 ++-- src/native/styles/shorthands/transform.ts | 13 ++-- 6 files changed, 140 insertions(+), 77 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index a9b0c70b..21ad6eb2 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -183,6 +183,31 @@ describe("one property per entry", () => { }, ); + test("transform: scale(var(--sx)) scales both axes by its one operand", () => { + expect( + renderStyle( + `${decoy} .my-class { --sx: 75%; transform: scale(var(--sx)); }`, + ), + ).toStrictEqual({ transform: [{ scale: 0.75 }] }); + }); + + test("scale: var(--sx) scales both axes by its one value", () => { + expect( + renderStyle(`${decoy} .my-class { --sx: 75%; scale: var(--sx); }`), + ).toStrictEqual({ transform: [{ scale: 0.75 }] }); + }); + + // Chromium 153, Firefox 155 and WebKit 26.6 translate a one-operand translate() along x only + test.each([ + "transform: translate(10px);", + "--t: 10px; transform: translate(var(--t));", + "--t: 10px; translate: var(--t);", + ])("%s translates along x only", (declarations) => { + expect(renderStyle(`${decoy} .my-class { ${declarations} }`)).toStrictEqual( + { transform: [{ translateX: 10 }, { translateY: 0 }] }, + ); + }); + test("a two-operand translate() renders an entry per axis, beside a sibling", () => { expect( renderStyle( @@ -214,3 +239,37 @@ describe("one property per entry", () => { ).toStrictEqual({ transform: [{ translateX: 10 }] }); }); }); + +// Chromium 153, Firefox 155 and WebKit 26.6: a function left without a valid argument makes the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) +test.each([ + "transform: scaleX(var(--missing));", + "transform: translateX(10px) scaleX(var(--missing));", + "transform: translate(10px, var(--missing));", + "transform: rotate(var(--missing));", + "--sx: none; transform: scaleX(var(--sx));", + "--sx: none; transform: scale(var(--sx));", +])("%s leaves no transform", (declarations) => { + expect( + renderStyle( + `${decoy} .earlier { transform: rotate(10deg); } .my-class { ${declarations} }`, + ), + ).toStrictEqual({ transform: [] }); +}); + +// Chromium 153, Firefox 155 and WebKit 26.6: a scale or translate longhand left without a value is none, and the transform property beside it stands +test.each([ + "scale: var(--missing);", + "scale: var(--missing) var(--missing);", + "translate: var(--missing) var(--missing);", + "--sx: none; scale: var(--sx);", + "--sx: none; --sy: 2; scale: var(--sx) var(--sy);", + "scale: unset;", + "scale: initial;", + "translate: initial;", +])("%s leaves the transform property's entries", (declarations) => { + expect( + renderStyle( + `${decoy} .earlier { transform: rotate(10deg); } .my-class { ${declarations} }`, + ), + ).toStrictEqual({ transform: [{ rotate: "10deg" }] }); +}); diff --git a/src/native/objects.ts b/src/native/objects.ts index 433bf774..a45a313b 100644 --- a/src/native/objects.ts +++ b/src/native/objects.ts @@ -55,6 +55,11 @@ export function applyValue( prop: string, value: any, ) { + if (transformKeys.has(prop)) { + applyTransformValue(target, prop, value); + return; + } + // This is confusing. // An undefined value means "don't set anything" (something failed while parsing) // While a null value means "remove this value", which in React Native means "set to undefined" @@ -64,23 +69,7 @@ export function applyValue( value = undefined; } - if (transformKeys.has(prop)) { - if (!Array.isArray(target.transform)) { - target.transform = []; - } - - const transformArray: Record[] = target.transform; - - // Remove any existing values - target.transform = transformArray.filter((t) => !(prop in t)); - - if (Array.isArray(value)) { - target.transform.push(...value); - } else { - target.transform.push(value); - } - return; - } else if (typeof value === "object" && value) { + if (typeof value === "object" && value) { if (ShortHandSymbol in value) { delete value[ShortHandSymbol]; Object.assign(target, value); @@ -98,6 +87,27 @@ export function applyValue( target[prop] = value; } +// A transform longhand that resolves to no value is `none`, so its entries go and nothing takes their place +function applyTransformValue( + target: Record, + prop: string, + value: unknown, +) { + const transforms: Record[] = Array.isArray(target.transform) + ? target.transform + : []; + + target.transform = transforms.filter((transform) => !(prop in transform)); + + if (value === undefined || value === null) { + return; + } else if (Array.isArray(value)) { + target.transform.push(...value); + } else { + target.transform.push(value); + } +} + export function setDeepPath( target: Record, paths: string | string[] | readonly string[], diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 851f469f..32a52f52 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -4,44 +4,35 @@ import { isStyleDescriptorArray } from "react-native-css/utilities"; import type { SimpleResolveValue, StyleFunctionResolver } from "../resolve"; import { scaleFactor } from "../scale-factor"; +// A component left without a valid value makes the declaration invalid at computed-value time (css-variables-1 §3.1), which null carries export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { - const args = descriptor[2]; - - if (!isStyleDescriptorArray(args)) { - return { scale: scaleFactor(resolveValue(args)) }; - } - - const x = scaleFactor(argument(resolveValue, args[0])); - const y = scaleFactor(argument(resolveValue, args[1])); - - const isXValid = typeof x === "string" || typeof x === "number"; - const isYValid = typeof y === "string" || typeof y === "number"; + const [first, second] = operands(descriptor[2]); + const x = scaleFactor(argument(resolveValue, first)); + const y = second === undefined ? x : scaleFactor(argument(resolveValue, second)); - if (isXValid && isYValid) { - return x === y ? { scale: x } : [{ scaleX: x }, { scaleY: y }]; - } else if (isXValid) { - return { scale: x }; - } else if (isYValid) { - return { scaleY: y }; + if (x === null || y === null) { + return null; } - return; + return x === y ? { scale: x } : [{ scaleX: x }, { scaleY: y }]; }; export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { const args = descriptor[2]; if (!isStyleDescriptorArray(args)) { - return { rotate: resolveValue(args) }; + const angle = resolveValue(args); + + return isTransformComponent(angle) ? { rotate: angle } : null; } const x = argument(resolveValue, args[0]); const y = argument(resolveValue, args[1]); const z = argument(resolveValue, args[2]); - const isXValid = typeof x === "string" || typeof x === "number"; - const isYValid = typeof y === "string" || typeof y === "number"; - const isZValid = typeof z === "string" || typeof z === "number"; + const isXValid = isTransformComponent(x); + const isYValid = isTransformComponent(y); + const isZValid = isTransformComponent(z); if (isXValid && isYValid && isZValid) { return [{ rotateX: x }, { rotateY: y }, { rotateZ: z }]; @@ -59,31 +50,20 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { return { rotateZ: z }; } - return; + return null; }; +// `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { - const args = descriptor[2]; + const [first, second] = operands(descriptor[2]); + const x = argument(resolveValue, first); + const y = second === undefined ? 0 : argument(resolveValue, second); - if (!isStyleDescriptorArray(args)) { - return; + if (!isTransformComponent(x) || !isTransformComponent(y)) { + return null; } - const x = argument(resolveValue, args[0]); - const y = argument(resolveValue, args[1]); - - const isXValid = typeof x === "string" || typeof x === "number"; - const isYValid = typeof y === "string" || typeof y === "number"; - - if (isXValid && isYValid) { - return [{ translateX: x }, { translateY: y }]; - } else if (isXValid) { - return { translateX: x }; - } else if (isYValid) { - return { translateY: y }; - } - - return; + return [{ translateX: x }, { translateY: y }]; }; /** A comma-separated argument list holds each argument as the array of its tokens */ @@ -98,3 +78,11 @@ function argument(resolveValue: SimpleResolveValue, arg: StyleDescriptor) { : arg, ); } + +function operands(args: StyleDescriptor): StyleDescriptor[] { + return isStyleDescriptorArray(args) ? args : [args]; +} + +function isTransformComponent(value: unknown): value is string | number { + return typeof value === "string" || typeof value === "number"; +} diff --git a/src/native/styles/resolve.ts b/src/native/styles/resolve.ts index e68f779a..dbc4e3a8 100644 --- a/src/native/styles/resolve.ts +++ b/src/native/styles/resolve.ts @@ -123,16 +123,16 @@ export function resolveValue( ) as StyleDescriptor; } else if (transformKeys.has(name)) { // translate, rotate, scale, etc. - let resolved = simpleResolve(value[2], castToArray); + const resolved = simpleResolve(value[2], castToArray); // CSS scale percentages describe a factor, unlike translation percentages. - if ( - (name === "scaleX" || name === "scaleY" || name === "scale") && - typeof resolved === "string" && - resolved.endsWith("%") - ) { - resolved = scaleFactor(resolved); - } - return { [name]: resolved }; + const component = + name === "scaleX" || name === "scaleY" || name === "scale" + ? scaleFactor(resolved) + : resolved; + + return component === undefined || component === null + ? null + : { [name]: component }; } else { let args = simpleResolve(value[2], castToArray); diff --git a/src/native/styles/scale-factor.ts b/src/native/styles/scale-factor.ts index 5d30789a..f8fe9d44 100644 --- a/src/native/styles/scale-factor.ts +++ b/src/native/styles/scale-factor.ts @@ -1,6 +1,9 @@ -export function scaleFactor(value: unknown) { - if (typeof value === "string" && value.endsWith("%")) { - return Number(value.slice(0, -1)) / 100; - } - return value; +// React Native takes a scale only as a number, and its transform validator throws on anything else +export function scaleFactor(value: unknown): number | null { + const factor = + typeof value === "string" && value.endsWith("%") + ? Number(value.slice(0, -1)) / 100 + : value; + + return typeof factor === "number" ? factor : null; } diff --git a/src/native/styles/shorthands/transform.ts b/src/native/styles/shorthands/transform.ts index 49a32369..bad77f86 100644 --- a/src/native/styles/shorthands/transform.ts +++ b/src/native/styles/shorthands/transform.ts @@ -12,11 +12,14 @@ export const transform: StyleFunctionResolver = ( if (Array.isArray(transforms)) { // React Native takes one property per transform object, so a resolver's group of entries is spread into the list - return transforms - .flat() - .filter( - (transform) => transform !== undefined && transform !== "initial", - ) as unknown; + const entries: unknown[] = transforms.flat(); + + // A function left without a valid argument makes the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) + return entries.includes(null) + ? [] + : entries.filter( + (transform) => transform !== undefined && transform !== "initial", + ); } else if (transforms) { // If it's a single transform, wrap it in an array return [transforms]; From c16f0e6c96170b6e4a81a4d39301b50c0c725775 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 21:08:57 +0300 Subject: [PATCH 03/17] fix(transforms): a transform list holding anything but entries is none A var() fallback holding a translate() pair nests a level deeper than a resolver's group, and a var() holding bare lengths (`--offset: 10px 20px; transform: var(--offset)`) resolves to numbers rather than entries; both reached React Native's validator. The shorthand now spreads every level, and a list with any item that is not a single-key entry is none, as browsers treat the declaration as invalid at computed-value time. --- src/__tests__/native/transform.test.tsx | 12 ++++++++- .../styles/functions/transform-functions.ts | 8 +++--- src/native/styles/shorthands/transform.ts | 26 ++++++++----------- 3 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 21ad6eb2..cb64e520 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -164,7 +164,7 @@ function renderStyle(css: string): unknown { } // A second definition keeps each variable from being inlined, so it resolves at runtime -const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; }`; +const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; }`; // React Native requires exactly one property per transform object, and its validator throws otherwise describe("one property per entry", () => { @@ -231,6 +231,14 @@ describe("one property per entry", () => { }, ); + test("a translate() pair in a var() fallback renders an entry per axis", () => { + expect( + renderStyle( + `.my-class { transform: var(--missing, translate(10px, 20px)); }`, + ), + ).toStrictEqual({ transform: [{ translateX: 10 }, { translateY: 20 }] }); + }); + test("a function React Native has no form for leaves its neighbour", () => { expect( renderStyle( @@ -246,6 +254,8 @@ test.each([ "transform: translateX(10px) scaleX(var(--missing));", "transform: translate(10px, var(--missing));", "transform: rotate(var(--missing));", + "--offset: 10px 20px; transform: var(--offset);", + "--offset: 10px 20px; transform: translateX(5px) var(--offset);", "--sx: none; transform: scaleX(var(--sx));", "--sx: none; transform: scale(var(--sx));", ])("%s leaves no transform", (declarations) => { diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 32a52f52..36fb8aa3 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -30,9 +30,9 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { const y = argument(resolveValue, args[1]); const z = argument(resolveValue, args[2]); - const isXValid = isTransformComponent(x); - const isYValid = isTransformComponent(y); - const isZValid = isTransformComponent(z); + const isXValid = typeof x === "string" || typeof x === "number"; + const isYValid = typeof y === "string" || typeof y === "number"; + const isZValid = typeof z === "string" || typeof z === "number"; if (isXValid && isYValid && isZValid) { return [{ rotateX: x }, { rotateY: y }, { rotateZ: z }]; @@ -50,7 +50,7 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { return { rotateZ: z }; } - return null; + return; }; // `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) diff --git a/src/native/styles/shorthands/transform.ts b/src/native/styles/shorthands/transform.ts index bad77f86..2622859f 100644 --- a/src/native/styles/shorthands/transform.ts +++ b/src/native/styles/shorthands/transform.ts @@ -10,20 +10,16 @@ export const transform: StyleFunctionResolver = ( ) => { const transforms = resolveValue(transformDescriptor[2]); - if (Array.isArray(transforms)) { - // React Native takes one property per transform object, so a resolver's group of entries is spread into the list - const entries: unknown[] = transforms.flat(); + // A group from a resolver and the list a var() fallback holds each nest a level, while React Native takes a flat list of single-key objects + const resolved: unknown[] = [transforms].flat(Number.POSITIVE_INFINITY); + const entries = resolved.filter( + (transform) => transform !== undefined && transform !== "initial", + ); - // A function left without a valid argument makes the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) - return entries.includes(null) - ? [] - : entries.filter( - (transform) => transform !== undefined && transform !== "initial", - ); - } else if (transforms) { - // If it's a single transform, wrap it in an array - return [transforms]; - } else { - return; - } + // Anything but a transform entry, null included, leaves the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) + return entries.every(isTransformEntry) ? entries : []; }; + +function isTransformEntry(value: unknown): boolean { + return typeof value === "object" && value !== null; +} From f26df668db94e6fb7b6d0014b81bb15cf497e152 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 21:12:15 +0300 Subject: [PATCH 04/17] fix(transforms): read an operand list a var() supplies whole `translate: var(--offset)` with `--offset: 10px 20px`, `transform: translate(var(--offset))` with `--offset: 10px, 20px` and `scale: var(--s)` with `--s: 2 3` each resolve their single var() to the whole operand list, which the resolvers read as one operand and rejected. A missing second operand, as in `scale(2, var(--missing))`, still leaves the declaration invalid rather than falling back to the first. --- src/__tests__/native/transform.test.tsx | 20 +++++++++++- .../styles/functions/transform-functions.ts | 32 +++++++++++++------ 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index cb64e520..950f1f3a 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -164,7 +164,7 @@ function renderStyle(css: string): unknown { } // A second definition keeps each variable from being inlined, so it resolves at runtime -const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; }`; +const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; --s: 1; }`; // React Native requires exactly one property per transform object, and its validator throws otherwise describe("one property per entry", () => { @@ -208,6 +208,23 @@ describe("one property per entry", () => { ); }); + // Chromium 153, Firefox 155 and WebKit 26.6 read an operand list a var() supplies whole + test.each([ + [ + "--offset: 10px 20px; translate: var(--offset);", + [{ translateX: 10 }, { translateY: 20 }], + ], + [ + "--offset: 10px, 20px; transform: translate(var(--offset));", + [{ translateX: 10 }, { translateY: 20 }], + ], + ["--s: 2 3; scale: var(--s);", [{ scaleX: 2 }, { scaleY: 3 }]], + ] as const)("%s reads both operands", (declarations, transform) => { + expect(renderStyle(`${decoy} .my-class { ${declarations} }`)).toStrictEqual( + { transform }, + ); + }); + test("a two-operand translate() renders an entry per axis, beside a sibling", () => { expect( renderStyle( @@ -254,6 +271,7 @@ test.each([ "transform: translateX(10px) scaleX(var(--missing));", "transform: translate(10px, var(--missing));", "transform: rotate(var(--missing));", + "transform: scale(2, var(--missing));", "--offset: 10px 20px; transform: var(--offset);", "--offset: 10px 20px; transform: translateX(5px) var(--offset);", "--sx: none; transform: scaleX(var(--sx));", diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 36fb8aa3..05955e3d 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -1,14 +1,17 @@ import type { StyleDescriptor } from "react-native-css/compiler"; -import { isStyleDescriptorArray } from "react-native-css/utilities"; +import { + commaListItems, + isStyleDescriptorArray, +} from "react-native-css/utilities"; import type { SimpleResolveValue, StyleFunctionResolver } from "../resolve"; import { scaleFactor } from "../scale-factor"; // A component left without a valid value makes the declaration invalid at computed-value time (css-variables-1 §3.1), which null carries export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { - const [first, second] = operands(descriptor[2]); - const x = scaleFactor(argument(resolveValue, first)); - const y = second === undefined ? x : scaleFactor(argument(resolveValue, second)); + const operands = resolveOperands(resolveValue, descriptor[2]); + const x = scaleFactor(operands[0]); + const y = operands.length > 1 ? scaleFactor(operands[1]) : x; if (x === null || y === null) { return null; @@ -55,9 +58,9 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { // `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { - const [first, second] = operands(descriptor[2]); - const x = argument(resolveValue, first); - const y = second === undefined ? 0 : argument(resolveValue, second); + const operands = resolveOperands(resolveValue, descriptor[2]); + const x = operands[0]; + const y = operands.length > 1 ? operands[1] : 0; if (!isTransformComponent(x) || !isTransformComponent(y)) { return null; @@ -79,8 +82,19 @@ function argument(resolveValue: SimpleResolveValue, arg: StyleDescriptor) { ); } -function operands(args: StyleDescriptor): StyleDescriptor[] { - return isStyleDescriptorArray(args) ? args : [args]; +// A var() can supply the whole operand list, which resolves to an array in place of one operand +function resolveOperands( + resolveValue: SimpleResolveValue, + args: StyleDescriptor, +): unknown[] { + if (isStyleDescriptorArray(args)) { + return args.map((arg) => argument(resolveValue, arg)); + } + + // A comma-separated list's items are the operands + const value = commaListItems(resolveValue(args)); + + return Array.isArray(value) ? value : [value]; } function isTransformComponent(value: unknown): value is string | number { From 870760f433cd67b83a242e30a6b68495c89dce2a Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 21:34:27 +0300 Subject: [PATCH 05/17] test(transforms): run each invalid function beside a valid one too On its own, a function left without a valid argument gives the same empty transform whether it is read as invalid or dropped. Next to a valid translateX(5px) only the invalid reading leaves no transform, which is what browsers compute. --- src/__tests__/native/transform.test.tsx | 27 +++++++++++++++---------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 950f1f3a..2d4ff225 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -266,17 +266,22 @@ describe("one property per entry", () => { }); // Chromium 153, Firefox 155 and WebKit 26.6: a function left without a valid argument makes the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) -test.each([ - "transform: scaleX(var(--missing));", - "transform: translateX(10px) scaleX(var(--missing));", - "transform: translate(10px, var(--missing));", - "transform: rotate(var(--missing));", - "transform: scale(2, var(--missing));", - "--offset: 10px 20px; transform: var(--offset);", - "--offset: 10px 20px; transform: translateX(5px) var(--offset);", - "--sx: none; transform: scaleX(var(--sx));", - "--sx: none; transform: scale(var(--sx));", -])("%s leaves no transform", (declarations) => { +test.each( + ( + [ + ["", "scaleX(var(--missing))"], + ["", "translate(10px, var(--missing))"], + ["", "rotate(var(--missing))"], + ["", "scale(2, var(--missing))"], + ["--offset: 10px 20px; ", "var(--offset)"], + ["--sx: none; ", "scaleX(var(--sx))"], + ["--sx: none; ", "scale(var(--sx))"], + ] as const + ).flatMap(([customProperties, transform]) => [ + `${customProperties}transform: ${transform};`, + `${customProperties}transform: translateX(5px) ${transform};`, + ]), +)("%s leaves no transform", (declarations) => { expect( renderStyle( `${decoy} .earlier { transform: rotate(10deg); } .my-class { ${declarations} }`, From fab45c929bc7115ecf4f2afb401a3c0cdc12aba2 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 23:16:24 +0300 Subject: [PATCH 06/17] fix(transforms): give each transform property a cascade slot, composed in CSS order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit translate, rotate, scale and transform each cascade on their own, and the element's transform composes them in that order (css-transforms-2 §6). The runtime appended a longhand to whatever transform array it found, and a later transform replaced the longhands. Each property now records its cascaded value per style target, and the slots compose into one transform after every rule. The compiler emits each longhand as one declaration under its own name, and carries it through the first pass unparsed, because lightningcss before parcel-bundler/lightningcss#1340 folds a parsed longhand into transform. A transform argument the compiler cannot convert now ignores the declaration with a warning (CSS 2.2 §4.2), as width: 1cap already does, instead of rendering an empty entry React Native refuses. A typed calc() warns too. --- src/__tests__/compiler/compiler.test.tsx | 40 ++++ src/__tests__/compiler/declarations.test.tsx | 4 +- src/__tests__/native/transform.test.tsx | 112 ++++++++- .../vendor/tailwind/transform.test.ts | 3 +- src/compiler/calculation.ts | 145 ++++++++++++ src/compiler/compiler.ts | 45 ++-- src/compiler/declarations.ts | 219 ++++++++---------- src/compiler/individual-transforms.ts | 94 ++++++++ src/compiler/tokens.ts | 60 +++++ src/native/objects.ts | 31 --- src/native/styles/calculate-props.ts | 149 +++++++++--- 11 files changed, 690 insertions(+), 212 deletions(-) create mode 100644 src/compiler/calculation.ts create mode 100644 src/compiler/individual-transforms.ts create mode 100644 src/compiler/tokens.ts diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index 01854195..914e27d3 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -382,6 +382,46 @@ test("warnings", () => { }); }); +test("a transform value the compiler cannot convert is ignored, with a warning", () => { + const compiled = compile(` +.my-class { + transform: translate(10px, 1cap); + translate: calc(1em + 5px) 5px; + rotate: 1grad; + scale: 2; +}`); + + expect(compiled.stylesheet()).toStrictEqual({ + s: [ + [ + "my-class", + [ + { + d: [ + [ + [ + [{}, "scaleX", 2], + [{}, "scaleY", 2], + ], + "scale", + ], + ], + s: [1, 1], + }, + ], + ], + ], + }); + + expect(compiled.warnings()).toStrictEqual({ + values: { + transform: ["1cap"], + translate: ["calc()"], + rotate: ["1 grad"], + }, + }); +}); + test("simplifies rem", () => { const compiled = compile(`.test { border-width: calc(10rem + 2px); diff --git a/src/__tests__/compiler/declarations.test.tsx b/src/__tests__/compiler/declarations.test.tsx index c2e18378..4dbd378f 100644 --- a/src/__tests__/compiler/declarations.test.tsx +++ b/src/__tests__/compiler/declarations.test.tsx @@ -8,8 +8,8 @@ const tests = [ ["-rn-ripple-layer: foreground;", [{ d: [[true, ["android_ripple", "foreground"]]], s: [1, 1] }]], ["caret-color: black", [{ d: [["#000", ["cursorColor"]]], s: [1, 1] }]], ["fill: black;", [{ d: [["#000", ["fill"]]], s: [1, 1] }]], - ["rotate: 3deg;", [{ d: [[[{}, "rotateZ", "3deg"], "rotateZ"]], s: [1, 1] }]], - ["rotate: x 3deg;", [{ d: [[[{}, "rotateX", "3deg"], "rotateX"]], s: [1, 1] }]], + ["rotate: 3deg;", [{ d: [[[{}, "rotateZ", "3deg"], "rotate"]], s: [1, 1] }]], + ["rotate: x 3deg;", [{ d: [[[{}, "rotateX", "3deg"], "rotate"]], s: [1, 1] }]], ["stroke-width: 1px;", [{ d: [[1, ["strokeWidth"]]], s: [1, 1] }]], ["stroke: black;", [{ d: [["#000", ["stroke"]]], s: [1, 1] }]], ] as const; diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 2d4ff225..a6b2d6a2 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -164,7 +164,7 @@ function renderStyle(css: string): unknown { } // A second definition keeps each variable from being inlined, so it resolves at runtime -const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; --s: 1; }`; +const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; --s: 1; --x: 9px; --y: 9px; }`; // React Native requires exactly one property per transform object, and its validator throws otherwise describe("one property per entry", () => { @@ -235,18 +235,16 @@ describe("one property per entry", () => { }); }); + // React Native refuses a transform entry without a property, so a function the compiler does not convert contributes none test.each([ "transform: scale3d(1, 2, 3);", "transform: scaleZ(2);", "transform: matrix(1, 0, 0, 1, 0, 0);", - ])( - "%s, which React Native has no form for, renders no entry", - (declaration) => { - expect(renderStyle(`.my-class { ${declaration} }`)).toStrictEqual({ - transform: [], - }); - }, - ); + ])("%s renders no entry", (declaration) => { + expect(renderStyle(`.my-class { ${declaration} }`)).toStrictEqual({ + transform: [], + }); + }); test("a translate() pair in a var() fallback renders an entry per axis", () => { expect( @@ -306,3 +304,99 @@ test.each([ ), ).toStrictEqual({ transform: [{ rotate: "10deg" }] }); }); + +// Chromium 153, Firefox 155 and WebKit 26.6 cascade each transform property on its own, and compose translate, rotate, scale, then the transform list (css-transforms-2 §6) +test.each([ + [ + ".earlier { translate: 10px 20px; } .my-class { --x: 1px; --y: 2px; translate: var(--x) var(--y); }", + [{ translateX: 1 }, { translateY: 2 }], + ], + [ + ".earlier { --x: 1px; --y: 2px; translate: var(--x) var(--y); } .my-class { translate: 10px 20px; }", + [{ translateX: 10 }, { translateY: 20 }], + ], + [ + ".earlier { scale: 2; } .my-class { scale: 3; }", + [{ scaleX: 3 }, { scaleY: 3 }], + ], + [ + ".earlier { transform: rotate(10deg); } .my-class { rotate: 20deg; }", + [{ rotateZ: "20deg" }, { rotate: "10deg" }], + ], + [ + ".earlier { translate: 10px 20px; } .my-class { --t: 5px; transform: translateX(var(--t)); }", + [{ translateX: 10 }, { translateY: 20 }, { translateX: 5 }], + ], + [ + ".earlier { --t: 5px; transform: translateX(var(--t)); } .my-class { translate: 10px 20px; }", + [{ translateX: 10 }, { translateY: 20 }, { translateX: 5 }], + ], + [ + ".my-class { translate: 10px 20px; rotate: 30deg; scale: 2; transform: translateX(5px); }", + [ + { translateX: 10 }, + { translateY: 20 }, + { rotateZ: "30deg" }, + { scaleX: 2 }, + { scaleY: 2 }, + { translateX: 5 }, + ], + ], + [ + ".earlier { translate: 10px 20px !important; } .my-class { translate: 1px 2px; }", + [{ translateX: 10 }, { translateY: 20 }], + ], + [ + ".earlier { transform: rotate(10deg) !important; } .my-class { translate: 1px 2px; }", + [{ translateX: 1 }, { translateY: 2 }, { rotate: "10deg" }], + ], +] as const)("%s composes in CSS order", (css, transform) => { + expect(renderStyle(`${decoy} ${css}`)).toStrictEqual({ transform }); +}); + +// A unit React Native has no equivalent for leaves the declaration invalid there, and an invalid declaration is ignored (CSS 2.2 §4.2) +test.each([ + [ + ".earlier { translate: 5px 6px; } .my-class { translate: 10px 1cap; }", + [{ translateX: 5 }, { translateY: 6 }], + ], + [ + ".earlier { transform: rotate(5deg); } .my-class { translate: 10px 1cap; }", + [{ rotate: "5deg" }], + ], + [ + ".earlier { transform: rotate(5deg); } .my-class { transform: translate(10px, 1cap); }", + [{ rotate: "5deg" }], + ], +] as const)( + "%s ignores the declaration it cannot convert", + (css, transform) => { + expect(renderStyle(css)).toStrictEqual({ transform }); + }, +); + +// Chromium 153, Firefox 155 and WebKit 26.6 resolve an em length against the element's font size, whichever rule sets it (css-values-4 §6.1.1) +test.each([ + [ + ".earlier { translate: 1em 5px; } .my-class { font-size: 20px; }", + [{ translateX: 20 }, { translateY: 5 }], + ], + [ + ".earlier { transform: translateX(1em); } .my-class { font-size: 20px; }", + [{ translateX: 20 }], + ], +] as const)( + "%s resolves em against the element's font size", + (css, transform) => { + expect(renderStyle(css)).toStrictEqual({ fontSize: 20, transform }); + }, +); + +// Chromium 153, Firefox 155 and WebKit 26.6: a later transform without a value replaces an earlier one, and is none (css-variables-1 §3.1) +test("transform: var(--missing) replaces an earlier rule's transform", () => { + expect( + renderStyle( + `${decoy} .earlier { transform: rotate(10deg); } .my-class { transform: var(--missing); }`, + ), + ).toStrictEqual({ transform: [] }); +}); diff --git a/src/__tests__/vendor/tailwind/transform.test.ts b/src/__tests__/vendor/tailwind/transform.test.ts index 2a7cf239..6655504d 100644 --- a/src/__tests__/vendor/tailwind/transform.test.ts +++ b/src/__tests__/vendor/tailwind/transform.test.ts @@ -233,11 +233,12 @@ describe("Transforms - Mixed", () => { ).toStrictEqual({ props: { style: { + // css-transforms-2 §6: translate, then rotate, then the transform list transform: [ - { skewY: "1deg" }, { translateX: 3.5 }, { translateY: 0 }, { rotateZ: "90deg" }, + { skewY: "1deg" }, ], }, }, diff --git a/src/compiler/calculation.ts b/src/compiler/calculation.ts new file mode 100644 index 00000000..3f7cc715 --- /dev/null +++ b/src/compiler/calculation.ts @@ -0,0 +1,145 @@ +import type { + DimensionPercentageFor_LengthValue, + Length, + RoundingStrategy, + TokenOrValue, +} from "lightningcss"; + +import { + commaSeparated, + delimiterToken, + functionToken, + identifierToken, + lengthToken, + numberToken, + percentageToken, + WHITESPACE_TOKEN, +} from "./tokens"; + +export type LengthLeaf = Length | DimensionPercentageFor_LengthValue; + +/** lightningcss's calculation tree for a length, as it holds one it could not fold. */ +export type LengthCalculation = + | { readonly type: "value"; readonly value: LengthLeaf } + | { readonly type: "number"; readonly value: number } + | { + readonly type: "sum"; + readonly value: readonly [LengthCalculation, LengthCalculation]; + } + | { + readonly type: "product"; + readonly value: readonly [number, LengthCalculation]; + } + | { readonly type: "function"; readonly value: LengthMathFunction }; + +export type LengthMathFunction = + | { + readonly type: "calc" | "abs" | "sign"; + readonly value: LengthCalculation; + } + | { + readonly type: "min" | "max" | "hypot"; + readonly value: readonly LengthCalculation[]; + } + | { + readonly type: "clamp"; + readonly value: readonly [ + LengthCalculation, + LengthCalculation, + LengthCalculation, + ]; + } + | { + readonly type: "round"; + readonly value: readonly [ + RoundingStrategy, + LengthCalculation, + LengthCalculation, + ]; + } + | { + readonly type: "rem" | "mod"; + readonly value: readonly [LengthCalculation, LengthCalculation]; + }; + +export function lengthLeafTokens(leaf: LengthLeaf): TokenOrValue[] { + switch (leaf.type) { + case "value": + case "dimension": + return [lengthToken(leaf.value)]; + case "percentage": + return [percentageToken(leaf.value)]; + case "calc": + return [calculationToken(leaf.value)]; + } +} + +/** The one token a calculation is written as: its own math function, or `calc()` around anything else. */ +export function calculationToken(calculation: LengthCalculation): TokenOrValue { + return calculation.type === "function" + ? mathFunctionToken(calculation.value) + : functionToken("calc", calculationTokens(calculation)); +} + +function calculationTokens(calculation: LengthCalculation): TokenOrValue[] { + switch (calculation.type) { + case "value": + return lengthLeafTokens(calculation.value); + case "number": + return [numberToken(calculation.value)]; + case "sum": + return [ + ...calculationTokens(calculation.value[0]), + WHITESPACE_TOKEN, + delimiterToken("+"), + WHITESPACE_TOKEN, + ...calculationTokens(calculation.value[1]), + ]; + case "product": { + const [factor, operand] = calculation.value; + + return [ + numberToken(factor), + WHITESPACE_TOKEN, + delimiterToken("*"), + WHITESPACE_TOKEN, + ...(operand.type === "sum" + ? [calculationToken(operand)] + : calculationTokens(operand)), + ]; + } + case "function": + return [mathFunctionToken(calculation.value)]; + } +} + +function mathFunctionToken(math: LengthMathFunction): TokenOrValue { + switch (math.type) { + case "calc": + case "abs": + case "sign": + return functionToken(math.type, calculationTokens(math.value)); + case "min": + case "max": + case "hypot": + case "clamp": + case "rem": + case "mod": + return functionToken( + math.type, + commaSeparated(math.value.map(calculationTokens)), + ); + case "round": { + const [strategy, value, interval] = math.value; + + return functionToken( + "round", + commaSeparated([ + [identifierToken(strategy)], + calculationTokens(value), + calculationTokens(interval), + ]), + ); + } + } +} diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index d410171f..6cb46729 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -34,6 +34,7 @@ import { reduceParseUnparsed, round, } from "./declarations"; +import { unparseIndividualTransform } from "./individual-transforms"; import { inlineVariables } from "./inline-variables"; import { extractKeyFrames } from "./keyframes"; import { lightningcssLoader } from "./lightningcss-loader"; @@ -190,27 +191,31 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { }; } - if (options.inlineVariables !== false) { - const exclusionList: string[] = options.inlineVariables?.exclude ?? []; + const exclusionList: string[] = + options.inlineVariables === false + ? [] + : (options.inlineVariables?.exclude ?? []); + + firstPassVisitor.Declaration = (decl) => { + if ( + options.inlineVariables !== false && + decl.property === "custom" && + decl.value.name.startsWith("--") && + !exclusionList.includes(decl.value.name) + ) { + const entry = vars.get(decl.value.name) ?? { + count: 0, + value: [ + ...decl.value.value, + { type: "token", value: { type: "white-space", value: " " } }, + ], + }; + entry.count++; + vars.set(decl.value.name, entry); + } - firstPassVisitor.Declaration = (decl) => { - if ( - decl.property === "custom" && - decl.value.name.startsWith("--") && - !exclusionList.includes(decl.value.name) - ) { - const entry = vars.get(decl.value.name) ?? { - count: 0, - value: [ - ...decl.value.value, - { type: "token", value: { type: "white-space", value: " " } }, - ], - }; - entry.count++; - vars.set(decl.value.name, entry); - } - }; - } + return unparseIndividualTransform(decl); + }; const { code: firstPass, warnings: firstPassWarnings } = lightningcss({ code: typeof code === "string" ? new TextEncoder().encode(code) : code, diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 52be116b..7e4547dd 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -736,159 +736,144 @@ function parseFont( builder.addDescriptor("font-weight", parseFontWeight(value.weight, builder)); } +type TransformFunction = Extract< + StyleFunction, + [Record, string, StyleDescriptor] +>; + +// An argument React Native has no equivalent for leaves the declaration invalid there, and an invalid declaration is ignored (CSS 2.2 §4.2) +function hasUnconvertibleArgument( + functions: readonly TransformFunction[], +): boolean { + return functions.some(([, , argument]) => argument === undefined); +} + function parseTransform( { value }: DeclarationType<"transform">, builder: StylesheetBuilder, ) { - builder.addDescriptor("transform", [ - {}, - "transform", - value.flatMap((t): StyleDescriptor[] => { - switch (t.type) { - case "perspective": - return [[{}, "perspective", parseLength(t.value, builder)]]; - case "translate": - return [ - [ - {}, - "translateX", - parseLengthOrCoercePercentageToRuntime(t.value[0], builder), - ], - [ - [ - {}, - "translateY", - parseLengthOrCoercePercentageToRuntime(t.value[1], builder), - ], - ], - ]; - case "translateX": - return [ - [ - {}, - "translateX", - parseLengthOrCoercePercentageToRuntime(t.value, builder), - ], - ]; - case "translateY": - return [ - [ - {}, - "translateY", - parseLengthOrCoercePercentageToRuntime(t.value, builder), - ], - ]; - case "rotate": - return [[{}, "rotate", parseAngle(t.value, builder)]]; - case "rotateX": - return [[{}, "rotateX", parseAngle(t.value, builder)]]; - case "rotateY": - return [[{}, "rotateY", parseAngle(t.value, builder)]]; - case "rotateZ": - return [[{}, "rotateZ", parseAngle(t.value, builder)]]; - case "scale": - return [ - [{}, "scaleX", parseLength(t.value[0], builder)], - [{}, "scaleY", parseLength(t.value[1], builder)], - ]; - case "scaleX": - return [[{}, "scaleX", parseLength(t.value, builder)]]; - case "scaleY": - return [[{}, "scaleY", parseLength(t.value, builder)]]; - case "skew": - return [ - [{}, "skewX", parseAngle(t.value[0], builder)], - [{}, "skewY", parseAngle(t.value[1], builder)], - ]; - case "skewX": - return [[{}, "skewX", parseAngle(t.value, builder)]]; - case "skewY": - return [[{}, "skewY", parseAngle(t.value, builder)]]; - case "translateZ": - case "translate3d": - case "scaleZ": - case "scale3d": - case "rotate3d": - case "matrix": - case "matrix3d": - return [[]]; - } - }), - ]); - return; + const functions = value.flatMap((t): TransformFunction[] => { + switch (t.type) { + case "perspective": + return [[{}, "perspective", parseLength(t.value, builder)]]; + case "translate": + return [ + [{}, "translateX", parseLength(t.value[0], builder)], + [{}, "translateY", parseLength(t.value[1], builder)], + ]; + case "translateX": + return [[{}, "translateX", parseLength(t.value, builder)]]; + case "translateY": + return [[{}, "translateY", parseLength(t.value, builder)]]; + case "rotate": + return [[{}, "rotate", parseAngle(t.value, builder)]]; + case "rotateX": + return [[{}, "rotateX", parseAngle(t.value, builder)]]; + case "rotateY": + return [[{}, "rotateY", parseAngle(t.value, builder)]]; + case "rotateZ": + return [[{}, "rotateZ", parseAngle(t.value, builder)]]; + case "scale": + return [ + [{}, "scaleX", parseLength(t.value[0], builder)], + [{}, "scaleY", parseLength(t.value[1], builder)], + ]; + case "scaleX": + return [[{}, "scaleX", parseLength(t.value, builder)]]; + case "scaleY": + return [[{}, "scaleY", parseLength(t.value, builder)]]; + case "skew": + return [ + [{}, "skewX", parseAngle(t.value[0], builder)], + [{}, "skewY", parseAngle(t.value[1], builder)], + ]; + case "skewX": + return [[{}, "skewX", parseAngle(t.value, builder)]]; + case "skewY": + return [[{}, "skewY", parseAngle(t.value, builder)]]; + case "translateZ": + case "translate3d": + case "scaleZ": + case "scale3d": + case "rotate3d": + case "matrix": + case "matrix3d": + return []; + } + }); + + if (hasUnconvertibleArgument(functions)) { + return; + } + + builder.addDescriptor("transform", [{}, "transform", functions]); } function parseTranslate( { value }: DeclarationType<"translate">, builder: StylesheetBuilder, ) { - builder.addDescriptor("translateX", [ - {}, - "translateX", - parseTranslateProp(value, "x", builder), - ]); - builder.addDescriptor("translateY", [ - {}, - "translateY", - parseTranslateProp(value, "y", builder), - ]); + const translations: TransformFunction[] = [ + [{}, "translateX", parseTranslateProp(value, "x", builder)], + [{}, "translateY", parseTranslateProp(value, "y", builder)], + ]; + + if (hasUnconvertibleArgument(translations)) { + return; + } + + builder.addDescriptor("translate", translations); } function parseRotate( { value }: DeclarationType<"rotate">, builder: StylesheetBuilder, ) { + const angle = parseAngle(value.angle, builder); + const rotations: TransformFunction[] = []; + if (value.x) { - builder.addDescriptor("rotateX", [ - {}, - "rotateX", - parseAngle(value.angle, builder), - ]); + rotations.push([{}, "rotateX", angle]); } if (value.y) { - builder.addDescriptor("rotateY", [ - {}, - "rotateY", - parseAngle(value.angle, builder), - ]); + rotations.push([{}, "rotateY", angle]); } if (value.z) { - builder.addDescriptor("rotateZ", [ - {}, - "rotateZ", - parseAngle(value.angle, builder), - ]); + rotations.push([{}, "rotateZ", angle]); } + + if (hasUnconvertibleArgument(rotations)) { + return; + } + + builder.addDescriptor( + "rotate", + rotations.length === 1 ? rotations[0] : rotations, + ); } function parseScale( { value }: DeclarationType<"scale">, builder: StylesheetBuilder, ) { - builder.addDescriptor("scaleX", [ - {}, - "scaleX", - parseScaleValue(value, "x", builder), - ]); - builder.addDescriptor("scaleY", [ - {}, - "scaleY", - parseScaleValue(value, "y", builder), + builder.addDescriptor("scale", [ + [{}, "scaleX", parseScaleValue(value, "x", builder)], + [{}, "scaleY", parseScaleValue(value, "y", builder)], ]); } export function parseScaleValue( - translate: Scale, + scale: Scale, prop: keyof Extract, builder: StylesheetBuilder, ): StyleDescriptor { - if (translate === "none") { + if (scale === "none") { return 1; } - return parseLength(translate[prop], builder); + return parseLength(scale[prop], builder); } function parseLetterSpacing( @@ -1516,6 +1501,7 @@ export function parseLength( switch (length.type) { case "calc": { // TODO: Add the calc polyfill + builder.addWarning("value", "calc()"); return undefined; } case "number": { @@ -2408,13 +2394,6 @@ export function parseFontVariantCaps( return undefined; } -export function parseLengthOrCoercePercentageToRuntime( - value: Length | DimensionPercentageFor_LengthValue | NumberOrPercentage, - builder: StylesheetBuilder, -): StyleDescriptor { - return parseLength(value, builder); -} - export function parseGap( declaration: DeclarationType<"gap" | "column-gap" | "row-gap">, builder: StylesheetBuilder, diff --git a/src/compiler/individual-transforms.ts b/src/compiler/individual-transforms.ts new file mode 100644 index 00000000..0086b5bf --- /dev/null +++ b/src/compiler/individual-transforms.ts @@ -0,0 +1,94 @@ +import type { + Declaration, + NumberOrPercentage, + Rotate, + Scale, + TokenOrValue, + Translate, +} from "lightningcss"; + +import { lengthLeafTokens } from "./calculation"; +import { + identifierToken, + numberToken, + percentageToken, + spaceSeparated, +} from "./tokens"; + +/** + * Carries `translate`, `rotate` and `scale` across the first pass as the tokens + * they were written as. lightningcss before + * https://github.com/parcel-bundler/lightningcss/pull/1340 folds a parsed one + * into `transform` when it serialises the rule, and passes an unparsed one + * through in place. + */ +export function unparseIndividualTransform( + declaration: Declaration, +): Declaration | undefined { + switch (declaration.property) { + case "translate": + return { + property: "unparsed", + value: { + propertyId: { property: "translate" }, + value: translateTokens(declaration.value), + }, + }; + case "rotate": + return { + property: "unparsed", + value: { + propertyId: { property: "rotate" }, + value: rotateTokens(declaration.value), + }, + }; + case "scale": + return { + property: "unparsed", + value: { + propertyId: { property: "scale" }, + value: scaleTokens(declaration.value), + }, + }; + default: + return undefined; + } +} + +function numberOrPercentageTokens(value: NumberOrPercentage): TokenOrValue[] { + switch (value.type) { + case "number": + return [numberToken(value.value)]; + case "percentage": + return [percentageToken(value.value)]; + } +} + +function translateTokens(value: Translate): TokenOrValue[] { + return value === "none" + ? [identifierToken("none")] + : spaceSeparated([ + lengthLeafTokens(value.x), + lengthLeafTokens(value.y), + lengthLeafTokens(value.z), + ]); +} + +function rotateTokens(value: Rotate): TokenOrValue[] { + return spaceSeparated([ + [numberToken(value.x)], + [numberToken(value.y)], + [numberToken(value.z)], + [{ type: "angle", value: value.angle }], + ]); +} + +function scaleTokens(value: Scale): TokenOrValue[] { + return value === "none" + ? [identifierToken("none")] + : spaceSeparated([ + numberOrPercentageTokens(value.x), + numberOrPercentageTokens(value.y), + numberOrPercentageTokens(value.z), + ]); +} diff --git a/src/compiler/tokens.ts b/src/compiler/tokens.ts new file mode 100644 index 00000000..1ca251b9 --- /dev/null +++ b/src/compiler/tokens.ts @@ -0,0 +1,60 @@ +import type { LengthValue, TokenOrValue } from "lightningcss"; + +export const WHITESPACE_TOKEN: TokenOrValue = { + type: "token", + value: { type: "white-space", value: " " }, +}; + +export const COMMA_TOKEN: TokenOrValue = { + type: "token", + value: { type: "comma" }, +}; + +export function delimiterToken(value: string): TokenOrValue { + return { type: "token", value: { type: "delim", value } }; +} + +export function identifierToken(value: string): TokenOrValue { + return { type: "token", value: { type: "ident", value } }; +} + +export function numberToken(value: number): TokenOrValue { + return { type: "token", value: { type: "number", value } }; +} + +/** lightningcss holds a percentage as its fraction, in a token as in a value: 50% is 0.5. */ +export function percentageToken(fraction: number): TokenOrValue { + return { type: "token", value: { type: "percentage", value: fraction } }; +} + +export function lengthToken(value: LengthValue): TokenOrValue { + return { type: "length", value }; +} + +export function functionToken( + name: string, + argumentTokens: TokenOrValue[], +): TokenOrValue { + return { type: "function", value: { name, arguments: argumentTokens } }; +} + +function joinTokens( + groups: readonly TokenOrValue[][], + separator: readonly TokenOrValue[], +): TokenOrValue[] { + return groups.flatMap((group, index) => + index === 0 ? group : [...separator, ...group], + ); +} + +export function spaceSeparated( + groups: readonly TokenOrValue[][], +): TokenOrValue[] { + return joinTokens(groups, [WHITESPACE_TOKEN]); +} + +export function commaSeparated( + groups: readonly TokenOrValue[][], +): TokenOrValue[] { + return joinTokens(groups, [COMMA_TOKEN, WHITESPACE_TOKEN]); +} diff --git a/src/native/objects.ts b/src/native/objects.ts index a45a313b..d6b5e979 100644 --- a/src/native/objects.ts +++ b/src/native/objects.ts @@ -2,7 +2,6 @@ import { commaListItems } from "react-native-css/utilities"; import { ShortHandSymbol } from "../native/styles/constants"; -import { transformKeys } from "../native/styles/defaults"; export function getDeepPath(source: any, paths: string | string[] | false) { if (!source) { @@ -25,10 +24,6 @@ export function getDeepPath(source: any, paths: string | string[] | false) { } return target; - } else if (transformKeys.has(paths)) { - return Array.isArray(source?.transform) - ? source.transform.find((t: any) => t[paths] !== undefined) - : source.transform; } else { return source?.[paths]; } @@ -55,11 +50,6 @@ export function applyValue( prop: string, value: any, ) { - if (transformKeys.has(prop)) { - applyTransformValue(target, prop, value); - return; - } - // This is confusing. // An undefined value means "don't set anything" (something failed while parsing) // While a null value means "remove this value", which in React Native means "set to undefined" @@ -87,27 +77,6 @@ export function applyValue( target[prop] = value; } -// A transform longhand that resolves to no value is `none`, so its entries go and nothing takes their place -function applyTransformValue( - target: Record, - prop: string, - value: unknown, -) { - const transforms: Record[] = Array.isArray(target.transform) - ? target.transform - : []; - - target.transform = transforms.filter((transform) => !(prop in transform)); - - if (value === undefined || value === null) { - return; - } else if (Array.isArray(value)) { - target.transform.push(...value); - } else { - target.transform.push(value); - } -} - export function setDeepPath( target: Record, paths: string | string[] | readonly string[], diff --git a/src/native/styles/calculate-props.ts b/src/native/styles/calculate-props.ts index 28b9ed36..c8afe058 100644 --- a/src/native/styles/calculate-props.ts +++ b/src/native/styles/calculate-props.ts @@ -2,6 +2,7 @@ import type { InlineVariable, StyleDeclaration, + StyleDescriptor, StyleRule, } from "react-native-css/compiler"; import { Specificity as S } from "react-native-css/utilities"; @@ -13,7 +14,6 @@ import { type Getter, type VariableContextValue, } from "../reactivity"; -import { transformKeys } from "./defaults"; import { resolveValue } from "./resolve"; export function calculateProps( @@ -31,7 +31,7 @@ export function calculateProps( let important: Record | undefined; const delayedStyles: (() => void)[] = []; - const transformStyles: (() => void)[] = []; + const transforms = createTransformComposition(); for (const rule of rules) { if (VAR_SYMBOL in rule) { @@ -50,9 +50,8 @@ export function calculateProps( } if (rule.d) { - let topLevelTarget = rule.s?.[S.Important] - ? (important ??= {}) - : (normal ??= {}); + const isImportant = Boolean(rule.s?.[S.Important]); + let topLevelTarget = isImportant ? (important ??= {}) : (normal ??= {}); let target = topLevelTarget; const ruleTarget = rule.target || "style"; @@ -71,7 +70,7 @@ export function calculateProps( inlineVariables, inheritedVariables, delayedStyles, - transformStyles, + transforms.recorderFor(target, ruleTarget, isImportant), guards, target, topLevelTarget, @@ -83,9 +82,14 @@ export function calculateProps( delayedStyle(); } - for (const transformStyle of transformStyles) { - transformStyle(); - } + transforms.compose((value) => + resolveValue(value, get, { + inlineVariables, + inheritedVariables, + renderGuards: guards, + calculateProps, + }), + ); return { normal, @@ -94,13 +98,108 @@ export function calculateProps( }; } +// css-transforms-2 §6: an element's transform is its `translate`, then its `rotate`, then its `scale`, then its `transform` list +const TRANSFORM_PROPERTIES = [ + "translate", + "rotate", + "scale", + "transform", +] as const; + +type TransformProperty = (typeof TRANSFORM_PROPERTIES)[number]; + +function isTransformProperty(prop: string | number): prop is TransformProperty { + return (TRANSFORM_PROPERTIES as readonly (string | number)[]).includes(prop); +} + +type TransformSlots = Partial>; + +interface TransformTarget { + readonly target: Record; + readonly slots: TransformSlots; +} + +type RecordTransform = ( + property: TransformProperty, + value: StyleDescriptor, +) => void; + +/** Each transform property of each style target is a cascade slot of its own, and the slots compose into one `transform` once every declaration has been walked. */ +function createTransformComposition() { + const byPath = new Map< + string, + { normal?: TransformTarget; important?: TransformTarget } + >(); + + return { + recorderFor( + target: Record, + path: string | readonly string[], + important: boolean, + ): RecordTransform { + return (property, value) => { + const pathKey = typeof path === "string" ? path : path.join("\0"); + const pair = byPath.get(pathKey) ?? {}; + const side = important ? "important" : "normal"; + const recorded = pair[side] ?? { target, slots: {} }; + + recorded.slots[property] = value; + pair[side] = recorded; + byPath.set(pathKey, pair); + }; + }, + + compose(resolve: (value: StyleDescriptor) => unknown) { + for (const { normal, important } of byPath.values()) { + const destination = important ?? normal; + const entries = composeTransform( + { ...normal?.slots, ...important?.slots }, + resolve, + ); + + if (destination !== undefined && entries !== undefined) { + destination.target.transform = entries; + } + } + }, + }; +} + +function composeTransform( + slots: TransformSlots, + resolve: (value: StyleDescriptor) => unknown, +): unknown[] | undefined { + let composed: unknown[] | undefined; + + for (const property of TRANSFORM_PROPERTIES) { + if (!Object.hasOwn(slots, property)) { + continue; + } + + const entries = transformEntries(resolve(slots[property])); + + if (entries !== undefined) { + composed = [...(composed ?? []), ...entries]; + } + } + + return composed; +} + +// A property that resolves to no value is `none` (css-variables-1 §3.1) +function transformEntries(value: unknown): unknown[] | undefined { + return value === undefined || value === null + ? undefined + : [value].flat(Number.POSITIVE_INFINITY); +} + export function applyDeclarations( get: Getter, declarations: StyleDeclaration[], inlineVariables: InlineVariable, inheritedVariables: VariableContextValue, delayedStyles: (() => void)[] = [], - transformStyles: (() => void)[] = [], + recordTransform: RecordTransform = () => undefined, guards: RenderGuard[] = [], target: Record = {}, topLevelTarget = target, @@ -162,9 +261,14 @@ export function applyDeclarations( prop = propPath; } + if (target === originalTarget && isTransformProperty(prop)) { + recordTransform(prop, value); + continue; + } + const shouldDelay = declaration[2]; - if (shouldDelay || transformKeys.has(prop)) { + if (shouldDelay) { /** * We need to delay the resolution of this value until after all * styles have been calculated. But another style might override @@ -175,11 +279,11 @@ export function applyDeclarations( * mutate the props object and not create a new one */ const originalValue = value; - // This needs to be a object with the [prop] so we can discover in transform arrays value = { [prop]: true }; - if (transformKeys.has(prop)) { - transformStyles.push(() => { + delayedStyles.push(() => { + if (getDeepPath(target, prop) === value) { + delete target[prop]; value = resolveValue(originalValue, get, { inlineVariables, inheritedVariables, @@ -187,21 +291,8 @@ export function applyDeclarations( calculateProps, }); applyValue(target, prop, value); - }); - } else { - delayedStyles.push(() => { - if (getDeepPath(target, prop) === value) { - delete target[prop]; - value = resolveValue(originalValue, get, { - inlineVariables, - inheritedVariables, - renderGuards: guards, - calculateProps, - }); - applyValue(target, prop, value); - } - }); - } + } + }); } else { value = resolveValue(value, get, { inlineVariables, From edc1086afff52139086189b0b4134bae28b231f8 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 23:32:36 +0300 Subject: [PATCH 07/17] fix(transforms): read translate, rotate and scale by their own grammars MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The individual transform properties each have a grammar of their own (css-transforms-2 §3): translate and scale take an optional z, and rotate takes an axis keyword or a vector beside its angle, in either order. A deferred one ran through the transform function of the same name, which takes no z, no axis and no none. Each now resolves through its own grammar on both routes. A rotation turns about the axis its vector names, reversed about a negative axis, and the zero vector rotates by none; the compiler and the runtime share that one decision. React Native's rotate keys turn only about an axis, so a vector off every axis warns and is ignored when written, and is none when substituted. A scale along z warns. A var() can supply part of a property's values, and they splice into the rest. A transform function given more operands than it takes is invalid. --- src/__tests__/compiler/compiler.test.tsx | 67 ++++++ src/__tests__/native/transform.test.tsx | 106 +++++++++- src/compiler/declarations.ts | 73 ++++--- .../styles/functions/transform-functions.ts | 194 ++++++++++++++---- src/utilities/index.ts | 1 + src/utilities/rotation-axis.ts | 37 ++++ 6 files changed, 408 insertions(+), 70 deletions(-) create mode 100644 src/utilities/rotation-axis.ts diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index 914e27d3..fc23072e 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -422,6 +422,73 @@ test("a transform value the compiler cannot convert is ignored, with a warning", }); }); +test("a scale along z or a rotate about an oblique axis warns", () => { + const compiled = compile(` +.my-class { + scale: 2 3 400%; + rotate: 1 1 0 45deg; +} +.unwarned { + scale: 2 3 100%; + translate: 10px 20px 30px; + rotate: 0 0 0 45deg; +}`); + + expect(compiled.stylesheet()).toStrictEqual({ + s: [ + [ + "my-class", + [ + { + d: [ + [ + [ + [{}, "scaleX", 2], + [{}, "scaleY", 3], + ], + "scale", + ], + ], + s: [1, 1], + }, + ], + ], + [ + "unwarned", + [ + { + d: [ + [ + [ + [{}, "scaleX", 2], + [{}, "scaleY", 3], + ], + "scale", + ], + [ + [ + [{}, "translateX", 10], + [{}, "translateY", 20], + ], + "translate", + ], + [[{}, "rotateZ", "0deg"], "rotate"], + ], + s: [2, 1], + }, + ], + ], + ], + }); + + expect(compiled.warnings()).toStrictEqual({ + values: { + scale: ["400%"], + rotate: ["1 1 0 45deg"], + }, + }); +}); + test("simplifies rem", () => { const compiled = compile(`.test { border-width: calc(10rem + 2px); diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index a6b2d6a2..4dfe977a 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -164,7 +164,7 @@ function renderStyle(css: string): unknown { } // A second definition keeps each variable from being inlined, so it resolves at runtime -const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; --s: 1; --x: 9px; --y: 9px; }`; +const decoy = `.decoy { --sx: 9; --sy: 9; --t: 9px; --offset: 1px; --s: 1; --x: 9px; --y: 9px; --r: 9deg; }`; // React Native requires exactly one property per transform object, and its validator throws otherwise describe("one property per entry", () => { @@ -274,6 +274,9 @@ test.each( ["--offset: 10px 20px; ", "var(--offset)"], ["--sx: none; ", "scaleX(var(--sx))"], ["--sx: none; ", "scale(var(--sx))"], + ["--t: 1px, 2px, 3px; ", "translate(var(--t))"], + ["--s: 1, 2, 3; ", "scale(var(--s))"], + ["--r: 10deg, 20deg; ", "rotate(var(--r))"], ] as const ).flatMap(([customProperties, transform]) => [ `${customProperties}transform: ${transform};`, @@ -292,7 +295,6 @@ test.each([ "scale: var(--missing);", "scale: var(--missing) var(--missing);", "translate: var(--missing) var(--missing);", - "--sx: none; scale: var(--sx);", "--sx: none; --sy: 2; scale: var(--sx) var(--sy);", "scale: unset;", "scale: initial;", @@ -392,6 +394,106 @@ test.each([ }, ); +// Chromium 153 and Firefox 155 rotate about the axis a vector names, reversing the angle about a negative axis, and rotate by none about the zero vector; WebKit 26.6 ignores the direction of a z axis +test.each([ + ["rotate: 0 0 -1 45deg;", [{ rotateZ: "-45deg" }]], + ["--r: 0 0 -1 45deg; rotate: var(--r);", [{ rotateZ: "-45deg" }]], + ["rotate: -1 0 0 45deg;", [{ rotateX: "-45deg" }]], + ["--r: -1 0 0 45deg; rotate: var(--r);", [{ rotateX: "-45deg" }]], + ["rotate: 0 0 2 45deg;", [{ rotateZ: "45deg" }]], + ["--r: 0 0 2 45deg; rotate: var(--r);", [{ rotateZ: "45deg" }]], + ["rotate: x 45deg;", [{ rotateX: "45deg" }]], + ["--r: x 45deg; rotate: var(--r);", [{ rotateX: "45deg" }]], + ["rotate: 45deg y;", [{ rotateY: "45deg" }]], + ["--r: 45deg y; rotate: var(--r);", [{ rotateY: "45deg" }]], + ["--r: 20deg; rotate: var(--r);", [{ rotateZ: "20deg" }]], + ["--r: x; rotate: var(--r) 45deg;", [{ rotateX: "45deg" }]], + ["--r: 0 0 -1; rotate: var(--r) 45deg;", [{ rotateZ: "-45deg" }]], + ["rotate: 0 0 0 45deg;", [{ rotateZ: "0deg" }]], + ["--r: 0 0 0 45deg; rotate: var(--r);", [{ rotateZ: "0deg" }]], + ["--r: none; rotate: var(--r);", [{ rotateZ: "0deg" }]], +] as const)("%s rotates about the axis it names", (declarations, transform) => { + expect( + renderStyle( + `${decoy} .earlier { rotate: 10deg; } .my-class { ${declarations} }`, + ), + ).toStrictEqual({ transform }); +}); + +// Chromium 153, Firefox 155 and WebKit 26.6 read the third value of translate and scale as its z, which React Native has no axis for +test.each([ + ["translate: 10px 20px 30px;", [{ translateX: 10 }, { translateY: 20 }]], + [ + "--t: 10px 20px 30px; translate: var(--t);", + [{ translateX: 10 }, { translateY: 20 }], + ], + [ + "--t: 20px 30px; translate: 10px var(--t);", + [{ translateX: 10 }, { translateY: 20 }], + ], + ["--t: none; translate: var(--t);", [{ translateX: 0 }, { translateY: 0 }]], + ["--t: NONE; translate: var(--t);", [{ translateX: 0 }, { translateY: 0 }]], + ["scale: 2 3 4;", [{ scaleX: 2 }, { scaleY: 3 }]], + ["--s: 2 3 4; scale: var(--s);", [{ scaleX: 2 }, { scaleY: 3 }]], + ["--s: 3 4; scale: 2 var(--s);", [{ scaleX: 2 }, { scaleY: 3 }]], + ["--s: none; scale: var(--s);", [{ scaleX: 1 }, { scaleY: 1 }]], +] as const)("%s renders its x and y", (declarations, transform) => { + expect( + renderStyle( + `${decoy} .earlier { translate: 1px 2px; scale: 5; } .my-class { translate: none; scale: none; ${declarations} }`, + ), + ).toStrictEqual({ + transform: [ + ...(declarations.includes("translate") + ? transform + : [{ translateX: 0 }, { translateY: 0 }]), + ...(declarations.includes("scale") + ? transform + : [{ scaleX: 1 }, { scaleY: 1 }]), + ], + }); +}); + +// Chromium 153, Firefox 155 and WebKit 26.6: a value the property's grammar does not take is invalid at computed-value time, so the property is none (css-variables-1 §3.1) +test.each([ + "--r: x y 45deg; rotate: var(--r);", + "--r: 0 45deg 0 1; rotate: var(--r);", + "--t: 10px 20px 30%; translate: var(--t);", + "--t: 1px 2px 3px 4px; translate: var(--t);", + "--s: 2 3 4 5; scale: var(--s);", + "--s: 2 3 red; scale: var(--s);", + "--s: none 2; scale: var(--s);", +])("%s leaves the property none", (declarations) => { + expect( + renderStyle( + `${decoy} .earlier { translate: 1px 2px; rotate: 10deg; scale: 5; transform: translateX(5px); } .my-class { ${declarations} }`, + ), + ).toStrictEqual({ + transform: [ + ...(declarations.includes("translate:") + ? [] + : [{ translateX: 1 }, { translateY: 2 }]), + ...(declarations.includes("rotate:") ? [] : [{ rotateZ: "10deg" }]), + ...(declarations.includes("scale:") + ? [] + : [{ scaleX: 5 }, { scaleY: 5 }]), + { translateX: 5 }, + ], + }); +}); + +// React Native's rotate keys turn only about an axis, so a rotate about a vector off every axis is ignored when written and none when substituted +test.each([ + ["rotate: 1 1 0 45deg;", [{ rotateZ: "10deg" }]], + ["--r: 1 1 0 45deg; rotate: var(--r);", []], +] as const)("%s rotates by none", (declarations, transform) => { + expect( + renderStyle( + `${decoy} .earlier { rotate: 10deg; } .my-class { ${declarations} }`, + ), + ).toStrictEqual(transform.length === 0 ? {} : { transform }); +}); + // Chromium 153, Firefox 155 and WebKit 26.6: a later transform without a value replaces an earlier one, and is none (css-variables-1 §3.1) test("transform: var(--missing) replaces an earlier rule's transform", () => { expect( diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 7e4547dd..23154dd5 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -36,7 +36,7 @@ import type { UnresolvedColor, } from "lightningcss"; -import { isStyleFunction } from "../utilities"; +import { isStyleFunction, negateAngle, rotationAxis } from "../utilities"; import { isMappingProperty } from "./atRules"; import type { StyleDescriptor, @@ -102,6 +102,13 @@ const unparsedRuntimeParsing = new Set([ "translate", ]); +// css-transforms-2 §3: the individual transform properties each have a grammar of their own, which the transform function of the same name does not share +const INDIVIDUAL_TRANSFORM_RESOLVERS: ReadonlyMap = new Map([ + ["rotate", "individualRotate"], + ["scale", "individualScale"], + ["translate", "individualTranslate"], +]); + const parsers: { [K in Declaration["property"]]?: Parser; } = { @@ -829,35 +836,50 @@ function parseRotate( { value }: DeclarationType<"rotate">, builder: StylesheetBuilder, ) { - const angle = parseAngle(value.angle, builder); - const rotations: TransformFunction[] = []; - - if (value.x) { - rotations.push([{}, "rotateX", angle]); - } - - if (value.y) { - rotations.push([{}, "rotateY", angle]); - } - - if (value.z) { - rotations.push([{}, "rotateZ", angle]); - } + const rotation = rotationAxis(value.x, value.y, value.z); - if (hasUnconvertibleArgument(rotations)) { - return; + switch (rotation.type) { + case "none": + builder.addDescriptor("rotate", [{}, "rotateZ", "0deg"]); + return; + case "axis": { + const angle = parseAngle(value.angle, builder); + + if (angle !== undefined) { + builder.addDescriptor("rotate", [ + {}, + rotation.rotation, + rotation.reversed ? negateAngle(angle) : angle, + ]); + } + return; + } + // React Native's rotate keys turn only about an axis, so a vector off every axis has none to take it + case "oblique": + builder.addWarning( + "value", + `${value.x} ${value.y} ${value.z} ${value.angle.value}${value.angle.type}`, + ); + return; + default: + rotation satisfies never; } - - builder.addDescriptor( - "rotate", - rotations.length === 1 ? rotations[0] : rotations, - ); } function parseScale( { value }: DeclarationType<"scale">, builder: StylesheetBuilder, ) { + // React Native has no z axis to scale along, and lightningcss holds a percentage as its fraction + if (value !== "none" && value.z.value !== 1) { + builder.addWarning( + "value", + value.z.type === "percentage" + ? `${round(value.z.value * 100)}%` + : `${round(value.z.value)}`, + ); + } + builder.addDescriptor("scale", [ [{}, "scaleX", parseScaleValue(value, "x", builder)], [{}, "scaleY", parseScaleValue(value, "y", builder)], @@ -974,7 +996,12 @@ export function parseUnparsedDeclaration( if (property === "animation") { builder.addDescriptor("animation", [{}, property, args]); } else { - builder.addDescriptor(property, [{}, toRNProperty(property), args, 1]); + builder.addDescriptor(property, [ + {}, + INDIVIDUAL_TRANSFORM_RESOLVERS.get(property) ?? toRNProperty(property), + args, + 1, + ]); } } else { const value = parseUnparsed(declaration.value.value, builder, property); diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 05955e3d..e2cfb1f6 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -2,6 +2,8 @@ import type { StyleDescriptor } from "react-native-css/compiler"; import { commaListItems, isStyleDescriptorArray, + negateAngle, + rotationAxis, } from "react-native-css/utilities"; import type { SimpleResolveValue, StyleFunctionResolver } from "../resolve"; @@ -9,65 +11,167 @@ import { scaleFactor } from "../scale-factor"; // A component left without a valid value makes the declaration invalid at computed-value time (css-variables-1 §3.1), which null carries export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { + return scalePair(resolveOperands(resolveValue, descriptor[2])); +}; + +export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { const operands = resolveOperands(resolveValue, descriptor[2]); - const x = scaleFactor(operands[0]); - const y = operands.length > 1 ? scaleFactor(operands[1]) : x; + const [angle] = operands; - if (x === null || y === null) { - return null; + return operands.length === 1 && isTransformComponent(angle) + ? { rotate: angle } + : null; +}; + +export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { + return translatePair(resolveOperands(resolveValue, descriptor[2])); +}; + +// css-transforms-2 §3: `translate: none | [ ?]?`, and React Native has no z axis to move along +export const individualTranslate: StyleFunctionResolver = ( + resolveValue, + descriptor, +) => { + const operands = resolveOperands(resolveValue, descriptor[2]); + + if (operands.length === 1 && isNoneKeyword(operands[0])) { + return [{ translateX: 0 }, { translateY: 0 }]; } - return x === y ? { scale: x } : [{ scaleX: x }, { scaleY: y }]; + const z = operands.length > 2 ? operands[2] : 0; + + return operands.length <= 3 && typeof z === "number" + ? translatePair(operands.slice(0, 2)) + : null; }; -export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { - const args = descriptor[2]; +// css-transforms-2 §3: `scale: none | [ | ]{1,3}`, and React Native has no z axis to scale along +export const individualScale: StyleFunctionResolver = ( + resolveValue, + descriptor, +) => { + const operands = resolveOperands(resolveValue, descriptor[2]); + + if (operands.length === 1 && isNoneKeyword(operands[0])) { + return [{ scaleX: 1 }, { scaleY: 1 }]; + } + + const z = operands.length > 2 ? operands[2] : 1; + + return operands.length <= 3 && scaleFactor(z) !== null + ? scalePair(operands.slice(0, 2)) + : null; +}; + +// css-transforms-2 §3: `rotate: none | | [x | y | z | {3}] && ` +export const individualRotate: StyleFunctionResolver = ( + resolveValue, + descriptor, +) => { + const operands = resolveOperands(resolveValue, descriptor[2]); + + if (operands.length === 1) { + const [angle] = operands; - if (!isStyleDescriptorArray(args)) { - const angle = resolveValue(args); + if (isNoneKeyword(angle)) { + return { rotateZ: "0deg" }; + } - return isTransformComponent(angle) ? { rotate: angle } : null; + return isTransformComponent(angle) ? { rotateZ: angle } : null; } - const x = argument(resolveValue, args[0]); - const y = argument(resolveValue, args[1]); - const z = argument(resolveValue, args[2]); - - const isXValid = typeof x === "string" || typeof x === "number"; - const isYValid = typeof y === "string" || typeof y === "number"; - const isZValid = typeof z === "string" || typeof z === "number"; - - if (isXValid && isYValid && isZValid) { - return [{ rotateX: x }, { rotateY: y }, { rotateZ: z }]; - } else if (isXValid && isYValid) { - return [{ rotateX: x }, { rotateY: y }]; - } else if (isXValid && isZValid) { - return [{ rotateX: x }, { rotateZ: z }]; - } else if (isYValid && isZValid) { - return [{ rotateY: y }, { rotateZ: z }]; - } else if (isXValid) { - return { rotateX: x }; - } else if (isYValid) { - return { rotateY: y }; - } else if (isZValid) { - return { rotateZ: z }; + const axisIndex = operands.findIndex(isAxisKeyword); + + if (axisIndex !== -1) { + const axis = operands[axisIndex]; + const angle = operands[axisIndex === 0 ? 1 : 0]; + + return operands.length === 2 && + isAxisKeyword(axis) && + isTransformComponent(angle) + ? { [AXIS_ROTATIONS[axis]]: angle } + : null; } - return; + const angleIndex = operands.length === 4 ? angleOperandIndex(operands) : -1; + const angle = operands[angleIndex]; + const [x, y, z] = operands.filter((_, index) => index !== angleIndex); + + if ( + angleIndex === -1 || + !isTransformComponent(angle) || + typeof x !== "number" || + typeof y !== "number" || + typeof z !== "number" + ) { + return null; + } + + const rotation = rotationAxis(x, y, z); + + switch (rotation.type) { + case "none": + return { rotateZ: "0deg" }; + case "axis": + return { + [rotation.rotation]: rotation.reversed ? negateAngle(angle) : angle, + }; + case "oblique": + return null; + default: + rotation satisfies never; + return null; + } }; +const AXIS_ROTATIONS = { + x: "rotateX", + y: "rotateY", + z: "rotateZ", +} as const; + +function isAxisKeyword(value: unknown): value is keyof typeof AXIS_ROTATIONS { + return value === "x" || value === "y" || value === "z"; +} + +// The angle of a vector rotation comes first or last, around three numbers +function angleOperandIndex(operands: readonly unknown[]): number { + const index = operands.findIndex((operand) => typeof operand === "string"); + + return index === 0 || index === operands.length - 1 ? index : -1; +} + +// `none` is the identity transform, and React Native refuses the keyword itself +function isNoneKeyword(value: unknown): boolean { + return typeof value === "string" && value.toLowerCase() === "none"; +} + +function scalePair(operands: readonly unknown[]): unknown { + const x = scaleFactor(operands[0]); + const y = operands.length > 1 ? scaleFactor(operands[1]) : x; + + if (operands.length > 2 || x === null || y === null) { + return null; + } + + return x === y ? { scale: x } : [{ scaleX: x }, { scaleY: y }]; +} + // `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) -export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { - const operands = resolveOperands(resolveValue, descriptor[2]); +function translatePair(operands: readonly unknown[]): unknown { const x = operands[0]; const y = operands.length > 1 ? operands[1] : 0; - if (!isTransformComponent(x) || !isTransformComponent(y)) { + if ( + operands.length > 2 || + !isTransformComponent(x) || + !isTransformComponent(y) + ) { return null; } return [{ translateX: x }, { translateY: y }]; -}; +} /** A comma-separated argument list holds each argument as the array of its tokens */ function argument(resolveValue: SimpleResolveValue, arg: StyleDescriptor) { @@ -82,19 +186,19 @@ function argument(resolveValue: SimpleResolveValue, arg: StyleDescriptor) { ); } -// A var() can supply the whole operand list, which resolves to an array in place of one operand +// A var() substitutes its tokens before the grammar reads them, so it can supply one operand, several, or the whole list (css-variables-1 §3) function resolveOperands( resolveValue: SimpleResolveValue, args: StyleDescriptor, ): unknown[] { - if (isStyleDescriptorArray(args)) { - return args.map((arg) => argument(resolveValue, arg)); - } - - // A comma-separated list's items are the operands - const value = commaListItems(resolveValue(args)); + // A lone var()'s comma-separated list supplies its items as the operands + const resolved = isStyleDescriptorArray(args) + ? args.map((arg) => argument(resolveValue, arg)) + : [commaListItems(resolveValue(args))]; - return Array.isArray(value) ? value : [value]; + return resolved.flatMap((operand): readonly unknown[] => + Array.isArray(operand) ? operand : [operand], + ); } function isTransformComponent(value: unknown): value is string | number { diff --git a/src/utilities/index.ts b/src/utilities/index.ts index a421c7b6..d9d7ee44 100644 --- a/src/utilities/index.ts +++ b/src/utilities/index.ts @@ -2,3 +2,4 @@ export * from "./equality"; export * from "./specificity"; export * from "./style-descriptor"; export * from "./dot-notation.types"; +export * from "./rotation-axis"; diff --git a/src/utilities/rotation-axis.ts b/src/utilities/rotation-axis.ts new file mode 100644 index 00000000..9a4fa30a --- /dev/null +++ b/src/utilities/rotation-axis.ts @@ -0,0 +1,37 @@ +export type RotationAxis = + | { readonly type: "none" } + | { + readonly type: "axis"; + readonly rotation: "rotateX" | "rotateY" | "rotateZ"; + readonly reversed: boolean; + } + | { readonly type: "oblique" }; + +// css-transforms-2 §3: a rotation turns about the direction its vector names, and the zero vector names none +export function rotationAxis(x: number, y: number, z: number): RotationAxis { + if (x === 0 && y === 0 && z === 0) { + return { type: "none" }; + } + + if (y === 0 && z === 0) { + return { type: "axis", rotation: "rotateX", reversed: x < 0 }; + } + + if (x === 0 && z === 0) { + return { type: "axis", rotation: "rotateY", reversed: y < 0 }; + } + + if (x === 0 && y === 0) { + return { type: "axis", rotation: "rotateZ", reversed: z < 0 }; + } + + return { type: "oblique" }; +} + +export function negateAngle(angle: string | number): string | number { + if (typeof angle === "number") { + return -angle; + } + + return angle.startsWith("-") ? angle.slice(1) : `-${angle}`; +} From ca6c8e5137435f605fe1ef811149942b0b96d5c4 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 9 Oct 2026 23:33:43 +0300 Subject: [PATCH 08/17] fix(transforms): render a scale as the scaleX / scaleY pair on both routes The compiler writes scale(2) and scale: 2 as the scaleX / scaleY pair, while the runtime wrote the same value as one scale entry when both axes matched. Both routes now write the pair, so one value has one shape whichever route resolves it. --- src/__tests__/native/transform.test.tsx | 4 ++-- src/__tests__/vendor/tailwind/transform.test.ts | 4 ++-- src/native/styles/functions/transform-functions.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 4dfe977a..7b7edeaf 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -188,13 +188,13 @@ describe("one property per entry", () => { renderStyle( `${decoy} .my-class { --sx: 75%; transform: scale(var(--sx)); }`, ), - ).toStrictEqual({ transform: [{ scale: 0.75 }] }); + ).toStrictEqual({ transform: [{ scaleX: 0.75 }, { scaleY: 0.75 }] }); }); test("scale: var(--sx) scales both axes by its one value", () => { expect( renderStyle(`${decoy} .my-class { --sx: 75%; scale: var(--sx); }`), - ).toStrictEqual({ transform: [{ scale: 0.75 }] }); + ).toStrictEqual({ transform: [{ scaleX: 0.75 }, { scaleY: 0.75 }] }); }); // Chromium 153, Firefox 155 and WebKit 26.6 translate a one-operand translate() along x only diff --git a/src/__tests__/vendor/tailwind/transform.test.ts b/src/__tests__/vendor/tailwind/transform.test.ts index 6655504d..7d859046 100644 --- a/src/__tests__/vendor/tailwind/transform.test.ts +++ b/src/__tests__/vendor/tailwind/transform.test.ts @@ -26,7 +26,7 @@ describe("Transforms - Scale", () => { expect(await renderCurrentTest()).toStrictEqual({ props: { style: { - transform: [{ scale: 0 }], + transform: [{ scaleX: 0 }, { scaleY: 0 }], }, }, }); @@ -53,7 +53,7 @@ describe("Transforms - Scale", () => { expect(await renderCurrentTest()).toStrictEqual({ props: { style: { - transform: [{ scale: 0.5 }], + transform: [{ scaleX: 0.5 }, { scaleY: 0.5 }], }, }, }); diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index e2cfb1f6..621abd51 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -154,7 +154,7 @@ function scalePair(operands: readonly unknown[]): unknown { return null; } - return x === y ? { scale: x } : [{ scaleX: x }, { scaleY: y }]; + return [{ scaleX: x }, { scaleY: y }]; } // `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) From 42444d8f425740d6b7e909ca087f6766cd405848 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 10 Nov 2026 20:22:01 -0500 Subject: [PATCH 09/17] perf(native): record transform declarations without per-render closures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The transform cascade built a Map, a recorder object and a closure for every calculateProps call, and a further closure for every rule, and tested each dynamic declaration with TRANSFORM_PROPERTIES.includes(). An element with no transform paid all of it: about 400 ns per render on Hermes for a single color: var(--c). A transform declaration now pushes one record onto an array, the slots are grouped and composed only when one was recorded, and the property test is four string compares. The cascade is unchanged: slots compose in css-transforms-2 §6 order, a later rule replaces an earlier one, and an !important slot replaces a normal one for the same path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D4jU1dW7KKQntNrr9i2xGi --- src/native/styles/calculate-props.ts | 162 +++++++++++++++------------ 1 file changed, 88 insertions(+), 74 deletions(-) diff --git a/src/native/styles/calculate-props.ts b/src/native/styles/calculate-props.ts index c8afe058..4ce33924 100644 --- a/src/native/styles/calculate-props.ts +++ b/src/native/styles/calculate-props.ts @@ -31,7 +31,7 @@ export function calculateProps( let important: Record | undefined; const delayedStyles: (() => void)[] = []; - const transforms = createTransformComposition(); + const transforms: TransformRecord[] = []; for (const rule of rules) { if (VAR_SYMBOL in rule) { @@ -70,10 +70,12 @@ export function calculateProps( inlineVariables, inheritedVariables, delayedStyles, - transforms.recorderFor(target, ruleTarget, isImportant), + transforms, guards, target, topLevelTarget, + ruleTarget, + isImportant, ); } } @@ -82,14 +84,16 @@ export function calculateProps( delayedStyle(); } - transforms.compose((value) => - resolveValue(value, get, { - inlineVariables, - inheritedVariables, - renderGuards: guards, - calculateProps, - }), - ); + if (transforms.length > 0) { + composeTransforms(transforms, (value) => + resolveValue(value, get, { + inlineVariables, + inheritedVariables, + renderGuards: guards, + calculateProps, + }), + ); + } return { normal, @@ -108,89 +112,97 @@ const TRANSFORM_PROPERTIES = [ type TransformProperty = (typeof TRANSFORM_PROPERTIES)[number]; +// Compares, not TRANSFORM_PROPERTIES.includes(): this runs for every dynamic declaration function isTransformProperty(prop: string | number): prop is TransformProperty { - return (TRANSFORM_PROPERTIES as readonly (string | number)[]).includes(prop); + return ( + prop === "transform" || + prop === "translate" || + prop === "rotate" || + prop === "scale" + ); } type TransformSlots = Partial>; -interface TransformTarget { +/** A transform property's declaration, kept until every rule has been walked */ +interface TransformRecord { readonly target: Record; - readonly slots: TransformSlots; + readonly path: string | readonly string[]; + readonly important: boolean; + readonly property: TransformProperty; + readonly value: StyleDescriptor; } -type RecordTransform = ( - property: TransformProperty, - value: StyleDescriptor, -) => void; - -/** Each transform property of each style target is a cascade slot of its own, and the slots compose into one `transform` once every declaration has been walked. */ -function createTransformComposition() { +/** + * Each transform property of each style target is a cascade slot of its own, + * and the slots compose into one `transform`. Records arrive in cascade + * order, so a later one replaces an earlier one, and an !important slot + * replaces a normal one for the same path. + */ +function composeTransforms( + records: readonly TransformRecord[], + resolve: (value: StyleDescriptor) => unknown, +) { const byPath = new Map< string, - { normal?: TransformTarget; important?: TransformTarget } + { target: Record; normal: TransformSlots; important: TransformSlots } >(); - return { - recorderFor( - target: Record, - path: string | readonly string[], - important: boolean, - ): RecordTransform { - return (property, value) => { - const pathKey = typeof path === "string" ? path : path.join("\0"); - const pair = byPath.get(pathKey) ?? {}; - const side = important ? "important" : "normal"; - const recorded = pair[side] ?? { target, slots: {} }; - - recorded.slots[property] = value; - pair[side] = recorded; - byPath.set(pathKey, pair); - }; - }, - - compose(resolve: (value: StyleDescriptor) => unknown) { - for (const { normal, important } of byPath.values()) { - const destination = important ?? normal; - const entries = composeTransform( - { ...normal?.slots, ...important?.slots }, - resolve, - ); - - if (destination !== undefined && entries !== undefined) { - destination.target.transform = entries; - } - } - }, - }; -} + for (const record of records) { + const pathKey = + typeof record.path === "string" ? record.path : record.path.join("\0"); + let slots = byPath.get(pathKey); -function composeTransform( - slots: TransformSlots, - resolve: (value: StyleDescriptor) => unknown, -): unknown[] | undefined { - let composed: unknown[] | undefined; + if (slots === undefined) { + slots = { target: record.target, normal: {}, important: {} }; + byPath.set(pathKey, slots); + } - for (const property of TRANSFORM_PROPERTIES) { - if (!Object.hasOwn(slots, property)) { - continue; + if (record.important) { + // The important target is merged over the normal one, so it takes the composed list + slots.target = record.target; + slots.important[record.property] = record.value; + } else { + slots.normal[record.property] = record.value; } + } + + for (const { target, normal, important } of byPath.values()) { + let composed: unknown[] | undefined; + + for (const property of TRANSFORM_PROPERTIES) { + const value = + property in important + ? important[property] + : property in normal + ? normal[property] + : undefined; + + if (value === undefined) { + continue; + } - const entries = transformEntries(resolve(slots[property])); + const resolved = resolve(value); - if (entries !== undefined) { - composed = [...(composed ?? []), ...entries]; + // A property that resolves to no value is `none` (css-variables-1 §3.1) + if (resolved !== undefined && resolved !== null) { + pushEntries((composed ??= []), resolved); + } } - } - return composed; + if (composed !== undefined) { + target.transform = composed; + } + } } -// A property that resolves to no value is `none` (css-variables-1 §3.1) -function transformEntries(value: unknown): unknown[] | undefined { - return value === undefined || value === null - ? undefined - : [value].flat(Number.POSITIVE_INFINITY); +// A resolver returns a group for a two-axis function, so entries are spread into the list +function pushEntries(entries: unknown[], value: unknown) { + if (Array.isArray(value)) { + for (const entry of value) pushEntries(entries, entry); + } else { + entries.push(value); + } } export function applyDeclarations( @@ -199,10 +211,12 @@ export function applyDeclarations( inlineVariables: InlineVariable, inheritedVariables: VariableContextValue, delayedStyles: (() => void)[] = [], - recordTransform: RecordTransform = () => undefined, + transforms: TransformRecord[] = [], guards: RenderGuard[] = [], target: Record = {}, topLevelTarget = target, + path: string | readonly string[] = "style", + important = false, ) { const originalTarget = target; @@ -262,7 +276,7 @@ export function applyDeclarations( } if (target === originalTarget && isTransformProperty(prop)) { - recordTransform(prop, value); + transforms.push({ target, path, important, property: prop, value }); continue; } From 00494c50b9b3535baaf3c8a710a07ab70baa21b9 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 11 Nov 2026 15:08:35 -0500 Subject: [PATCH 10/17] test(transforms): render a written translate() pair and translateZ() On main, `transform: translate(10px, 20px)` compiles its second offset a level too deep, and `translateZ()` compiles to an empty entry, so React Native's processTransform throws on both in development. The compiler fix here covers them, but only through a var() fallback, or scale3d(), scaleZ() and matrix(), so these render the written forms. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/native/transform.test.tsx | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 7b7edeaf..7e269eef 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -240,12 +240,22 @@ describe("one property per entry", () => { "transform: scale3d(1, 2, 3);", "transform: scaleZ(2);", "transform: matrix(1, 0, 0, 1, 0, 0);", + "transform: translateZ(10px);", ])("%s renders no entry", (declaration) => { expect(renderStyle(`.my-class { ${declaration} }`)).toStrictEqual({ transform: [], }); }); + test.each([ + ["translate(10px, 20px)", [{ translateX: 10 }, { translateY: 20 }]], + ["translate(-50%, -50%)", [{ translateX: "-50%" }, { translateY: "-50%" }]], + ] as const)("transform: %s renders an entry per axis", (value, transform) => { + expect(renderStyle(`.my-class { transform: ${value}; }`)).toStrictEqual({ + transform, + }); + }); + test("a translate() pair in a var() fallback renders an entry per axis", () => { expect( renderStyle( @@ -261,6 +271,12 @@ describe("one property per entry", () => { ), ).toStrictEqual({ transform: [{ translateX: 10 }] }); }); + + test("translateZ() leaves its neighbour", () => { + expect( + renderStyle(`.my-class { transform: translateZ(10px) rotate(45deg); }`), + ).toStrictEqual({ transform: [{ rotate: "45deg" }] }); + }); }); // Chromium 153, Firefox 155 and WebKit 26.6: a function left without a valid argument makes the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) From a7b029e18cc7e405ec04d36ee9f06654439ae647 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 11 Nov 2026 15:09:48 -0500 Subject: [PATCH 11/17] refactor(compiler): add the first-pass transform visitor beside the variable counter The individual transform properties are unparsed in every compile, while variables are counted only when they are inlined. Keep the counting block as it was, named, and add a Declaration visitor that runs it and then unparses, instead of restructuring the block around the new step. Also leaves parseScaleValue's parameter named as on main; renaming it is unrelated to the fix. Co-Authored-By: Claude Opus 5.5 --- src/compiler/compiler.ts | 46 ++++++++++++++++++++---------------- src/compiler/declarations.ts | 6 ++--- 2 files changed, 28 insertions(+), 24 deletions(-) diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index 6cb46729..9082f589 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -5,6 +5,7 @@ import { debug } from "debug"; import { type ContainerRule, type CustomAtRules, + type Declaration, type MediaRule, type ParsedComponent, type PropertyRule, @@ -191,29 +192,32 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { }; } - const exclusionList: string[] = - options.inlineVariables === false - ? [] - : (options.inlineVariables?.exclude ?? []); + let countVariable: ((decl: Declaration) => void) | undefined; - firstPassVisitor.Declaration = (decl) => { - if ( - options.inlineVariables !== false && - decl.property === "custom" && - decl.value.name.startsWith("--") && - !exclusionList.includes(decl.value.name) - ) { - const entry = vars.get(decl.value.name) ?? { - count: 0, - value: [ - ...decl.value.value, - { type: "token", value: { type: "white-space", value: " " } }, - ], - }; - entry.count++; - vars.set(decl.value.name, entry); - } + if (options.inlineVariables !== false) { + const exclusionList: string[] = options.inlineVariables?.exclude ?? []; + + countVariable = (decl) => { + if ( + decl.property === "custom" && + decl.value.name.startsWith("--") && + !exclusionList.includes(decl.value.name) + ) { + const entry = vars.get(decl.value.name) ?? { + count: 0, + value: [ + ...decl.value.value, + { type: "token", value: { type: "white-space", value: " " } }, + ], + }; + entry.count++; + vars.set(decl.value.name, entry); + } + }; + } + firstPassVisitor.Declaration = (decl) => { + countVariable?.(decl); return unparseIndividualTransform(decl); }; diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 23154dd5..3a381447 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -887,15 +887,15 @@ function parseScale( } export function parseScaleValue( - scale: Scale, + translate: Scale, prop: keyof Extract, builder: StylesheetBuilder, ): StyleDescriptor { - if (scale === "none") { + if (translate === "none") { return 1; } - return parseLength(scale[prop], builder); + return parseLength(translate[prop], builder); } function parseLetterSpacing( From 675f24f96306f6b2a4d48a9837641d58a90760d9 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 11 Nov 2026 15:11:11 -0500 Subject: [PATCH 12/17] refactor(compiler): leave a calc() translate parsed instead of re-tokenizing it The first-pass workaround rebuilt a calc() from lightningcss's calculation tree only so that the second pass could warn about it and ignore it: React Native takes no calc(). A translate holding one now stays parsed. Alone in its rule it reaches the same warning. Beside a transform, lightningcss folds it into a translate3d() that the compiler drops either way, so the rendered style is the same and only that warning is lost. Tailwind writes its translate with var(), which is already unparsed, so it never takes this path. With calculation.ts gone, tokens.ts had one reader, so what it still needs moves into individual-transforms.ts. Each component is one token, so the space join takes tokens rather than groups. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/compiler/compiler.test.tsx | 4 +- src/compiler/calculation.ts | 145 ----------------------- src/compiler/individual-transforms.ts | 107 +++++++++++------ src/compiler/tokens.ts | 60 ---------- 4 files changed, 74 insertions(+), 242 deletions(-) delete mode 100644 src/compiler/calculation.ts delete mode 100644 src/compiler/tokens.ts diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index fc23072e..28779964 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -386,9 +386,11 @@ test("a transform value the compiler cannot convert is ignored, with a warning", const compiled = compile(` .my-class { transform: translate(10px, 1cap); - translate: calc(1em + 5px) 5px; rotate: 1grad; scale: 2; +} +.alone { + translate: calc(1em + 5px) 5px; }`); expect(compiled.stylesheet()).toStrictEqual({ diff --git a/src/compiler/calculation.ts b/src/compiler/calculation.ts deleted file mode 100644 index 3f7cc715..00000000 --- a/src/compiler/calculation.ts +++ /dev/null @@ -1,145 +0,0 @@ -import type { - DimensionPercentageFor_LengthValue, - Length, - RoundingStrategy, - TokenOrValue, -} from "lightningcss"; - -import { - commaSeparated, - delimiterToken, - functionToken, - identifierToken, - lengthToken, - numberToken, - percentageToken, - WHITESPACE_TOKEN, -} from "./tokens"; - -export type LengthLeaf = Length | DimensionPercentageFor_LengthValue; - -/** lightningcss's calculation tree for a length, as it holds one it could not fold. */ -export type LengthCalculation = - | { readonly type: "value"; readonly value: LengthLeaf } - | { readonly type: "number"; readonly value: number } - | { - readonly type: "sum"; - readonly value: readonly [LengthCalculation, LengthCalculation]; - } - | { - readonly type: "product"; - readonly value: readonly [number, LengthCalculation]; - } - | { readonly type: "function"; readonly value: LengthMathFunction }; - -export type LengthMathFunction = - | { - readonly type: "calc" | "abs" | "sign"; - readonly value: LengthCalculation; - } - | { - readonly type: "min" | "max" | "hypot"; - readonly value: readonly LengthCalculation[]; - } - | { - readonly type: "clamp"; - readonly value: readonly [ - LengthCalculation, - LengthCalculation, - LengthCalculation, - ]; - } - | { - readonly type: "round"; - readonly value: readonly [ - RoundingStrategy, - LengthCalculation, - LengthCalculation, - ]; - } - | { - readonly type: "rem" | "mod"; - readonly value: readonly [LengthCalculation, LengthCalculation]; - }; - -export function lengthLeafTokens(leaf: LengthLeaf): TokenOrValue[] { - switch (leaf.type) { - case "value": - case "dimension": - return [lengthToken(leaf.value)]; - case "percentage": - return [percentageToken(leaf.value)]; - case "calc": - return [calculationToken(leaf.value)]; - } -} - -/** The one token a calculation is written as: its own math function, or `calc()` around anything else. */ -export function calculationToken(calculation: LengthCalculation): TokenOrValue { - return calculation.type === "function" - ? mathFunctionToken(calculation.value) - : functionToken("calc", calculationTokens(calculation)); -} - -function calculationTokens(calculation: LengthCalculation): TokenOrValue[] { - switch (calculation.type) { - case "value": - return lengthLeafTokens(calculation.value); - case "number": - return [numberToken(calculation.value)]; - case "sum": - return [ - ...calculationTokens(calculation.value[0]), - WHITESPACE_TOKEN, - delimiterToken("+"), - WHITESPACE_TOKEN, - ...calculationTokens(calculation.value[1]), - ]; - case "product": { - const [factor, operand] = calculation.value; - - return [ - numberToken(factor), - WHITESPACE_TOKEN, - delimiterToken("*"), - WHITESPACE_TOKEN, - ...(operand.type === "sum" - ? [calculationToken(operand)] - : calculationTokens(operand)), - ]; - } - case "function": - return [mathFunctionToken(calculation.value)]; - } -} - -function mathFunctionToken(math: LengthMathFunction): TokenOrValue { - switch (math.type) { - case "calc": - case "abs": - case "sign": - return functionToken(math.type, calculationTokens(math.value)); - case "min": - case "max": - case "hypot": - case "clamp": - case "rem": - case "mod": - return functionToken( - math.type, - commaSeparated(math.value.map(calculationTokens)), - ); - case "round": { - const [strategy, value, interval] = math.value; - - return functionToken( - "round", - commaSeparated([ - [identifierToken(strategy)], - calculationTokens(value), - calculationTokens(interval), - ]), - ); - } - } -} diff --git a/src/compiler/individual-transforms.ts b/src/compiler/individual-transforms.ts index 0086b5bf..2687cbcf 100644 --- a/src/compiler/individual-transforms.ts +++ b/src/compiler/individual-transforms.ts @@ -1,5 +1,7 @@ import type { Declaration, + DimensionPercentageFor_LengthValue, + Length, NumberOrPercentage, Rotate, Scale, @@ -7,14 +9,6 @@ import type { Translate, } from "lightningcss"; -import { lengthLeafTokens } from "./calculation"; -import { - identifierToken, - numberToken, - percentageToken, - spaceSeparated, -} from "./tokens"; - /** * Carries `translate`, `rotate` and `scale` across the first pass as the tokens * they were written as. lightningcss before @@ -26,14 +20,16 @@ export function unparseIndividualTransform( declaration: Declaration, ): Declaration | undefined { switch (declaration.property) { - case "translate": - return { - property: "unparsed", - value: { - propertyId: { property: "translate" }, - value: translateTokens(declaration.value), - }, - }; + case "translate": { + const value = translateTokens(declaration.value); + + return value + ? { + property: "unparsed", + value: { propertyId: { property: "translate" }, value }, + } + : undefined; + } case "rotate": return { property: "unparsed", @@ -55,40 +51,79 @@ export function unparseIndividualTransform( } } -function numberOrPercentageTokens(value: NumberOrPercentage): TokenOrValue[] { +const WHITESPACE_TOKEN: TokenOrValue = { + type: "token", + value: { type: "white-space", value: " " }, +}; + +const NONE_TOKENS: TokenOrValue[] = [ + { type: "token", value: { type: "ident", value: "none" } }, +]; + +function spaceSeparated(tokens: TokenOrValue[]): TokenOrValue[] { + return tokens.flatMap((token, index) => + index === 0 ? [token] : [WHITESPACE_TOKEN, token], + ); +} + +function numberToken(value: number): TokenOrValue { + return { type: "token", value: { type: "number", value } }; +} + +// lightningcss holds a percentage as its fraction, in a token as in a value: 50% is 0.5 +function percentageToken(value: number): TokenOrValue { + return { type: "token", value: { type: "percentage", value } }; +} + +function numberOrPercentageToken(value: NumberOrPercentage): TokenOrValue { + return value.type === "number" + ? numberToken(value.value) + : percentageToken(value.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 "number": - return [numberToken(value.value)]; + case "value": + case "dimension": + return { type: "length", value: value.value }; case "percentage": - return [percentageToken(value.value)]; + return percentageToken(value.value); + case "calc": + return undefined; } } -function translateTokens(value: Translate): TokenOrValue[] { - return value === "none" - ? [identifierToken("none")] - : spaceSeparated([ - lengthLeafTokens(value.x), - lengthLeafTokens(value.y), - lengthLeafTokens(value.z), - ]); +// A translate holding a calc() stays parsed, so it reaches the compiler's warning unless lightningcss folds it into a transform beside it +function translateTokens(value: Translate): TokenOrValue[] | undefined { + if (value === "none") { + return NONE_TOKENS; + } + + const x = lengthToken(value.x); + const y = lengthToken(value.y); + const z = lengthToken(value.z); + + return x && y && z ? spaceSeparated([x, y, z]) : undefined; } function rotateTokens(value: Rotate): TokenOrValue[] { return spaceSeparated([ - [numberToken(value.x)], - [numberToken(value.y)], - [numberToken(value.z)], - [{ type: "angle", value: value.angle }], + numberToken(value.x), + numberToken(value.y), + numberToken(value.z), + { type: "angle", value: value.angle }, ]); } function scaleTokens(value: Scale): TokenOrValue[] { return value === "none" - ? [identifierToken("none")] + ? NONE_TOKENS : spaceSeparated([ - numberOrPercentageTokens(value.x), - numberOrPercentageTokens(value.y), - numberOrPercentageTokens(value.z), + numberOrPercentageToken(value.x), + numberOrPercentageToken(value.y), + numberOrPercentageToken(value.z), ]); } diff --git a/src/compiler/tokens.ts b/src/compiler/tokens.ts deleted file mode 100644 index 1ca251b9..00000000 --- a/src/compiler/tokens.ts +++ /dev/null @@ -1,60 +0,0 @@ -import type { LengthValue, TokenOrValue } from "lightningcss"; - -export const WHITESPACE_TOKEN: TokenOrValue = { - type: "token", - value: { type: "white-space", value: " " }, -}; - -export const COMMA_TOKEN: TokenOrValue = { - type: "token", - value: { type: "comma" }, -}; - -export function delimiterToken(value: string): TokenOrValue { - return { type: "token", value: { type: "delim", value } }; -} - -export function identifierToken(value: string): TokenOrValue { - return { type: "token", value: { type: "ident", value } }; -} - -export function numberToken(value: number): TokenOrValue { - return { type: "token", value: { type: "number", value } }; -} - -/** lightningcss holds a percentage as its fraction, in a token as in a value: 50% is 0.5. */ -export function percentageToken(fraction: number): TokenOrValue { - return { type: "token", value: { type: "percentage", value: fraction } }; -} - -export function lengthToken(value: LengthValue): TokenOrValue { - return { type: "length", value }; -} - -export function functionToken( - name: string, - argumentTokens: TokenOrValue[], -): TokenOrValue { - return { type: "function", value: { name, arguments: argumentTokens } }; -} - -function joinTokens( - groups: readonly TokenOrValue[][], - separator: readonly TokenOrValue[], -): TokenOrValue[] { - return groups.flatMap((group, index) => - index === 0 ? group : [...separator, ...group], - ); -} - -export function spaceSeparated( - groups: readonly TokenOrValue[][], -): TokenOrValue[] { - return joinTokens(groups, [WHITESPACE_TOKEN]); -} - -export function commaSeparated( - groups: readonly TokenOrValue[][], -): TokenOrValue[] { - return joinTokens(groups, [COMMA_TOKEN, WHITESPACE_TOKEN]); -} From d5de42ecb9ad0067bab2f48b79f5c171e2000c8c Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Wed, 11 Nov 2026 15:26:57 -0500 Subject: [PATCH 13/17] perf(native): compose and read transforms without per-render collections On Hermes, transforms still cost 19-44% more than on main, in the calculate-props cascade and in the readers it calls on every render: - composeTransforms keyed a Map by a joined path string and kept each slot set as an object tested with `in`. Records now carry a slot index, and a style target's 4 normal and 4 !important slots are an array, found by a scan of the targets, which is almost always one. - The transform shorthand flattened, filtered and tested its list in three passes. One recursive pass now flattens it, skips undefined and `initial`, and stops at the first value that is not an entry. - resolveOperands mapped then flat-mapped through closures, and the individual properties sliced their operands to drop a z. The operands are now pushed in one loop, and the pairs read a count instead of a copy. Destructuring is gone from the readers, since Hermes runs it through an iterator helper. Output is unchanged. On Hermes, against main, ns per calculateProps call, 5 processes per side: tw translate-x-4 rotate-45 scale-110 +18.7% -> -1.9% tw rotate-45 skew-x-6 +5.5% -> -6.5% translate: 10px 20px (written) +3.6% -> -17.3% transform: translate() rotate() +39.3% -> +4.0% tw transform, one set +24.7% -> +6.9% transform: scale(var(--s)) +37.6% -> +7.5% transform: var(--t) two fns +43.1% -> +8.7% translate(var(--x), var(--y)) +43.6% -> +12.0% The cases left above main are transform functions whose output main nests in a way React Native refuses. Rules with no transform are flat. Co-Authored-By: Claude Opus 5.5 --- src/native/styles/calculate-props.ts | 129 +++++++++++------- .../styles/functions/transform-functions.ts | 59 ++++---- src/native/styles/shorthands/transform.ts | 33 +++-- 3 files changed, 140 insertions(+), 81 deletions(-) diff --git a/src/native/styles/calculate-props.ts b/src/native/styles/calculate-props.ts index 4ce33924..c06dde03 100644 --- a/src/native/styles/calculate-props.ts +++ b/src/native/styles/calculate-props.ts @@ -103,36 +103,53 @@ export function calculateProps( } // css-transforms-2 §6: an element's transform is its `translate`, then its `rotate`, then its `scale`, then its `transform` list -const TRANSFORM_PROPERTIES = [ - "translate", - "rotate", - "scale", - "transform", -] as const; - -type TransformProperty = (typeof TRANSFORM_PROPERTIES)[number]; - -// Compares, not TRANSFORM_PROPERTIES.includes(): this runs for every dynamic declaration -function isTransformProperty(prop: string | number): prop is TransformProperty { - return ( - prop === "transform" || - prop === "translate" || - prop === "rotate" || - prop === "scale" - ); +const TRANSFORM_SLOTS = 4; + +// A transform property's cascade slot in composition order, or -1. This runs for every dynamic declaration +function transformSlot(prop: string | number): number { + switch (prop) { + case "translate": + return 0; + case "rotate": + return 1; + case "scale": + return 2; + case "transform": + return 3; + default: + return -1; + } } -type TransformSlots = Partial>; - /** A transform property's declaration, kept until every rule has been walked */ interface TransformRecord { readonly target: Record; readonly path: string | readonly string[]; readonly important: boolean; - readonly property: TransformProperty; + readonly slot: number; readonly value: StyleDescriptor; } +/** One style target's slots: the normal ones, then the !important ones */ +interface TransformGroup { + readonly path: string | readonly string[]; + target: Record; + readonly slots: (StyleDescriptor | undefined)[]; +} + +function samePath( + a: string | readonly string[], + b: string | readonly string[], +): boolean { + if (a === b) return true; + if (typeof a === "string" || typeof b === "string") return false; + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; +} + /** * Each transform property of each style target is a cascade slot of its own, * and the slots compose into one `transform`. Records arrive in cascade @@ -143,40 +160,54 @@ function composeTransforms( records: readonly TransformRecord[], resolve: (value: StyleDescriptor) => unknown, ) { - const byPath = new Map< - string, - { target: Record; normal: TransformSlots; important: TransformSlots } - >(); - - for (const record of records) { - const pathKey = - typeof record.path === "string" ? record.path : record.path.join("\0"); - let slots = byPath.get(pathKey); - - if (slots === undefined) { - slots = { target: record.target, normal: {}, important: {} }; - byPath.set(pathKey, slots); + // Almost always one group, so a scan beats keying a Map by path + const groups: TransformGroup[] = []; + + for (let r = 0; r < records.length; r++) { + const record = records[r]!; + let group: TransformGroup | undefined; + + for (let g = 0; g < groups.length; g++) { + if (samePath(groups[g]!.path, record.path)) { + group = groups[g]; + break; + } + } + + if (group === undefined) { + group = { + path: record.path, + target: record.target, + slots: [ + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + ], + }; + groups.push(group); } if (record.important) { // The important target is merged over the normal one, so it takes the composed list - slots.target = record.target; - slots.important[record.property] = record.value; + group.target = record.target; + group.slots[record.slot + TRANSFORM_SLOTS] = record.value; } else { - slots.normal[record.property] = record.value; + group.slots[record.slot] = record.value; } } - for (const { target, normal, important } of byPath.values()) { + for (let g = 0; g < groups.length; g++) { + const group = groups[g]!; let composed: unknown[] | undefined; - for (const property of TRANSFORM_PROPERTIES) { - const value = - property in important - ? important[property] - : property in normal - ? normal[property] - : undefined; + for (let slot = 0; slot < TRANSFORM_SLOTS; slot++) { + const important = group.slots[slot + TRANSFORM_SLOTS]; + const value = important !== undefined ? important : group.slots[slot]; if (value === undefined) { continue; @@ -191,7 +222,7 @@ function composeTransforms( } if (composed !== undefined) { - target.transform = composed; + group.target.transform = composed; } } } @@ -199,7 +230,7 @@ function composeTransforms( // A resolver returns a group for a two-axis function, so entries are spread into the list function pushEntries(entries: unknown[], value: unknown) { if (Array.isArray(value)) { - for (const entry of value) pushEntries(entries, entry); + for (let i = 0; i < value.length; i++) pushEntries(entries, value[i]); } else { entries.push(value); } @@ -275,8 +306,10 @@ export function applyDeclarations( prop = propPath; } - if (target === originalTarget && isTransformProperty(prop)) { - transforms.push({ target, path, important, property: prop, value }); + const slot = target === originalTarget ? transformSlot(prop) : -1; + + if (slot !== -1) { + transforms.push({ target, path, important, slot, value }); continue; } diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index 621abd51..d5344fc4 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -11,12 +11,14 @@ import { scaleFactor } from "../scale-factor"; // A component left without a valid value makes the declaration invalid at computed-value time (css-variables-1 §3.1), which null carries export const scale: StyleFunctionResolver = (resolveValue, descriptor) => { - return scalePair(resolveOperands(resolveValue, descriptor[2])); + const operands = resolveOperands(resolveValue, descriptor[2]); + + return scalePair(operands, operands.length); }; export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { const operands = resolveOperands(resolveValue, descriptor[2]); - const [angle] = operands; + const angle = operands[0]; return operands.length === 1 && isTransformComponent(angle) ? { rotate: angle } @@ -24,7 +26,9 @@ export const rotate: StyleFunctionResolver = (resolveValue, descriptor) => { }; export const translate: StyleFunctionResolver = (resolveValue, descriptor) => { - return translatePair(resolveOperands(resolveValue, descriptor[2])); + const operands = resolveOperands(resolveValue, descriptor[2]); + + return translatePair(operands, operands.length); }; // css-transforms-2 §3: `translate: none | [ ?]?`, and React Native has no z axis to move along @@ -41,7 +45,7 @@ export const individualTranslate: StyleFunctionResolver = ( const z = operands.length > 2 ? operands[2] : 0; return operands.length <= 3 && typeof z === "number" - ? translatePair(operands.slice(0, 2)) + ? translatePair(operands, Math.min(operands.length, 2)) : null; }; @@ -59,7 +63,7 @@ export const individualScale: StyleFunctionResolver = ( const z = operands.length > 2 ? operands[2] : 1; return operands.length <= 3 && scaleFactor(z) !== null - ? scalePair(operands.slice(0, 2)) + ? scalePair(operands, Math.min(operands.length, 2)) : null; }; @@ -71,7 +75,7 @@ export const individualRotate: StyleFunctionResolver = ( const operands = resolveOperands(resolveValue, descriptor[2]); if (operands.length === 1) { - const [angle] = operands; + const angle = operands[0]; if (isNoneKeyword(angle)) { return { rotateZ: "0deg" }; @@ -146,11 +150,12 @@ function isNoneKeyword(value: unknown): boolean { return typeof value === "string" && value.toLowerCase() === "none"; } -function scalePair(operands: readonly unknown[]): unknown { +// The first `count` operands, so a caller can leave out a z without copying the list +function scalePair(operands: readonly unknown[], count: number): unknown { const x = scaleFactor(operands[0]); - const y = operands.length > 1 ? scaleFactor(operands[1]) : x; + const y = count > 1 ? scaleFactor(operands[1]) : x; - if (operands.length > 2 || x === null || y === null) { + if (count > 2 || x === null || y === null) { return null; } @@ -158,15 +163,11 @@ function scalePair(operands: readonly unknown[]): unknown { } // `translate(x)` is `translate(x, 0)` (css-transforms-1 §9) -function translatePair(operands: readonly unknown[]): unknown { +function translatePair(operands: readonly unknown[], count: number): unknown { const x = operands[0]; - const y = operands.length > 1 ? operands[1] : 0; + const y = count > 1 ? operands[1] : 0; - if ( - operands.length > 2 || - !isTransformComponent(x) || - !isTransformComponent(y) - ) { + if (count > 2 || !isTransformComponent(x) || !isTransformComponent(y)) { return null; } @@ -191,14 +192,26 @@ function resolveOperands( resolveValue: SimpleResolveValue, args: StyleDescriptor, ): unknown[] { - // A lone var()'s comma-separated list supplies its items as the operands - const resolved = isStyleDescriptorArray(args) - ? args.map((arg) => argument(resolveValue, arg)) - : [commaListItems(resolveValue(args))]; + const operands: unknown[] = []; - return resolved.flatMap((operand): readonly unknown[] => - Array.isArray(operand) ? operand : [operand], - ); + if (isStyleDescriptorArray(args)) { + for (const arg of args) { + pushOperand(operands, argument(resolveValue, arg)); + } + } else { + // A lone var()'s comma-separated list supplies its items as the operands + pushOperand(operands, commaListItems(resolveValue(args))); + } + + return operands; +} + +function pushOperand(operands: unknown[], operand: unknown) { + if (Array.isArray(operand)) { + for (const item of operand as unknown[]) operands.push(item); + } else { + operands.push(operand); + } } function isTransformComponent(value: unknown): value is string | number { diff --git a/src/native/styles/shorthands/transform.ts b/src/native/styles/shorthands/transform.ts index 2622859f..fab9f169 100644 --- a/src/native/styles/shorthands/transform.ts +++ b/src/native/styles/shorthands/transform.ts @@ -8,18 +8,31 @@ export const transform: StyleFunctionResolver = ( resolveValue, transformDescriptor, ) => { - const transforms = resolveValue(transformDescriptor[2]); - - // A group from a resolver and the list a var() fallback holds each nest a level, while React Native takes a flat list of single-key objects - const resolved: unknown[] = [transforms].flat(Number.POSITIVE_INFINITY); - const entries = resolved.filter( - (transform) => transform !== undefined && transform !== "initial", - ); + const entries: unknown[] = []; // Anything but a transform entry, null included, leaves the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) - return entries.every(isTransformEntry) ? entries : []; + return appendEntries(entries, resolveValue(transformDescriptor[2])) + ? entries + : []; }; -function isTransformEntry(value: unknown): boolean { - return typeof value === "object" && value !== null; +// A group from a resolver and the list a var() fallback holds each nest a level, while React Native takes a flat list of single-key objects. Returns false for anything but an entry +function appendEntries(entries: unknown[], value: unknown): boolean { + if (Array.isArray(value)) { + for (const item of value as unknown[]) { + if (!appendEntries(entries, item)) return false; + } + return true; + } + + if (value === undefined || value === "initial") { + return true; + } + + if (typeof value === "object" && value !== null) { + entries.push(value); + return true; + } + + return false; } From 15f6ee9b7df3b3783397c6d2106d4e77f0461063 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 13:20:04 -0500 Subject: [PATCH 14/17] refactor(transforms): keep only the longhand grammar Tailwind reaches The grammar commit gave translate, rotate and scale their own grammars: an optional z, a none keyword substituted from a var(), and for rotate an axis keyword or a vector beside its angle, reversed about a negative axis, with an oblique vector warned and ignored. It added a shared rotationAxis() utility and a warning for a scale along z. Tailwind needs one part of it. scale-3d and scale-z-* write a three-value `scale: var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)`, as its 3D translate utilities do for translate, so individualTranslate and individualScale keep taking an optional z. The rest only matters for CSS written by hand: Tailwind writes `rotate: ` (rotate-x-* goes through transform:) and writes none literally, which the compiler already reads. So this removes individualRotate, the substituted none keyword, rotation-axis.ts, the vector handling in parseRotate and the scale z warning. A rotate longhand from a var() reads through rotate() again, as `{ rotate: angle }`, which React Native treats as rotateZ. Without the keyword handling, a none from a var() reached React Native as { translateX: "none" } or { rotate: "none" }, which it throws on. isTransformComponent now takes only a number or a dimension, so a keyword makes the property none: the identity, as browsers render it. 133 Tailwind utilities and combinations render identically before and after, and every result passes React Native's processTransform; no hand-written case throws either. The 13 test cases for the removed grammar, and the compiler test for its warnings, go. The removed grammar is kept as a patch for later. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D4jU1dW7KKQntNrr9i2xGi --- src/__tests__/compiler/compiler.test.tsx | 67 ----------- src/__tests__/native/transform.test.tsx | 39 +------ src/compiler/declarations.ts | 62 ++++------- .../styles/functions/transform-functions.ts | 105 ++---------------- src/utilities/index.ts | 1 - src/utilities/rotation-axis.ts | 37 ------ 6 files changed, 38 insertions(+), 273 deletions(-) delete mode 100644 src/utilities/rotation-axis.ts diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index 28779964..a1a6906b 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -424,73 +424,6 @@ test("a transform value the compiler cannot convert is ignored, with a warning", }); }); -test("a scale along z or a rotate about an oblique axis warns", () => { - const compiled = compile(` -.my-class { - scale: 2 3 400%; - rotate: 1 1 0 45deg; -} -.unwarned { - scale: 2 3 100%; - translate: 10px 20px 30px; - rotate: 0 0 0 45deg; -}`); - - expect(compiled.stylesheet()).toStrictEqual({ - s: [ - [ - "my-class", - [ - { - d: [ - [ - [ - [{}, "scaleX", 2], - [{}, "scaleY", 3], - ], - "scale", - ], - ], - s: [1, 1], - }, - ], - ], - [ - "unwarned", - [ - { - d: [ - [ - [ - [{}, "scaleX", 2], - [{}, "scaleY", 3], - ], - "scale", - ], - [ - [ - [{}, "translateX", 10], - [{}, "translateY", 20], - ], - "translate", - ], - [[{}, "rotateZ", "0deg"], "rotate"], - ], - s: [2, 1], - }, - ], - ], - ], - }); - - expect(compiled.warnings()).toStrictEqual({ - values: { - scale: ["400%"], - rotate: ["1 1 0 45deg"], - }, - }); -}); - test("simplifies rem", () => { const compiled = compile(`.test { border-width: calc(10rem + 2px); diff --git a/src/__tests__/native/transform.test.tsx b/src/__tests__/native/transform.test.tsx index 7e269eef..6cfeeda7 100644 --- a/src/__tests__/native/transform.test.tsx +++ b/src/__tests__/native/transform.test.tsx @@ -410,24 +410,12 @@ test.each([ }, ); -// Chromium 153 and Firefox 155 rotate about the axis a vector names, reversing the angle about a negative axis, and rotate by none about the zero vector; WebKit 26.6 ignores the direction of a z axis +// Chromium 153, Firefox 155 and WebKit 26.6 rotate about the axis a keyword or a vector along one axis names test.each([ - ["rotate: 0 0 -1 45deg;", [{ rotateZ: "-45deg" }]], - ["--r: 0 0 -1 45deg; rotate: var(--r);", [{ rotateZ: "-45deg" }]], - ["rotate: -1 0 0 45deg;", [{ rotateX: "-45deg" }]], - ["--r: -1 0 0 45deg; rotate: var(--r);", [{ rotateX: "-45deg" }]], ["rotate: 0 0 2 45deg;", [{ rotateZ: "45deg" }]], - ["--r: 0 0 2 45deg; rotate: var(--r);", [{ rotateZ: "45deg" }]], ["rotate: x 45deg;", [{ rotateX: "45deg" }]], - ["--r: x 45deg; rotate: var(--r);", [{ rotateX: "45deg" }]], ["rotate: 45deg y;", [{ rotateY: "45deg" }]], - ["--r: 45deg y; rotate: var(--r);", [{ rotateY: "45deg" }]], - ["--r: 20deg; rotate: var(--r);", [{ rotateZ: "20deg" }]], - ["--r: x; rotate: var(--r) 45deg;", [{ rotateX: "45deg" }]], - ["--r: 0 0 -1; rotate: var(--r) 45deg;", [{ rotateZ: "-45deg" }]], - ["rotate: 0 0 0 45deg;", [{ rotateZ: "0deg" }]], - ["--r: 0 0 0 45deg; rotate: var(--r);", [{ rotateZ: "0deg" }]], - ["--r: none; rotate: var(--r);", [{ rotateZ: "0deg" }]], + ["--r: 20deg; rotate: var(--r);", [{ rotate: "20deg" }]], ] as const)("%s rotates about the axis it names", (declarations, transform) => { expect( renderStyle( @@ -447,12 +435,9 @@ test.each([ "--t: 20px 30px; translate: 10px var(--t);", [{ translateX: 10 }, { translateY: 20 }], ], - ["--t: none; translate: var(--t);", [{ translateX: 0 }, { translateY: 0 }]], - ["--t: NONE; translate: var(--t);", [{ translateX: 0 }, { translateY: 0 }]], ["scale: 2 3 4;", [{ scaleX: 2 }, { scaleY: 3 }]], ["--s: 2 3 4; scale: var(--s);", [{ scaleX: 2 }, { scaleY: 3 }]], ["--s: 3 4; scale: 2 var(--s);", [{ scaleX: 2 }, { scaleY: 3 }]], - ["--s: none; scale: var(--s);", [{ scaleX: 1 }, { scaleY: 1 }]], ] as const)("%s renders its x and y", (declarations, transform) => { expect( renderStyle( @@ -498,23 +483,11 @@ test.each([ }); }); -// React Native's rotate keys turn only about an axis, so a rotate about a vector off every axis is ignored when written and none when substituted -test.each([ - ["rotate: 1 1 0 45deg;", [{ rotateZ: "10deg" }]], - ["--r: 1 1 0 45deg; rotate: var(--r);", []], -] as const)("%s rotates by none", (declarations, transform) => { - expect( - renderStyle( - `${decoy} .earlier { rotate: 10deg; } .my-class { ${declarations} }`, - ), - ).toStrictEqual(transform.length === 0 ? {} : { transform }); -}); - -// Chromium 153, Firefox 155 and WebKit 26.6: a later transform without a value replaces an earlier one, and is none (css-variables-1 §3.1) -test("transform: var(--missing) replaces an earlier rule's transform", () => { +// React Native's rotate keys turn only about an axis, so a substituted rotate about a vector off every axis is none +test("--r: 1 1 0 45deg; rotate: var(--r); rotates by none", () => { expect( renderStyle( - `${decoy} .earlier { transform: rotate(10deg); } .my-class { transform: var(--missing); }`, + `${decoy} .earlier { rotate: 10deg; } .my-class { --r: 1 1 0 45deg; rotate: var(--r); }`, ), - ).toStrictEqual({ transform: [] }); + ).toStrictEqual({}); }); diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 3a381447..1591d0ab 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -36,7 +36,7 @@ import type { UnresolvedColor, } from "lightningcss"; -import { isStyleFunction, negateAngle, rotationAxis } from "../utilities"; +import { isStyleFunction } from "../utilities"; import { isMappingProperty } from "./atRules"; import type { StyleDescriptor, @@ -102,9 +102,8 @@ const unparsedRuntimeParsing = new Set([ "translate", ]); -// css-transforms-2 §3: the individual transform properties each have a grammar of their own, which the transform function of the same name does not share +// css-transforms-2 §3: the translate and scale properties take an optional z, which the functions of the same name do not const INDIVIDUAL_TRANSFORM_RESOLVERS: ReadonlyMap = new Map([ - ["rotate", "individualRotate"], ["scale", "individualScale"], ["translate", "individualTranslate"], ]); @@ -836,50 +835,35 @@ function parseRotate( { value }: DeclarationType<"rotate">, builder: StylesheetBuilder, ) { - const rotation = rotationAxis(value.x, value.y, value.z); + const angle = parseAngle(value.angle, builder); + const rotations: TransformFunction[] = []; - switch (rotation.type) { - case "none": - builder.addDescriptor("rotate", [{}, "rotateZ", "0deg"]); - return; - case "axis": { - const angle = parseAngle(value.angle, builder); - - if (angle !== undefined) { - builder.addDescriptor("rotate", [ - {}, - rotation.rotation, - rotation.reversed ? negateAngle(angle) : angle, - ]); - } - return; - } - // React Native's rotate keys turn only about an axis, so a vector off every axis has none to take it - case "oblique": - builder.addWarning( - "value", - `${value.x} ${value.y} ${value.z} ${value.angle.value}${value.angle.type}`, - ); - return; - default: - rotation satisfies never; + if (value.x) { + rotations.push([{}, "rotateX", angle]); + } + + if (value.y) { + rotations.push([{}, "rotateY", angle]); + } + + if (value.z) { + rotations.push([{}, "rotateZ", angle]); + } + + if (hasUnconvertibleArgument(rotations)) { + return; } + + builder.addDescriptor( + "rotate", + rotations.length === 1 ? rotations[0] : rotations, + ); } function parseScale( { value }: DeclarationType<"scale">, builder: StylesheetBuilder, ) { - // React Native has no z axis to scale along, and lightningcss holds a percentage as its fraction - if (value !== "none" && value.z.value !== 1) { - builder.addWarning( - "value", - value.z.type === "percentage" - ? `${round(value.z.value * 100)}%` - : `${round(value.z.value)}`, - ); - } - builder.addDescriptor("scale", [ [{}, "scaleX", parseScaleValue(value, "x", builder)], [{}, "scaleY", parseScaleValue(value, "y", builder)], diff --git a/src/native/styles/functions/transform-functions.ts b/src/native/styles/functions/transform-functions.ts index d5344fc4..8c04a8a1 100644 --- a/src/native/styles/functions/transform-functions.ts +++ b/src/native/styles/functions/transform-functions.ts @@ -2,8 +2,6 @@ import type { StyleDescriptor } from "react-native-css/compiler"; import { commaListItems, isStyleDescriptorArray, - negateAngle, - rotationAxis, } from "react-native-css/utilities"; import type { SimpleResolveValue, StyleFunctionResolver } from "../resolve"; @@ -37,11 +35,6 @@ export const individualTranslate: StyleFunctionResolver = ( descriptor, ) => { const operands = resolveOperands(resolveValue, descriptor[2]); - - if (operands.length === 1 && isNoneKeyword(operands[0])) { - return [{ translateX: 0 }, { translateY: 0 }]; - } - const z = operands.length > 2 ? operands[2] : 0; return operands.length <= 3 && typeof z === "number" @@ -55,11 +48,6 @@ export const individualScale: StyleFunctionResolver = ( descriptor, ) => { const operands = resolveOperands(resolveValue, descriptor[2]); - - if (operands.length === 1 && isNoneKeyword(operands[0])) { - return [{ scaleX: 1 }, { scaleY: 1 }]; - } - const z = operands.length > 2 ? operands[2] : 1; return operands.length <= 3 && scaleFactor(z) !== null @@ -67,89 +55,6 @@ export const individualScale: StyleFunctionResolver = ( : null; }; -// css-transforms-2 §3: `rotate: none | | [x | y | z | {3}] && ` -export const individualRotate: StyleFunctionResolver = ( - resolveValue, - descriptor, -) => { - const operands = resolveOperands(resolveValue, descriptor[2]); - - if (operands.length === 1) { - const angle = operands[0]; - - if (isNoneKeyword(angle)) { - return { rotateZ: "0deg" }; - } - - return isTransformComponent(angle) ? { rotateZ: angle } : null; - } - - const axisIndex = operands.findIndex(isAxisKeyword); - - if (axisIndex !== -1) { - const axis = operands[axisIndex]; - const angle = operands[axisIndex === 0 ? 1 : 0]; - - return operands.length === 2 && - isAxisKeyword(axis) && - isTransformComponent(angle) - ? { [AXIS_ROTATIONS[axis]]: angle } - : null; - } - - const angleIndex = operands.length === 4 ? angleOperandIndex(operands) : -1; - const angle = operands[angleIndex]; - const [x, y, z] = operands.filter((_, index) => index !== angleIndex); - - if ( - angleIndex === -1 || - !isTransformComponent(angle) || - typeof x !== "number" || - typeof y !== "number" || - typeof z !== "number" - ) { - return null; - } - - const rotation = rotationAxis(x, y, z); - - switch (rotation.type) { - case "none": - return { rotateZ: "0deg" }; - case "axis": - return { - [rotation.rotation]: rotation.reversed ? negateAngle(angle) : angle, - }; - case "oblique": - return null; - default: - rotation satisfies never; - return null; - } -}; - -const AXIS_ROTATIONS = { - x: "rotateX", - y: "rotateY", - z: "rotateZ", -} as const; - -function isAxisKeyword(value: unknown): value is keyof typeof AXIS_ROTATIONS { - return value === "x" || value === "y" || value === "z"; -} - -// The angle of a vector rotation comes first or last, around three numbers -function angleOperandIndex(operands: readonly unknown[]): number { - const index = operands.findIndex((operand) => typeof operand === "string"); - - return index === 0 || index === operands.length - 1 ? index : -1; -} - -// `none` is the identity transform, and React Native refuses the keyword itself -function isNoneKeyword(value: unknown): boolean { - return typeof value === "string" && value.toLowerCase() === "none"; -} - // The first `count` operands, so a caller can leave out a z without copying the list function scalePair(operands: readonly unknown[], count: number): unknown { const x = scaleFactor(operands[0]); @@ -214,6 +119,14 @@ function pushOperand(operands: unknown[], operand: unknown) { } } +// A number, or a dimension such as "45deg" or "-50%". A keyword such as none +// from a var() is not one: React Native throws on it, and the property is none function isTransformComponent(value: unknown): value is string | number { - return typeof value === "string" || typeof value === "number"; + if (typeof value === "number") return true; + if (typeof value !== "string") return false; + + const first = value.charCodeAt(0); + return ( + (first >= 48 && first <= 57) || first === 45 || first === 43 || first === 46 + ); } diff --git a/src/utilities/index.ts b/src/utilities/index.ts index d9d7ee44..a421c7b6 100644 --- a/src/utilities/index.ts +++ b/src/utilities/index.ts @@ -2,4 +2,3 @@ export * from "./equality"; export * from "./specificity"; export * from "./style-descriptor"; export * from "./dot-notation.types"; -export * from "./rotation-axis"; diff --git a/src/utilities/rotation-axis.ts b/src/utilities/rotation-axis.ts deleted file mode 100644 index 9a4fa30a..00000000 --- a/src/utilities/rotation-axis.ts +++ /dev/null @@ -1,37 +0,0 @@ -export type RotationAxis = - | { readonly type: "none" } - | { - readonly type: "axis"; - readonly rotation: "rotateX" | "rotateY" | "rotateZ"; - readonly reversed: boolean; - } - | { readonly type: "oblique" }; - -// css-transforms-2 §3: a rotation turns about the direction its vector names, and the zero vector names none -export function rotationAxis(x: number, y: number, z: number): RotationAxis { - if (x === 0 && y === 0 && z === 0) { - return { type: "none" }; - } - - if (y === 0 && z === 0) { - return { type: "axis", rotation: "rotateX", reversed: x < 0 }; - } - - if (x === 0 && z === 0) { - return { type: "axis", rotation: "rotateY", reversed: y < 0 }; - } - - if (x === 0 && y === 0) { - return { type: "axis", rotation: "rotateZ", reversed: z < 0 }; - } - - return { type: "oblique" }; -} - -export function negateAngle(angle: string | number): string | number { - if (typeof angle === "number") { - return -angle; - } - - return angle.startsWith("-") ? angle.slice(1) : `-${angle}`; -} From 556cdc16c2a7986df02590cf63a9cf701a4e545b Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 13:33:32 -0500 Subject: [PATCH 15/17] perf(native): resolve a transform list's functions one by one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The transform shorthand resolved its argument list with resolveValue, which maps the list into a new array and filters that into another, and then copied the result into its list of entries. It now resolves each function in turn and appends it, so a transform: with two functions allocates one array instead of three. The output is unchanged. On Hermes (list-bench, against bench), the transform: cases go from +7–14% to −5…+3%: transform: translate(10px, 20px) rotate(45deg) +9.9% → −4.7%, translate(var(--x), var(--y)) +11.9% → −0.1%, transform: var(--t) +14.0% → +3.1%, scale(var(--s)) +12.2% → +0.5%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D4jU1dW7KKQntNrr9i2xGi --- src/native/styles/shorthands/transform.ts | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/native/styles/shorthands/transform.ts b/src/native/styles/shorthands/transform.ts index fab9f169..386c85f8 100644 --- a/src/native/styles/shorthands/transform.ts +++ b/src/native/styles/shorthands/transform.ts @@ -1,3 +1,5 @@ +import { isStyleDescriptorArray } from "react-native-css/utilities"; + import type { StyleFunctionResolver } from "../resolve"; /** @@ -8,12 +10,20 @@ export const transform: StyleFunctionResolver = ( resolveValue, transformDescriptor, ) => { + const args = transformDescriptor[2]; const entries: unknown[] = []; // Anything but a transform entry, null included, leaves the declaration invalid at computed-value time, so the transform is none (css-variables-1 §3.1) - return appendEntries(entries, resolveValue(transformDescriptor[2])) - ? entries - : []; + if (!isStyleDescriptorArray(args)) { + return appendEntries(entries, resolveValue(args)) ? entries : []; + } + + // Each function in turn, rather than resolving the list into an array to copy again + for (const arg of args) { + if (!appendEntries(entries, resolveValue(arg))) return []; + } + + return entries; }; // A group from a resolver and the list a var() fallback holds each nest a level, while React Native takes a flat list of single-key objects. Returns false for anything but an entry From d492b14681bbcdaaead4683a253375783b672816 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 15:45:22 -0500 Subject: [PATCH 16/17] test: read comma-separated arguments through translate(), not rotate() The list-separator fix tested that each one-token argument of a comma-separated list is unwrapped with rotate() over three arguments, which main read as rotateX, rotateY and rotateZ. The transform-properties fix reads rotate() by its grammar, which takes one angle, so three arguments are invalid and render none. translate() over two arguments tests the same unwrapping with a function that takes them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D4jU1dW7KKQntNrr9i2xGi --- src/__tests__/native/variable-lists.test.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/__tests__/native/variable-lists.test.tsx b/src/__tests__/native/variable-lists.test.tsx index 3088e33c..f8cfbdb1 100644 --- a/src/__tests__/native/variable-lists.test.tsx +++ b/src/__tests__/native/variable-lists.test.tsx @@ -397,9 +397,9 @@ test.each<[string, readonly unknown[], readonly unknown[]]>([ test.each<[string, StyleDescriptor, unknown]>([ [ - "rotate() over three comma-separated arguments", - [{}, "rotate", [["10deg"], ["20deg"], ["30deg"]]], - [{ rotateX: "10deg" }, { rotateY: "20deg" }, { rotateZ: "30deg" }], + "translate() over two comma-separated arguments", + [{}, "translate", [[10], [20]]], + [{ translateX: 10 }, { translateY: 20 }], ], ["join() over one value", [{}, "join", "#123"], "#123"], ])("%s reads each argument", (_, descriptor, expected) => { From ddf5648c400cc6e98ce4bd5f0bbc66ab92c8aced Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 20:08:26 -0500 Subject: [PATCH 17/17] perf(native): compose a lone transform declaration directly composeTransforms set up a group and its eight slots on every render, even when an element has only one transform property, which is the usual case. With one record there is nothing to compose, so resolve it and flatten it into the target's transform directly. Hermes list-bench against main (7-15 processes per side): - transform: var(--t): +17% -> +4% - translate(var(--x), var(--y)): +8% -> -1% - Tailwind transform, one set: +4% -> -3% - transform: scale(var(--s)): +3% -> -7% - written transform: translate() rotate(): +1% -> -8% - no other case moves V8 stays 39-53% faster than main on the transform cases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D4jU1dW7KKQntNrr9i2xGi --- src/native/styles/calculate-props.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/native/styles/calculate-props.ts b/src/native/styles/calculate-props.ts index c06dde03..fbb2172d 100644 --- a/src/native/styles/calculate-props.ts +++ b/src/native/styles/calculate-props.ts @@ -160,6 +160,19 @@ function composeTransforms( records: readonly TransformRecord[], resolve: (value: StyleDescriptor) => unknown, ) { + // One declaration, the usual case, has nothing to compose with + if (records.length === 1) { + const record = records[0]!; + const resolved = resolve(record.value); + + if (resolved !== undefined && resolved !== null) { + const composed: unknown[] = []; + pushEntries(composed, resolved); + record.target.transform = composed; + } + return; + } + // Almost always one group, so a scan beats keying a Map by path const groups: TransformGroup[] = [];