From f2ae910663b0593210ea6a97d0b72d3981348d9f Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 23:32:50 -0500 Subject: [PATCH 1/3] fix(native): layer a style prop's class, inline and !important values without copying the inline value A smaller alternative to #487, measured against it. On main: - an !important class on a single-key target other than style, such as contentContainerClassName, replaces both the class's other values and the inline value, because the !important pass merges that target with mergeDefinedProps; - the CSS-variable filter rebuilds every inline object, so an Animated.Value turns into a plain object nothing drives, and a Reanimated animated style's handle is copied with keys dropped; - the !important pass flattens the inline style into the class's, which folds an animated style's handle into a plain object, so Reanimated drops the class's values; - with the object form ({ target: "style" }), an inline [], { height: undefined } or vars() replaces the class's style; - a callback style beside a class becomes an array, where it never runs. Nativewind v4 gets each of these right. The filter now copies nothing until it finds a CSS variable and passes a class instance as it is; the !important pass layers the inline value instead of flattening it, on every single-key target; the object form keeps the class's value when the inline one filters to nothing; and #416's callback composition is carried over. flattenStyleArray loses its last callers and goes. On Hermes this allocates less per render than main: nothing for an inline style with no CSS variable, and a two-element array instead of a merged object under !important. Tests: #416's compiler/important.test.tsx, #487's rightIsInline and components changes, and style-layers-regressions.test.tsx, whose 9 cases all fail on main. Co-authored-by: Yevhenii Co-Authored-By: Claude Opus 5.5 --- src/__tests__/compiler/important.test.tsx | 78 ++++++ src/__tests__/native/components.test.tsx | 10 + src/__tests__/native/rightIsInline.test.tsx | 11 +- .../native/style-layers-regressions.test.tsx | 104 ++++++++ src/native/styles/index.ts | 231 ++++++++---------- 5 files changed, 300 insertions(+), 134 deletions(-) create mode 100644 src/__tests__/compiler/important.test.tsx create mode 100644 src/__tests__/native/style-layers-regressions.test.tsx diff --git a/src/__tests__/compiler/important.test.tsx b/src/__tests__/compiler/important.test.tsx new file mode 100644 index 00000000..22c3e386 --- /dev/null +++ b/src/__tests__/compiler/important.test.tsx @@ -0,0 +1,78 @@ +import { render } from "@testing-library/react-native"; +import { compile } from "react-native-css/compiler"; +import { Pressable } from "react-native-css/components/Pressable"; +import { registerCSS, testID } from "react-native-css/jest"; +import { Specificity } from "react-native-css/utilities"; + +// !important selects which of the runtime's two merge passes a class takes, so a callback style is checked through both + +const PLAIN = `.bg-red { background-color: red; }`; +const IMPORTANT = `.bg-red\\! { background-color: red !important; }`; + +function ruleFor(css: string) { + const rule = compile(css).stylesheet().s?.[0]?.[1]?.[0]; + + if (rule === undefined) { + throw new Error(`compiled no rule for ${css}`); + } + + return rule; +} + +test("!important sets the Important slot, and nothing else moves", () => { + const plain = ruleFor(PLAIN); + const important = ruleFor(IMPORTANT); + + expect(plain.s[Specificity.Important]).toBeUndefined(); + expect(important.s[Specificity.Important]).toBe(1); + + expect(plain.d).toStrictEqual(important.d); + expect(plain.s[Specificity.ClassName]).toBe( + important.s[Specificity.ClassName], + ); +}); + +test("the marker selects the merge pass, and the operand order is how you see it", () => { + registerCSS(`${PLAIN}\n${IMPORTANT}`); + + expect( + render( + ({ backgroundColor: "blue" })} + />, + ).getByTestId(testID).props.style, + ).toStrictEqual([{ backgroundColor: "#f00" }, { backgroundColor: "blue" }]); + + // Reversed with the marker: the important declaration is rightmost and wins. + expect( + render( + ({ backgroundColor: "blue" })} + />, + ).getByTestId(testID).props.style, + ).toStrictEqual([{ backgroundColor: "blue" }, { backgroundColor: "#f00" }]); +}); + +test("the callback ran on both routes rather than reaching the view unevaluated", () => { + registerCSS(`${PLAIN}\n${IMPORTANT}`); + + for (const className of ["bg-red", "bg-red!"]) { + const style = render( + ({ opacity: pressed ? 0.5 : 1 })} + />, + ).getByTestId(testID).props.style as unknown[]; + + expect(style).toContainEqual({ opacity: 1 }); + + for (const entry of style) { + expect(typeof entry).not.toBe("function"); + } + } +}); diff --git a/src/__tests__/native/components.test.tsx b/src/__tests__/native/components.test.tsx index 4ec527a9..a6d443bf 100644 --- a/src/__tests__/native/components.test.tsx +++ b/src/__tests__/native/components.test.tsx @@ -92,6 +92,16 @@ test("nativeStyleMapping with boolean true works alongside other styles", () => expect(component.props.style).toStrictEqual({ color: "#f00" }); }); +test("nativeStyleMapping with boolean true takes an !important class's value over the element's", () => { + registerCSS(`.text-center { text-align: center !important; }`); + + const component = render( + , + ).getByTestId(testID); + + expect(component.props.textAlign).toBe("center"); +}); + test("nativeStyleMapping with boolean true on custom component", () => { registerCSS(`.text-right { text-align: right; }`); diff --git a/src/__tests__/native/rightIsInline.test.tsx b/src/__tests__/native/rightIsInline.test.tsx index dc8bc781..710b5f74 100644 --- a/src/__tests__/native/rightIsInline.test.tsx +++ b/src/__tests__/native/rightIsInline.test.tsx @@ -9,6 +9,8 @@ * runtime behavior with intentionally malformed data. */ +import { StyleSheet } from "react-native"; + import { render } from "@testing-library/react-native"; import { Text } from "react-native-css/components/Text"; import { View } from "react-native-css/components/View"; @@ -576,8 +578,8 @@ describe("rightIsInline - Important Style Interactions", () => { />, ).getByTestId(testID); - // Important overrides, VAR_SYMBOL filtered, literal kept - expect(component.props.style).toEqual({ + // Important overrides, VAR_SYMBOL filtered, literal kept; the inline style stays a layer of its own + expect(StyleSheet.flatten(component.props.style)).toEqual({ color: "#f00", fontSize: 12, lineHeight: 24, @@ -604,13 +606,14 @@ describe("rightIsInline - Important Style Interactions", () => { , ).getByTestId(testID); - // All important properties override inline - expect(component.props.style).toEqual({ + // All important properties override inline, which stays a layer of its own + expect(StyleSheet.flatten(component.props.style)).toEqual({ color: "#f00", fontSize: 14, fontWeight: "bold", lineHeight: 24, }); + expect(component.props.style).toContain(inlineStyle); }); }); diff --git a/src/__tests__/native/style-layers-regressions.test.tsx b/src/__tests__/native/style-layers-regressions.test.tsx new file mode 100644 index 00000000..4abe356c --- /dev/null +++ b/src/__tests__/native/style-layers-regressions.test.tsx @@ -0,0 +1,104 @@ +import { Animated, View as RNView, StyleSheet } from "react-native"; + +import { act, render } from "@testing-library/react-native"; +import { Pressable } from "react-native-css/components/Pressable"; +import { ScrollView } from "react-native-css/components/ScrollView"; +import { registerCSS, testID } from "react-native-css/jest"; +import { styled } from "react-native-css/native"; +import { VAR_SYMBOL } from "react-native-css/native/reactivity"; + +// Each case renders as it does in Nativewind v4, which applies the class, then the inline style, then !important + +const CSS = ` +.p-4 { padding: 16px; } +.bg-red\\! { background-color: red !important; } +`; + +beforeEach(() => registerCSS(CSS)); + +test("an !important class on contentContainerClassName keeps the class's other values and the inline style", () => { + const component = render( + , + ).getByTestId(testID); + + expect(StyleSheet.flatten(component.props.contentContainerStyle)).toEqual({ + padding: 16, + backgroundColor: "#f00", + margin: 2, + }); +}); + +describe.each(["p-4", "p-4 bg-red!"])("className=%s", (className) => { + test("an inline Animated.Value stays live", () => { + const AnimatedView = styled(Animated.View, { className: "style" }); + const opacity = new Animated.Value(0.5); + + const component = render( + , + ).getByTestId(testID); + + act(() => { + opacity.setValue(0.9); + }); + + expect(StyleSheet.flatten(component.props.style)).toMatchObject({ + padding: 16, + opacity: 0.9, + }); + }); + + test("an inline style that holds no CSS variable reaches the component as the same object", () => { + const inline = { margin: 2 }; + + const component = render( + , + ).getByTestId(testID); + + // Layered, at any depth, never copied + expect([component.props.style].flat(Infinity)).toContain(inline); + }); +}); + +const RNViewStyled = styled(RNView, { className: { target: "style" } }); + +test.each([ + [[]], + [{ height: undefined }], + [{ [VAR_SYMBOL]: "inline", brand: "red" }], +])("the object form keeps the class's style beside an inline %p", (inline) => { + const component = render( + , + ).getByTestId(testID); + + expect(StyleSheet.flatten(component.props.style)).toMatchObject({ + padding: 16, + }); + expect(StyleSheet.flatten(component.props.style)).not.toHaveProperty("brand"); +}); + +test("a Pressable's callback style runs between a class and an !important class", () => { + const component = render( + ({ + opacity: pressed ? 0.5 : 1, + backgroundColor: "blue", + })} + />, + ).getByTestId(testID); + + expect(StyleSheet.flatten(component.props.style)).toEqual({ + padding: 16, + opacity: 1, + backgroundColor: "#f00", + }); +}); diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index d1298fd4..35b11ace 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -54,49 +54,20 @@ function hasNonOverlappingProperties( return false; } -/** - * Flattens a style array into a single object when possible, with rightmost values taking precedence. - * Returns the original array if it contains any non-plain objects, arrays, or CSS variable objects. - * - * Note: This function assumes the input array has already been filtered (e.g., by filterCssVariables), - * so empty arrays should not reach this function. If they do, they will be treated as non-flattenable. - * - * @param styleArray - The style array to potentially flatten - * @returns A single merged object if all items are plain objects, otherwise the original array - */ -function flattenStyleArray(styleArray: any[]): any { - // Check if we can flatten to a single object (all items are plain objects) - for (const item of styleArray) { - // Use explicit null check instead of !item to allow falsy values like 0 or false - if ( - item == null || - typeof item !== "object" || - Array.isArray(item) || - Object.prototype.hasOwnProperty.call(item, VAR_SYMBOL) - ) { - return styleArray; - } - } - - // Use reduce to avoid spread operator performance issues with large arrays - return styleArray.reduce((acc, item) => Object.assign(acc, item), {}); -} - /** * Recursively filters out CSS variable objects (with VAR_SYMBOL) from style values. * This prevents CSS variable runtime objects from leaking into React Native component props. * * @param value - The value to filter (can be any type: object, array, primitive, etc.) * @param depth - Internal recursion depth counter to prevent stack overflow (max 100) - * @returns The filtered value with CSS variables removed, or `undefined` if the entire value - * should be filtered out (e.g., empty arrays, objects with only VAR_SYMBOL properties) + * @returns The value with CSS variables removed, or `undefined` if the entire value should be filtered out * * Filtering behavior: * - Objects with VAR_SYMBOL property: returns `undefined` (completely filtered) - * - Arrays: filters out VAR_SYMBOL objects, returns `undefined` if empty after filtering - * - Objects: recursively filters properties, returns `undefined` if no properties remain - * - Primitives (null, undefined, numbers, strings, booleans): returned as-is - * - Symbol properties: intentionally filtered out for React Native compatibility + * - A value holding no CSS variable comes back as the same object, uncopied, so an animated style keeps its identity + * - A value holding some comes back copied without them, or `undefined` if nothing remains + * - Class instances (e.g. an Animated.Value) and primitives: returned as-is + * - A top-level style object with no string keys (`{}`, or only Symbol keys): returns `undefined` * * @example * filterCssVariables({fontSize: 16, color: {[VAR_SYMBOL]: true}}) // {fontSize: 16} @@ -105,59 +76,59 @@ function flattenStyleArray(styleArray: any[]): any { */ function filterCssVariables(value: any, depth = 0): any | undefined { // Prevent stack overflow on deeply nested structures - if (depth > 100) { + if (depth > 100 || typeof value !== "object" || value === null) { return value; } - if (value === null || value === undefined) { - return value; + // If the object itself has VAR_SYMBOL, filter it out (check own property only) + if (Object.prototype.hasOwnProperty.call(value, VAR_SYMBOL)) { + return undefined; } + // Nothing is copied until a CSS variable is found, so an inline style keeps its identity, as an animated style's handle needs if (Array.isArray(value)) { - // Single-pass filter with map operation - const filtered: any[] = []; - - for (const item of value) { - const filteredItem = filterCssVariables(item, depth + 1); - if ( - filteredItem !== undefined && - !( - typeof filteredItem === "object" && - filteredItem !== null && - Object.prototype.hasOwnProperty.call(filteredItem, VAR_SYMBOL) - ) - ) { - filtered.push(filteredItem); + let filtered: any[] | undefined; + for (let index = 0; index < value.length; index++) { + const item = value[index]; + const kept = filterCssVariables(item, depth + 1); + if (filtered === undefined) { + if (kept === item) continue; + filtered = value.slice(0, index); } + if (kept !== undefined) filtered.push(kept); } - + if (filtered === undefined) return value; return filtered.length > 0 ? filtered : undefined; } - if (typeof value === "object") { - // If the object itself has VAR_SYMBOL, filter it out (check own property only) - if (Object.prototype.hasOwnProperty.call(value, VAR_SYMBOL)) { - return undefined; - } + // A class instance, such as an Animated.Value, passes as it is: a plain copy detaches it from its animation + const prototype: unknown = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) { + return value; + } - // Otherwise, filter VAR_SYMBOL properties from nested objects - const filtered: Record = {}; - let hasProperties = false; - - // Use Object.keys to only iterate own string properties (not inherited, not Symbols) - // This intentionally filters out Symbol properties for React Native compatibility - for (const key of Object.keys(value)) { - const filteredValue = filterCssVariables(value[key], depth + 1); - if (filteredValue !== undefined) { - filtered[key] = filteredValue; - hasProperties = true; + // Object.keys only iterates own string properties, so Symbol properties are left out of a copy + const keys = Object.keys(value); + let filtered: Record | undefined; + for (let index = 0; index < keys.length; index++) { + const key = keys[index] as string; + const item = value[key]; + const kept = filterCssVariables(item, depth + 1); + if (filtered === undefined) { + if (kept === item) continue; + filtered = {}; + for (let earlier = 0; earlier < index; earlier++) { + const earlierKey = keys[earlier] as string; + filtered[earlierKey] = value[earlierKey]; } } - - return hasProperties ? filtered : undefined; + if (kept !== undefined) filtered[key] = kept; } - - return value; + // A style object with no string keys, such as {}, adds nothing, as before + if (filtered === undefined) + return depth === 0 && keys.length === 0 ? undefined : value; + for (const _ in filtered) return filtered; + return undefined; } export const stylesFamily = family( @@ -356,6 +327,20 @@ function mergeDefinedProps( return result; } +type StyleCallback = (state: unknown) => unknown; + +function isStyleCallback(value: unknown): value is StyleCallback { + return typeof value === "function"; +} + +// Pressable calls a function style with its pressed state, so a merge keeps a callback a callback +function composeStyleCallback(left: unknown, right: unknown): StyleCallback { + return (state) => [ + isStyleCallback(left) ? left(state) : left, + isStyleCallback(right) ? right(state) : right, + ]; +} + function deepMergeConfig( config: Config, left: Record | undefined, @@ -382,67 +367,24 @@ function deepMergeConfig( if (left?.style) { result.style = left.style; } - } else if (rightIsInline && right?.style) { - // Filter inline styles if rightIsInline is true - const filteredRightStyle = filterCssVariables(right.style); - - if (left?.style) { - if (!filteredRightStyle) { - // All inline styles were CSS variables, only use left - result.style = left.style; - } else { - const leftStyle = left.style; - - // For arrays or objects, check if we need to create a style array - const leftIsObject = - typeof leftStyle === "object" && !Array.isArray(leftStyle); - const rightIsObject = - typeof filteredRightStyle === "object" && - !Array.isArray(filteredRightStyle); - - if (leftIsObject && rightIsObject) { - if (hasNonOverlappingProperties(leftStyle, filteredRightStyle)) { - result.style = [leftStyle, filteredRightStyle]; - } else { - // All left properties are in right, right overrides - result.style = filteredRightStyle; - } - } else { - // One or both are arrays, merge them - result.style = [leftStyle, filteredRightStyle]; - } - } - } else { - // No left style, just use filtered right - if (filteredRightStyle) { - result.style = filteredRightStyle; - } else { - // All filtered out, remove style prop - delete result.style; - } - } } else if (!rightIsInline && right?.style) { // Merging non-inline styles (e.g., important styles) if (left?.style) { - // If left.style is an array, append right.style - if (Array.isArray(left.style)) { - const combined = [...left.style, right.style]; - result.style = flattenStyleArray(combined); + if (isStyleCallback(left.style) || isStyleCallback(right.style)) { + result.style = composeStyleCallback(left.style, right.style); } else if ( typeof left.style === "object" && - typeof right.style === "object" + !Array.isArray(left.style) && + typeof right.style === "object" && + !hasNonOverlappingProperties(left.style, right.style) ) { - // Both are objects, check for overlaps - if (hasNonOverlappingProperties(left.style, right.style)) { - result.style = flattenStyleArray([left.style, right.style]); - } else { - // All left properties are overridden by right - result.style = right.style; - } + // All left properties are overridden by right + result.style = right.style; } else { - // One or both are arrays/mixed types - const combined = [left.style, right.style]; - result.style = flattenStyleArray(combined); + // Layered rather than flattened: a copy would merge an inline animated style's handle into a plain object + result.style = Array.isArray(left.style) + ? [...left.style, right.style] + : [left.style, right.style]; } } } @@ -503,7 +445,9 @@ function deepMergeConfig( typeof rightValue === "object" && rightValue !== null && !Array.isArray(rightValue); - if (leftIsObj && rightIsObj) { + if (isStyleCallback(leftValue) || isStyleCallback(rightValue)) { + result[finalKey] = composeStyleCallback(leftValue, rightValue); + } else if (leftIsObj && rightIsObj) { if (hasNonOverlappingProperties(leftValue, rightValue)) { result[finalKey] = [leftValue, rightValue]; } else { @@ -517,6 +461,20 @@ function deepMergeConfig( // No left value — use filtered right value (not the unfiltered one from mergeDefinedProps) result[finalKey] = rightValue; } + } else if ( + config.target.length === 1 && + finalKey && + finalKey !== "style" && + left?.[finalKey] !== undefined && + right[finalKey] !== undefined + ) { + // An !important value layers over the class's and the inline value rather than replacing both + const leftValue = left[finalKey]; + const rightValue = right[finalKey]; + result[finalKey] = + isStyleCallback(leftValue) || isStyleCallback(rightValue) + ? composeStyleCallback(leftValue, rightValue) + : [leftValue, rightValue]; } return result; @@ -535,9 +493,22 @@ function deepMergeConfig( rightValue = filterCssVariables(rightValue); } - if (rightValue !== undefined) { - result[target] = - left && target in left ? [left[target], rightValue] : rightValue; + if (rightValue === undefined && rightIsInline && target in right) { + // An inline value that held only CSS variables leaves the class's, and never reaches the component itself + if (left && target in left) { + result[target] = left[target]; + } else { + delete result[target]; + } + } else if (rightValue !== undefined) { + if (left && target in left) { + result[target] = + isStyleCallback(left[target]) || isStyleCallback(rightValue) + ? composeStyleCallback(left[target], rightValue) + : [left[target], rightValue]; + } else { + result[target] = rightValue; + } } return result; From bd4841eaef5eaa7ba6b5cea4661ac224d448b00a Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Tue, 17 Nov 2026 23:51:34 -0500 Subject: [PATCH 2/3] perf(native): skip an element's undefined props in the style target's merge The ["style"] target merged props with { ...left, ...right }, which copies an undefined prop such as style={undefined}. The merge then deletes that key, and in Hermes deleting an existing property moves the props object off its fast hidden class. mergeDefinedProps, which every other target already uses, never copies it, so the later delete is a no-op. It also stops an undefined inline prop from replacing one the class computes, as on every other target. Co-Authored-By: Claude Opus 5.5 --- src/native/styles/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index 35b11ace..1e29b3f2 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -360,7 +360,7 @@ function deepMergeConfig( config.target[0] === "style" ) { // Special handling for style target when we have inline styles - result = { ...left, ...right }; + result = mergeDefinedProps(left, right); // Handle null/undefined inline styles if (right?.style === null || right?.style === undefined) { From c3997c17a8c6280266eb1efd17d74d82a0d1e0e8 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Thu, 19 Nov 2026 12:33:08 -0500 Subject: [PATCH 3/3] refactor: clean up --- src/native/styles/index.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/native/styles/index.ts b/src/native/styles/index.ts index 1e29b3f2..eaff447d 100644 --- a/src/native/styles/index.ts +++ b/src/native/styles/index.ts @@ -80,17 +80,13 @@ function filterCssVariables(value: any, depth = 0): any | undefined { return value; } - // If the object itself has VAR_SYMBOL, filter it out (check own property only) - if (Object.prototype.hasOwnProperty.call(value, VAR_SYMBOL)) { - return undefined; - } - // Nothing is copied until a CSS variable is found, so an inline style keeps its identity, as an animated style's handle needs if (Array.isArray(value)) { let filtered: any[] | undefined; for (let index = 0; index < value.length; index++) { const item = value[index]; const kept = filterCssVariables(item, depth + 1); + // No copy yet: skip unchanged items, then copy them all with the slice once one changes if (filtered === undefined) { if (kept === item) continue; filtered = value.slice(0, index); @@ -101,6 +97,11 @@ function filterCssVariables(value: any, depth = 0): any | undefined { return filtered.length > 0 ? filtered : undefined; } + // If the object itself has VAR_SYMBOL, filter it out (check own property only) + if (Object.prototype.hasOwnProperty.call(value, VAR_SYMBOL)) { + return undefined; + } + // A class instance, such as an Animated.Value, passes as it is: a plain copy detaches it from its animation const prototype: unknown = Object.getPrototypeOf(value); if (prototype !== Object.prototype && prototype !== null) { @@ -114,8 +115,10 @@ function filterCssVariables(value: any, depth = 0): any | undefined { const key = keys[index] as string; const item = value[key]; const kept = filterCssVariables(item, depth + 1); + // No copy yet: skip unchanged keys, then copy them all below once one changes if (filtered === undefined) { if (kept === item) continue; + // Objects have no slice: copy the unchanged keys before this one, performantly / avoiding allocations filtered = {}; for (let earlier = 0; earlier < index; earlier++) { const earlierKey = keys[earlier] as string; @@ -124,9 +127,12 @@ function filterCssVariables(value: any, depth = 0): any | undefined { } if (kept !== undefined) filtered[key] = kept; } + // A style object with no string keys, such as {}, adds nothing, as before - if (filtered === undefined) + if (filtered === undefined) { return depth === 0 && keys.length === 0 ? undefined : value; + } + for (const _ in filtered) return filtered; return undefined; }