From 01b4a6f1f5ef7834159dfb37841038f7edf2695e Mon Sep 17 00:00:00 2001 From: YevheniiKotyrlo <44449990+YevheniiKotyrlo@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:48:08 +0200 Subject: [PATCH 01/14] fix(native): rank an unset specificity slot the same however it is spelled (#432) Co-authored-by: Sam Moore --- src/__tests__/native/specificity.test.tsx | 132 ++++++++++++++++++ src/__tests__/vendor/tailwind/states.test.tsx | 63 +++++++++ src/compiler/compiler.types.ts | 3 +- src/compiler/selector-builder.ts | 4 +- src/utilities/specificity.ts | 25 ++-- 5 files changed, 212 insertions(+), 15 deletions(-) diff --git a/src/__tests__/native/specificity.test.tsx b/src/__tests__/native/specificity.test.tsx index b5828935..4c928668 100644 --- a/src/__tests__/native/specificity.test.tsx +++ b/src/__tests__/native/specificity.test.tsx @@ -1,9 +1,15 @@ import { StyleSheet, type ViewProps } from "react-native"; import { fireEvent, render } from "@testing-library/react-native"; +import type { StyleRule } from "react-native-css/compiler"; +import { compile } from "react-native-css/compiler"; import { Text } from "react-native-css/components/Text"; import { registerCSS, testID } from "react-native-css/jest"; import { styled } from "react-native-css/runtime"; +import { + Specificity, + specificityCompareFn, +} from "react-native-css/utilities/specificity"; test("inline styles", () => { registerCSS(`.red { background-color: red; }`); @@ -188,3 +194,129 @@ test("passThrough - inline important existing", () => { color: "#00f", }); }); + +test("the runtime sort reproduces the compile-time order after the sheet's JSON transport", () => { + const compiled = compile( + `.inp { color: red; } .inp::placeholder { color: blue; }`, + ).stylesheet().s?.[0]?.[1]; + + if (compiled === undefined) { + throw new Error( + "compiled no rules for .inp — the fixture or the compiler moved", + ); + } + + const pseudoElementCounts = (rules: StyleRule[]) => + rules.map((rule) => rule.s[Specificity.PseudoElements] ?? 0); + + expect(pseudoElementCounts(compiled)).toEqual([0, 1]); + + // Metro injects the sheet as JSON, which writes each specificity hole as `null`. + const transported = JSON.parse(JSON.stringify(compiled)) as StyleRule[]; + + expect(transported.flatMap((rule) => rule.s)).toContain(null); + + for (const order of [transported, [...transported].reverse()]) { + expect(pseudoElementCounts([...order].sort(specificityCompareFn))).toEqual([ + 0, 1, + ]); + } +}); + +describe("specificityCompareFn", () => { + const slotsByPrecedence = [ + ["Important", Specificity.Important], + ["Inline", Specificity.Inline], + ["PseudoElements", Specificity.PseudoElements], + ["ClassName", Specificity.ClassName], + ["Order", Specificity.Order], + ] as const; + + const ruleWith = (entries: [slot: number, value: number | null][]) => { + const s: StyleRule["s"] = []; + for (const [slot, value] of entries) { + s[slot] = value; + } + return { s }; + }; + + test.each(slotsByPrecedence)("%s decides when it alone is set", (_, slot) => { + expect( + specificityCompareFn(ruleWith([[slot, 1]]), ruleWith([])), + ).toBeGreaterThan(0); + expect( + specificityCompareFn(ruleWith([]), ruleWith([[slot, 1]])), + ).toBeLessThan(0); + }); + + test.each(slotsByPrecedence.slice(0, -1))( + "%s outranks every slot beneath it", + (name, slot) => { + const beneath = slotsByPrecedence + .slice(slotsByPrecedence.findIndex(([entry]) => entry === name) + 1) + .map(([, lower]): [number, number] => [lower, 9]); + + expect( + specificityCompareFn(ruleWith([[slot, 1]]), ruleWith(beneath)), + ).toBeGreaterThan(0); + }, + ); + + const withUnsetSlot = ( + slot: number, + spelling: "hole" | "null" | "zero", + order: number, + ) => + ruleWith([ + ...(spelling === "hole" + ? [] + : [[slot, spelling === "null" ? null : 0] as [number, number | null]]), + [Specificity.Order, order], + ]); + + test.each(slotsByPrecedence.slice(0, -1))( + "an unset %s defers to the slots beneath it however each side spells it", + (_, slot) => { + for (const [left, right] of [ + ["hole", "null"], + ["null", "zero"], + ["zero", "hole"], + ] as const) { + expect( + specificityCompareFn( + withUnsetSlot(slot, left, 2), + withUnsetSlot(slot, right, 1), + ), + ).toBeGreaterThan(0); + expect( + specificityCompareFn( + withUnsetSlot(slot, right, 2), + withUnsetSlot(slot, left, 1), + ), + ).toBeGreaterThan(0); + } + }, + ); + + test.each(slotsByPrecedence)( + "%s ranks a hole, a null and a zero alike", + (_, slot) => { + const hole = ruleWith([]); + const transported = ruleWith([[slot, null]]); + const zero = ruleWith([[slot, 0]]); + + expect(specificityCompareFn(hole, transported)).toBe(0); + expect(specificityCompareFn(transported, zero)).toBe(0); + expect(specificityCompareFn(zero, hole)).toBe(0); + }, + ); + + test("an inline record ranks beneath an important rule and above any selector", () => { + expect( + specificityCompareFn({}, ruleWith([[Specificity.Important, 1]])), + ).toBeLessThan(0); + expect( + specificityCompareFn({}, ruleWith([[Specificity.ClassName, 9]])), + ).toBeGreaterThan(0); + }); +}); diff --git a/src/__tests__/vendor/tailwind/states.test.tsx b/src/__tests__/vendor/tailwind/states.test.tsx index c4abd1e0..d45626b4 100644 --- a/src/__tests__/vendor/tailwind/states.test.tsx +++ b/src/__tests__/vendor/tailwind/states.test.tsx @@ -1,5 +1,10 @@ import { fireEvent, screen } from "@testing-library/react-native"; +import type { StyleRule } from "react-native-css/compiler"; import { Switch, TextInput, View } from "react-native-css/components"; +import { + Specificity, + specificityCompareFn, +} from "react-native-css/utilities/specificity"; import { render } from "./_tailwind"; @@ -100,6 +105,64 @@ test("placeholder", async () => { }); }); +test.each(["placeholder", "selection"])( + "a %s: utility still sorts after its element utility once the sheet is serialised", + async (variant) => { + const { stylesheet } = await render( + , + ); + + const rules = (stylesheet().s ?? []).flatMap(([, ruleSet]) => ruleSet); + const pseudoElementCounts = (sorted: StyleRule[]) => + sorted.map((rule) => rule.s[Specificity.PseudoElements] ?? 0); + + expect(pseudoElementCounts([...rules].sort(specificityCompareFn))).toEqual([ + 0, 1, + ]); + + // Metro injects the sheet as JSON, which writes each specificity hole as `null`. + const transported = JSON.parse(JSON.stringify(rules)) as StyleRule[]; + + for (const order of [transported, [...transported].reverse()]) { + expect( + pseudoElementCounts([...order].sort(specificityCompareFn)), + ).toEqual([0, 1]); + } + }, +); + +// A pseudo-element rule ranks equal to both of its neighbours on main, so the sort cannot move them past it +test.each(["placeholder:text-gray-400", "selection:text-blue-200"])( + "a pressed background outranks the resting one with %s between them once the sheet is serialised", + async (pseudoElementUtility) => { + const className = `active:bg-gray-100 ${pseudoElementUtility} bg-white`; + const { stylesheet } = await render( + , + ); + const ruleSets = new Map(stylesheet().s ?? []); + + // Metro injects the sheet as JSON, which writes each specificity hole as `null`. + const transported = className + .split(" ") + .flatMap((name) => + ( + JSON.parse(JSON.stringify(ruleSets.get(name) ?? [])) as StyleRule[] + ).map((rule) => ({ name, rule })), + ); + + const cascade = [...transported] + .sort((a, b) => specificityCompareFn(a.rule, b.rule)) + .map(({ name }) => name); + + expect(cascade.indexOf("bg-white")).toBeLessThan( + cascade.indexOf("active:bg-gray-100"), + ); + }, +); + test("disabled", async () => { const { rerender } = await render( , diff --git a/src/compiler/compiler.types.ts b/src/compiler/compiler.types.ts index 43ed1d1e..d45b5abc 100644 --- a/src/compiler/compiler.types.ts +++ b/src/compiler/compiler.types.ts @@ -256,7 +256,8 @@ export interface ContainerQuery { * This array is sorted by most common values when parsing a StyleSheet */ export type SpecificityArray = SpecificityValue[]; -export type SpecificityValue = number | undefined; +/** `null` is what a native runtime reads for an unset slot, because the sheet reaches it as JSON. */ +export type SpecificityValue = number | null | undefined; /****************************** Compiler ********************************/ diff --git a/src/compiler/selector-builder.ts b/src/compiler/selector-builder.ts index b150ca1a..c2230058 100644 --- a/src/compiler/selector-builder.ts +++ b/src/compiler/selector-builder.ts @@ -89,7 +89,7 @@ function parseComponents( // Merge the specificity with the root specificity for (let i = 0; i < specificity.length; i++) { const value = specificity[i]; - if (value !== undefined) { + if (typeof value === "number") { root.specificity[i] = (root.specificity[i] ?? 0) + value; } } @@ -216,7 +216,7 @@ function parseComponents( if (component.kind === "is") { for (let i = 0; i < specificity.length; i++) { const value = specificity[i]; - if (value !== undefined) { + if (typeof value === "number") { parent.specificity[i] = (parent.specificity[i] ?? 0) + value; } diff --git a/src/utilities/specificity.ts b/src/utilities/specificity.ts index 342f0a38..bc741c16 100644 --- a/src/utilities/specificity.ts +++ b/src/utilities/specificity.ts @@ -22,6 +22,12 @@ const Order = Specificity.Order; export const inlineSpecificity: SpecificityArray = []; inlineSpecificity[Specificity.Inline] = 1; +/** An unset slot ranks as zero, whether it is a hole in memory or the `null` the sheet's JSON transport writes for one. */ +const rank = (spec: SpecificityArray, slot: number): number => spec[slot] || 0; + +/** Most significant first. */ +const slots = [Important, Inline, PseudoElements, ClassName, Order]; + export const specificityCompareFn = ( a: StyleRule | InlineStyleRecord, b: StyleRule | InlineStyleRecord, @@ -29,17 +35,12 @@ export const specificityCompareFn = ( const aSpec = a.s ? a.s : inlineSpecificity; const bSpec = b.s ? b.s : inlineSpecificity; - if (aSpec[Important] !== bSpec[Important]) { - return (aSpec[Important] || 0) - (bSpec[Important] || 0); - } else if (aSpec[Inline] !== bSpec[Inline]) { - return (aSpec[Inline] || 0) - (bSpec[Inline] || 0); - } else if (aSpec[PseudoElements] !== bSpec[PseudoElements]) { - return (aSpec[PseudoElements] || 0) - (bSpec[PseudoElements] || 0); - } else if (aSpec[ClassName] !== bSpec[ClassName]) { - return (aSpec[ClassName] || 0) - (bSpec[ClassName] || 0); - } else if (aSpec[Order] !== bSpec[Order]) { - return (aSpec[Order] || 0) - (bSpec[Order] || 0); - } else { - return 0; + for (const slot of slots) { + const difference = rank(aSpec, slot) - rank(bSpec, slot); + if (difference !== 0) { + return difference; + } } + + return 0; }; From a029180c542aa4a9b24fe812f327dd93e6a1b8fa Mon Sep 17 00:00:00 2001 From: YevheniiKotyrlo <44449990+YevheniiKotyrlo@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:53:55 +0200 Subject: [PATCH 02/14] fix(types): accept an explicit undefined wherever a consumer writes an optional member (#418) Co-authored-by: Sam Moore --- .config/eslint.config.mjs | 16 +++ src/__tests__/native/styled.test.ios.tsx | 19 +++ src/__tests__/types/exact-optional.test.ts | 133 +++++++++++++++++++++ src/compiler/compiler.types.ts | 22 ++-- src/jest/index.ts | 4 +- src/metro/index.ts | 10 +- src/native/react/useNativeCss.ts | 8 +- src/native/reactivity.ts | 4 +- src/runtime.types.ts | 37 +++--- types.d.ts | 24 ++-- 10 files changed, 228 insertions(+), 49 deletions(-) create mode 100644 src/__tests__/types/exact-optional.test.ts diff --git a/.config/eslint.config.mjs b/.config/eslint.config.mjs index 7836a30b..c5fc528e 100644 --- a/.config/eslint.config.mjs +++ b/.config/eslint.config.mjs @@ -65,4 +65,20 @@ export default tseslint.config( "@typescript-eslint/no-unsafe-member-access": "off", }, }, + // Enforce new members automatically via linting rather than tests + // An optional prop this package adds to a React Native interface takes `| undefined`, as React Native's own do, so it accepts an explicit undefined under exactOptionalPropertyTypes + { + files: ["types.d.ts"], + rules: { + "no-restricted-syntax": [ + "error", + { + selector: + "TSModuleDeclaration TSInterfaceBody > TSPropertySignature[optional=true] > TSTypeAnnotation > :not(TSUnionType:has(> TSUndefinedKeyword))", + message: + "Write `?: T | undefined`: under exactOptionalPropertyTypes a bare `?: T` rejects the explicit undefined React Native's own props accept.", + }, + ], + }, + }, ); diff --git a/src/__tests__/native/styled.test.ios.tsx b/src/__tests__/native/styled.test.ios.tsx index 3f4ef620..21e55876 100644 --- a/src/__tests__/native/styled.test.ios.tsx +++ b/src/__tests__/native/styled.test.ios.tsx @@ -163,6 +163,25 @@ test.each(["nativeStyleMapping", "nativeStyleToProp"] as const)( }, ); +test("a mapping entry set to undefined maps nothing", () => { + registerCSS(`.subject { color: blue; background-color: red; }`); + const StyledView = styled(View, { + className: { + target: "style", + nativeStyleMapping: { + color: "accessibilityLabel", + backgroundColor: undefined, + }, + }, + }); + + render(); + + const props = screen.getByTestId(testID).props; + expect(props.accessibilityLabel).toBe("#00f"); + expect(props.style).toEqual({ backgroundColor: "#f00" }); +}); + test.each([false, true])( "current mapping wins over deprecated alias (empty: %s)", (empty) => { diff --git a/src/__tests__/types/exact-optional.test.ts b/src/__tests__/types/exact-optional.test.ts new file mode 100644 index 00000000..46fd9391 --- /dev/null +++ b/src/__tests__/types/exact-optional.test.ts @@ -0,0 +1,133 @@ +import { join } from "node:path"; + +import ts from "typescript"; + +const root = join(__dirname, "../../..").replaceAll("\\", "/"); +const fixtureName = `${root}/src/__tests__/types/exact-optional.fixture.tsx`; + +// Writes an explicit undefined to each optional member a consumer writes +const fixture = ` +import createDebug from "debug"; +import type { MetroConfig } from "metro-config"; +import { + Button, + FlatList, + Image, + ImageBackground, + KeyboardAvoidingView, + ScrollView, + Switch, + Text, + TouchableWithoutFeedback, + View, +} from "react-native"; +import { styled } from "react-native-css"; +import { compile } from "react-native-css/compiler"; +import { compileWithAutoDebug, registerCSS } from "react-native-css/jest"; +import { withReactNativeCSS } from "react-native-css/metro"; +import type { Config } from "react-native-css/native/react/useNativeCss"; +import type { Effect } from "react-native-css/native/reactivity"; + +declare const maybe: string | undefined; +declare const metroConfig: MetroConfig; + +const StyledView = styled(View); +const MappedView = styled( + View, + { + className: { + target: "style", + nativeStyleMapping: { color: "accessibilityLabel", backgroundColor: undefined }, + }, + contentClassName: { target: "style", nativeStyleMapping: undefined }, + }, + { passThrough: undefined }, +); + +export const elements = [ + , + , + , + , + , +