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/package.json b/package.json index 130d8971..5d61abbb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@scatterlab/react-native-css", - "version": "3.1.0-rc.1-zeta.1", + "version": "3.1.0-rc.1-zeta.2", "description": "Use CSS stylesheets in React Native", "exports": { ".": { diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index a1a6906b..b81f196f 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -43,6 +43,23 @@ test("reads global CSS variables", () => { }); }); +test.each([ + // Browsers read these back clipped in WPT css/css-color/canvas-srgb-gamut-mapping.html + ["oklch(80% 0.35 30)", "#f00"], + ["oklch(90% 0.35 0)", "#ff32d5"], + // Folded by lightningcss to an oklch()/lch() color outside sRGB + ["color-mix(in oklch, red, blue)", "#ba00c2"], + ["color-mix(in lch, red, blue)", "#f50086"], +])("out-of-sRGB color %s is clipped, not gamut mapped", (value, expected) => { + const compiled = compile(`:root { --c: ${value}; }`, { + inlineVariables: false, + }); + + expect(compiled.stylesheet()).toStrictEqual({ + vr: [["c", [[expected]]]], + }); +}); + test(":root CSS variables with media queries", () => { const compiled = compile( `:root { diff --git a/src/__tests__/compiler/inline-variables.test.ts b/src/__tests__/compiler/inline-variables.test.ts new file mode 100644 index 00000000..c00dcbe7 --- /dev/null +++ b/src/__tests__/compiler/inline-variables.test.ts @@ -0,0 +1,377 @@ +import type { + ReactNativeCssStyleSheet, + StyleDescriptor, + StyleRule, +} from "react-native-css/compiler"; +import { compile } from "react-native-css/compiler"; + +function rulesFor( + sheet: ReactNativeCssStyleSheet, + className: string, +): StyleRule[] { + return sheet.s?.find(([name]) => name === className)?.[1] ?? []; +} + +function foldedValue( + sheet: ReactNativeCssStyleSheet, + className: string, + property: string, +) { + for (const rule of rulesFor(sheet, className)) { + for (const declaration of rule.d ?? []) { + if (!Array.isArray(declaration) && property in declaration) { + return declaration[property]; + } + } + } + return undefined; +} + +function runtimeValue( + sheet: ReactNativeCssStyleSheet, + className: string, + property: string, +): StyleDescriptor { + for (const rule of rulesFor(sheet, className)) { + for (const declaration of rule.d ?? []) { + if (Array.isArray(declaration) && declaration[1] === property) { + return declaration[0]; + } + } + } + return undefined; +} + +function readsAtRuntime(sheet: ReactNativeCssStyleSheet, className: string) { + return rulesFor(sheet, className).some((rule) => rule.dv === 1); +} + +function declaredValue( + sheet: ReactNativeCssStyleSheet, + className: string, + name: string, +) { + for (const rule of rulesFor(sheet, className)) { + for (const [declared, value] of rule.v ?? []) { + if (declared === name) return value; + } + } + return undefined; +} + +describe("a variable is folded only where its value is provable", () => { + test("a class-scoped variable does not reach another rule", () => { + const sheet = compile( + `.parent { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + // An element carrying only `.child` never matched `.parent`, so it has no `--x` + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + expect(declaredValue(sheet, "parent", "x")).toBe(10); + }); + + test("the same block is provable, and still folds", () => { + const sheet = compile(`.a { --x: 10px; width: var(--x); }`).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "a")).toBe(false); + }); + + test.each([":root", ":host", "*", "html"])( + "%s is universal, so its variables fold anywhere", + (selector) => { + const sheet = compile( + `${selector} { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + expect(readsAtRuntime(sheet, "child")).toBe(false); + }, + ); + + test.each([ + ["div", "every element descends from html, from no other element name"], + [":hover", "a state is not a scope"], + [".theme", "a class is the case this whole rule exists for"], + ])("%s is not universal: %s", (selector) => { + const sheet = compile( + `${selector} { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + }); + + test.each([ + [":root", 10], + [".theme", undefined], + ])("a nested `&` under %s takes its parent's answer", (parent, expected) => { + const sheet = compile( + `${parent} { & { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(expected); + }); + + test("a nested selector under :root names its descendants, not every element", () => { + const sheet = compile( + `:root { * { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + }); + + test("@layer does not narrow a universal scope", () => { + const sheet = compile( + `@layer theme { :root, :host { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + }); + + test("a keyframe's declaration is a second definition", () => { + const sheet = compile( + `.a { --x: 10px; width: var(--x); animation: grow 1s; } @keyframes grow { to { --x: 20px; } }`, + ).stylesheet(); + + // While the animation runs, `.a`'s `--x` is the keyframe's + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "a")).toBe(true); + }); + + test("a keyframe's reference folds a universal variable", () => { + const sheet = compile( + `:root { --x: 10px; } @keyframes grow { to { width: var(--x); } }`, + ).stylesheet(); + + expect(sheet.k).toStrictEqual([["grow", [["to", [{ width: 10 }]]]]]); + }); +}); + +describe("a folded declaration is removed once nothing reads it", () => { + test("a declaration whose every reference folded is removed", () => { + const sheet = compile(`.a { --x: 10px; width: var(--x); }`).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + }); + + test("a declaration another rule reads at runtime is kept", () => { + const sheet = compile( + `.a { --x: 10px; width: var(--x); } .b { height: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "b")).toBe(true); + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); + + test("an !important declaration and an !important read count as any other", () => { + const sheet = compile( + `.a { --x: 10px !important; width: var(--x); } .b { height: var(--x) !important; }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "b")).toBe(true); + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); + + test.each([ + ["an rgb() alpha", `.a { --c: 0.5; color: rgb(255 0 0 / var(--c)); }`], + [ + "a light-dark() branch", + `.a { --c: 0.5; color: light-dark(rgb(255 0 0 / var(--c)), #00f); }`, + ], + ])("a reference inside %s keeps its declaration", (_name, css) => { + const sheet = compile(css).stylesheet(); + + expect(declaredValue(sheet, "a", "c")).toBe(0.5); + }); + + test("a variable declared initial folds to the reference's fallback", () => { + const sheet = compile( + `.a { --x: initial; width: var(--x, 10px); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("every declaration of a fully folded chain is removed", () => { + const sheet = compile( + `.a { --y: 10px; --x: var(--y); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + expect(declaredValue(sheet, "a", "y")).toBeUndefined(); + }); + + test("a declaration read only by a removed declaration is removed", () => { + const sheet = compile( + `.a { --x: var(--y); height: 1px; } .b { --y: 10px; height: 2px; }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + expect(declaredValue(sheet, "b", "y")).toBeUndefined(); + }); + + test("a declaration read by a kept declaration is kept", () => { + const sheet = compile( + `.a { --x: var(--y); height: 1px; } .b { --y: 10px; height: 2px; } .c { width: var(--x); }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toStrictEqual([{}, "var", "y", 1]); + expect(declaredValue(sheet, "b", "y")).toBe(10); + }); +}); + +describe("a conditional scope is not a universal one", () => { + test.each([ + ["@media (min-width: 1px)", "media"], + ["@container (min-width: 1px)", "container"], + ])("%s wrapping :root", (atRule) => { + const sheet = compile( + `${atRule} { :root { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + }); + + test("a conditional block still folds into itself", () => { + // A query that switches the declaration off switches the reference off with it + const sheet = compile( + `@media (min-width: 1px) { .a { --x: 10px; width: var(--x); } }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); +}); + +describe("@supports is decided when the stylesheet compiles", () => { + test("a kept block's declarations apply unconditionally", () => { + const sheet = compile( + `@supports (color: color-mix(in lab, red, red)) { :root { --x: 10px; } } + .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + }); +}); + +describe("a registered property", () => { + test("inherits: false keeps a :root declaration from reaching other elements", () => { + // An element other than the root holds the registered initial value, not the one `:root` declares + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + :root { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); + + test("inherits: true leaves the universal fold alone", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: true; initial-value: 10px; } + :root { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(20); + }); + + test("inherits: false does not narrow a declaration on every element", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + * { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(20); + }); + + test("a typed initial value is left to the runtime", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); + + test("a declared property does not fold its initial value across rules", () => { + const sheet = compile( + `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } + .a { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); +}); + +describe("a variable's own value is held to the same terms", () => { + test("a nested reference does not cross a block boundary", () => { + const sheet = compile( + `.a { --x: var(--y); width: var(--x); } .b { --y: 10px; }`, + ).stylesheet(); + + // `--y` belongs to `.b`, and folding it into `.a` would carry it to elements that never matched `.b` + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(runtimeValue(sheet, "a", "width")).toStrictEqual([ + {}, + "var", + "y", + 1, + ]); + expect(declaredValue(sheet, "b", "y")).toBe(10); + }); + + test("a nested reference in the same block folds", () => { + const sheet = compile( + `.a { --y: 10px; --x: var(--y); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("a nested reference to a variable declared initial folds to its fallback", () => { + const sheet = compile( + `.a { --y: initial; --x: var(--y, 10px); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("a universal nested reference folds into a kept declaration", () => { + const sheet = compile( + `:root { --y: 10px; } .a { --x: var(--y); } .b { width: var(--x); }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); +}); + +test("the fold does not depend on the order the rules are written in", () => { + // `--y` is declared twice, so it is not a candidate, and the winning `2px` is left to the runtime + const declarations = `:root { --y: 1px; } :root { --y: 2px; }`; + const reference = `.a { --x: var(--y); width: var(--x); }`; + + const varFirst = compile(`${reference} ${declarations}`).stylesheet(); + const varLast = compile(`${declarations} ${reference}`).stylesheet(); + + for (const sheet of [varFirst, varLast]) { + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(runtimeValue(sheet, "a", "width")).toStrictEqual([ + {}, + "var", + "y", + 1, + ]); + } +}); diff --git a/src/__tests__/compiler/property.test.ts b/src/__tests__/compiler/property.test.ts index 20ae04db..11d7b564 100644 --- a/src/__tests__/compiler/property.test.ts +++ b/src/__tests__/compiler/property.test.ts @@ -316,7 +316,7 @@ test("an inheriting property with one declaration is still inlined", () => { inherits: true; initial-value: 0px; } -.parent { --folded: 10px; } +:root { --folded: 10px; } .child { width: var(--folded); } `); @@ -404,7 +404,7 @@ test.each([ test("a property left unregistered is inlined like any other declared once", () => { const result = compile(` @property --t { syntax: ""; inherits: false; initial-value: rotate(45deg); } -.parent { --t: rotate(10deg); } +:root { --t: rotate(10deg); } .child { transform: var(--t); } `).stylesheet(); @@ -433,7 +433,7 @@ test("an @property nested in @media is not registered", () => { test("the last @property declaration of a name decides what the inliner folds", () => { const consumers = ` -.parent { --flip: 10px; } +:root { --flip: 10px; } .child { width: var(--flip); } `; const child = (css: string) => diff --git a/src/__tests__/native/batch.test.tsx b/src/__tests__/native/batch.test.tsx new file mode 100644 index 00000000..2cb6c876 --- /dev/null +++ b/src/__tests__/native/batch.test.tsx @@ -0,0 +1,93 @@ +import { Dimensions } from "react-native"; + +import { act, render, screen } from "@testing-library/react-native"; +import { View } from "react-native-css/components/View"; +import { registerCSS } from "react-native-css/jest"; + +import { batch, observable, type Effect } from "../../native/reactivity"; + +jest.mock("react-native", () => { + const RN = jest.requireActual("react-native"); + RN.Platform.OS = "ios"; + return RN as unknown; +}); + +const rotate = (width: number) => { + act(() => { + const metrics = { width, height: 800, scale: 2, fontScale: 1 }; + Dimensions.set({ window: metrics, screen: metrics }); + }); +}; + +const effectRecording = (record: () => void): Effect => ({ + observers: new Set(), + run: record, +}); + +test.each([ + ["before", ".a { width: 10vw; color: var(--c); }"], + ["after", ".a { color: var(--c); width: 10vw; }"], +])( + "a rotation reaches an element reading a viewport unit %s a shared width-dependent variable", + (_, rule) => { + registerCSS(` + :root { --c: blue; } + @media (min-width: 500px) { :root { --c: red; } } + ${rule} + .b { color: var(--c); } + `); + rotate(300); + render( + <> + + + , + ); + + for (const [width, color] of [ + [700, "red"], + [300, "blue"], + [700, "red"], + ] as const) { + rotate(width); + expect(screen.getByTestId("a")).toHaveStyle({ width: width / 10, color }); + expect(screen.getByTestId("b")).toHaveStyle({ color }); + } + }, +); + +test("an effect notified again while the batch drains runs again", () => { + const source = observable(1); + const derived = observable((read) => read(source) * 10); + const seen: string[] = []; + const subscriber = effectRecording(() => { + seen.push(`${source.get()},${derived.get()}`); + }); + + source.get(subscriber); + derived.get(subscriber); + batch(() => { + source.set(2); + }); + + expect(seen.at(-1)).toBe("2,20"); +}); + +test("a batch defers every notification until its update returns, and runs each effect once", () => { + const width = observable(1); + const height = observable(1); + let runs = 0; + const subscriber = effectRecording(() => { + runs += 1; + }); + + width.get(subscriber); + height.get(subscriber); + batch(() => { + width.set(2); + height.set(2); + expect(runs).toBe(0); + }); + + expect(runs).toBe(1); +}); diff --git a/src/__tests__/native/color-mix.test.tsx b/src/__tests__/native/color-mix.test.tsx index d600e8fe..e48016d6 100644 --- a/src/__tests__/native/color-mix.test.tsx +++ b/src/__tests__/native/color-mix.test.tsx @@ -48,6 +48,28 @@ test("color-mix() - oklch", () => { }); }); +test("color-mix() - hsl", () => { + registerCSS( + `.test { + --bg: hsl(0 100% 50%); + @supports (color: color-mix(in lab, red, red)) { + background-color: color-mix(in oklab, var(--bg) 50%, transparent); + } + } + `, + { + inlineVariables: false, + }, + ); + + render(); + const component = screen.getByTestId(testID); + + expect(component.props.style).toStrictEqual({ + backgroundColor: "rgba(255, 0, 0, 0.5)", + }); +}); + test("color-mix() - black with transparent (NaN oklab channels)", () => { // lightningcss resolves this at compile time to oklab(0 NaN NaN / 0.5): // black is oklab [l=0, a=0, b=0] and transparent has no chromaticity, so the diff --git a/src/__tests__/native/media-query.test.tsx b/src/__tests__/native/media-query.test.tsx index 020b4aad..ab9501f2 100644 --- a/src/__tests__/native/media-query.test.tsx +++ b/src/__tests__/native/media-query.test.tsx @@ -1,11 +1,11 @@ -import { PixelRatio } from "react-native"; +import { Appearance, PixelRatio } from "react-native"; import { act, render, screen } from "@testing-library/react-native"; import { View } from "react-native-css/components/View"; import { registerCSS, testID } from "react-native-css/jest"; import { colorScheme } from "react-native-css/runtime"; -import { dimensions } from "../../native/reactivity"; +import { dimensions, reducedMotion } from "../../native/reactivity"; jest.mock("react-native", () => { const RN = jest.requireActual("react-native"); @@ -62,6 +62,40 @@ test("color scheme", () => { }); }); +// "unspecified" (react-native 0.82-0.86) and "auto" (0.87+) are not in every +// version's ColorSchemeName, but both mean "follow the system" at runtime. +test.each([null, undefined, "unspecified", "auto"])( + "color scheme %p follows the system", + (value) => { + registerCSS(` +.my-class { color: blue; } + +@media (prefers-color-scheme: dark) { + .my-class { color: red; } +}`); + + render(); + const component = screen.getByTestId(testID); + + act(() => { + colorScheme.set("dark"); + }); + + expect(component.props.style).toStrictEqual({ + color: "#f00", + }); + + act(() => { + colorScheme.set(value as Parameters[0]); + }); + + expect(component.props.style).toStrictEqual({ + color: "#00f", + }); + expect(colorScheme.get()).toBe(Appearance.getColorScheme() ?? "light"); + }, +); + test("width (plain)", () => { registerCSS(` .my-class { color: blue; } @@ -283,3 +317,202 @@ describe("max-resolution", () => { expect(component.props.style).toStrictEqual(undefined); }); }); + +describe("a reduced-motion preference AccessibilityInfo has not answered", () => { + let answered: ReturnType; + + beforeEach(() => { + answered = reducedMotion.get(); + reducedMotion.set(undefined); + }); + + afterEach(() => { + act(() => { + reducedMotion.set(answered); + }); + }); + + test("a mounted view takes the device's answer when it arrives", () => { + registerCSS(` + .my-class { color: #000000; } + @media (prefers-reduced-motion: reduce) { .my-class { color: #020202; } }`); + + render(); + const component = screen.getByTestId(testID); + expect(component.props.style).toStrictEqual({ color: "#000" }); + + act(() => { + reducedMotion.set("reduce"); + }); + expect(component.props.style).toStrictEqual({ color: "#020202" }); + }); + + test.each([ + "(prefers-reduced-motion: reduce)", + "(prefers-reduced-motion: no-preference)", + "(prefers-reduced-motion)", + ])("leaves @media %s unmatched", (query) => { + registerCSS( + `.my-class { color: #000000; } @media ${query} { .my-class { color: #010101; } }`, + ); + + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ + color: "#000", + }); + }); + + test("a mounted view follows the reduced-motion preference as it changes", () => { + registerCSS(` + .my-class { color: #000000; } + @media (prefers-reduced-motion: no-preference) { .my-class { color: #010101; } } + @media (prefers-reduced-motion: reduce) { .my-class { color: #020202; } }`); + + render(); + const component = screen.getByTestId(testID); + expect(component.props.style).toStrictEqual({ color: "#000" }); + + act(() => { + reducedMotion.set("no-preference"); + }); + expect(component.props.style).toStrictEqual({ color: "#010101" }); + + act(() => { + reducedMotion.set("reduce"); + }); + expect(component.props.style).toStrictEqual({ color: "#020202" }); + + act(() => { + reducedMotion.set("no-preference"); + }); + expect(component.props.style).toStrictEqual({ color: "#010101" }); + }); +}); + +// Chromium 156, Firefox 157 and WebKit 27.2 agree on every row: [query, reduce/light, reduce/dark, no-preference/light, no-preference/dark] +const BROWSER_MEDIA_ROWS = [ + ["(prefers-reduced-motion: reduce)", true, true, false, false], + ["(prefers-reduced-motion: no-preference)", false, false, true, true], + ["(prefers-reduced-motion)", true, true, false, false], + ["not (prefers-reduced-motion)", false, false, true, true], + ["not (prefers-reduced-motion: reduce)", false, false, true, true], + ["not (prefers-reduced-motion: no-preference)", true, true, false, false], + ["not all and (prefers-reduced-motion: reduce)", false, false, true, true], + ["(prefers-reduced-motion: bogus)", false, false, false, false], + ["(prefers-reduced-motion: initial)", false, false, false, false], + ["(PREFERS-REDUCED-MOTION: reduce)", true, true, false, false], + ["( prefers-reduced-motion : reduce )", true, true, false, false], + ["(prefers-reduced-motion:/* a comment */reduce)", true, true, false, false], + ["((prefers-reduced-motion: reduce))", true, true, false, false], + ["screen and (prefers-reduced-motion: reduce)", true, true, false, false], + [ + "only screen and (prefers-reduced-motion: reduce)", + true, + true, + false, + false, + ], + ["all and (prefers-reduced-motion: reduce)", true, true, false, false], + ["print and (prefers-reduced-motion: reduce)", false, false, false, false], + ["not screen and (prefers-reduced-motion: reduce)", false, false, true, true], + ["not print and (prefers-reduced-motion: reduce)", true, true, true, true], + ["(prefers-reduced-motion: reduce), print", true, true, false, false], + [ + "(prefers-reduced-motion: reduce) and (min-width: 1px)", + true, + true, + false, + false, + ], + [ + "(prefers-reduced-motion: reduce) and (prefers-color-scheme: dark)", + false, + true, + false, + false, + ], + [ + "(prefers-reduced-motion: reduce), (prefers-color-scheme: dark)", + true, + true, + false, + true, + ], + [ + "(prefers-reduced-motion: reduce) or (prefers-color-scheme: dark)", + true, + true, + false, + true, + ], + [ + "not ((prefers-reduced-motion: reduce) and (prefers-color-scheme: dark))", + true, + false, + true, + true, + ], + [ + "(prefers-reduced-motion: reduce) and (not (prefers-color-scheme: dark))", + true, + false, + false, + false, + ], + [ + "(prefers-reduced-motion: no-preference) and (prefers-reduced-motion: reduce)", + false, + false, + false, + false, + ], + [ + "(prefers-reduced-motion: reduce) and (unknown-feature)", + false, + false, + false, + false, + ], + [ + "(prefers-reduced-motion: reduce) or (unknown-feature)", + true, + true, + false, + false, + ], + ["(prefers-color-scheme: dark)", false, true, false, true], + ["(unknown-feature)", false, false, false, false], +] as const; + +const MEDIA_STATES = [ + ["reduce", "light"], + ["reduce", "dark"], + ["no-preference", "light"], + ["no-preference", "dark"], +] as const; + +describe.each(BROWSER_MEDIA_ROWS)( + "@media %s matches as browsers match it", + (query, ...matches) => { + test.each( + MEDIA_STATES.map( + ([motion, scheme], index) => [motion, scheme, matches[index]] as const, + ), + )("under %s motion in the %s scheme: %s", (motion, scheme, expected) => { + act(() => { + reducedMotion.set(motion); + colorScheme.set(scheme); + }); + registerCSS( + `.my-class { color: #000000; } @media ${query} { .my-class { color: #010101; } }`, + ); + + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ + color: expected ? "#010101" : "#000", + }); + }); + }, +); diff --git a/src/__tests__/native/reactivity-dependencies.test.tsx b/src/__tests__/native/reactivity-dependencies.test.tsx index 52d4cd3b..f008cbd2 100644 --- a/src/__tests__/native/reactivity-dependencies.test.tsx +++ b/src/__tests__/native/reactivity-dependencies.test.tsx @@ -104,3 +104,35 @@ test("an explicit computed argument replaces its previous dependency", () => { cleanupEffect(subscriber); expect(second.observers.size).toBe(0); }); + +test("an observed computed value runs once per change, not once per read", () => { + const source = observable(1); + let computed = 0; + const value = observable((get) => { + computed += 1; + return get(source) * 2; + }); + const subscriber: Effect = { observers: new Set(), run: jest.fn() }; + + for (let read = 0; read < 20; read += 1) { + expect(value.get(subscriber)).toBe(2); + } + expect(computed).toBe(1); + + source.set(5); + expect(value.get(subscriber)).toBe(10); + expect(computed).toBe(2); +}); + +test("a family deletes a key by value only while the key still maps to it", () => { + const cached = family((key: string) => ({ key })); + const original = cached("shared"); + cached.delete("shared"); + const replacement = cached("shared"); + + expect(cached.deleteIf("shared", original)).toBe(false); + expect(cached("shared")).toBe(replacement); + + expect(cached.deleteIf("shared", replacement)).toBe(true); + expect(cached.size()).toBe(0); +}); diff --git a/src/__tests__/native/reactivity-dual-package.test.ts b/src/__tests__/native/reactivity-dual-package.test.ts new file mode 100644 index 00000000..3f759fec --- /dev/null +++ b/src/__tests__/native/reactivity-dual-package.test.ts @@ -0,0 +1,92 @@ +import type { Effect } from "../../native/reactivity"; + +type ReactivityModule = typeof import("../../native/reactivity"); + +// A fresh module registry evaluates the module again against the same globalThis, as a second build in one app does +function loadCopy(): ReactivityModule { + jest.resetModules(); + return jest.requireActual("../../native/reactivity"); +} + +function createSubscriber(): Effect & { runs: number } { + const subscriber: Effect & { runs: number } = { + observers: new Set(), + runs: 0, + run: () => { + subscriber.runs++; + }, + }; + + return subscriber; +} + +describe("two evaluations of the reactivity module", () => { + test("are two copies", () => { + const first = loadCopy(); + const second = loadCopy(); + + expect(second.observable).not.toBe(first.observable); + }); + + test("share every piece of process-global state", () => { + const first = loadCopy(); + const second = loadCopy(); + const census = Object.keys(globalThis.__react_native_css_reactivity ?? {}); + + expect(census.length).toBeGreaterThan(0); + + for (const name of census) { + const key = name as keyof ReactivityModule; + + expect(first[key]).toBeDefined(); + expect(second[key]).toBe(first[key]); + } + }); + + test("deliver a write through one to a subscriber on the other", () => { + const first = loadCopy(); + const second = loadCopy(); + const subscriber = createSubscriber(); + const next = + second.colorScheme.get(subscriber) === "dark" ? "light" : "dark"; + + first.colorScheme.set(next); + + expect(subscriber.runs).toBe(1); + expect(second.colorScheme.get()).toBe(next); + }); + + test("batch a write through one inside a batch the other opened", () => { + const first = loadCopy(); + const second = loadCopy(); + const subscriber = createSubscriber(); + const value = second.observable(0); + value.get(subscriber); + + first.observableBatch.current = new Set(); + value.set(1); + + expect(subscriber.runs).toBe(0); + expect(first.observableBatch.current.size).toBe(1); + + for (const effect of first.observableBatch.current) { + effect.run(); + } + first.observableBatch.current = undefined; + + expect(subscriber.runs).toBe(1); + }); + + test("key a component's interaction and layout observables off one family", () => { + const first = loadCopy(); + const second = loadCopy(); + const key = {}; + + expect(second.containerLayoutFamily(key)).toBe( + first.containerLayoutFamily(key), + ); + expect(second.hoverFamily(key)).toBe(first.hoverFamily(key)); + expect(second.activeFamily(key)).toBe(first.activeFamily(key)); + expect(second.focusFamily(key)).toBe(first.focusFamily(key)); + }); +}); diff --git a/src/__tests__/native/reduce-motion-init.test.ts b/src/__tests__/native/reduce-motion-init.test.ts new file mode 100644 index 00000000..867f1b0d --- /dev/null +++ b/src/__tests__/native/reduce-motion-init.test.ts @@ -0,0 +1,105 @@ +type ReduceMotionListener = (isReduceMotionEnabled: boolean) => void; + +interface AccessibilityInfoDouble { + readonly isReduceMotionEnabled?: () => Promise; + readonly addEventListener?: ( + event: string, + listener: ReduceMotionListener, + ) => { readonly remove: () => void }; +} + +function importReactivityWith( + accessibilityInfo: AccessibilityInfoDouble | undefined, +) { + jest.resetModules(); + // The module pins its state on globalThis, which outlives the registry reset, so a re-import builds a fresh one only once it is gone + globalThis.__react_native_css_reactivity = undefined; + // A Proxy over requireActual rather than a spread: spreading react-native eagerly triggers its lazy DevMenu getter and throws + jest.doMock("react-native", () => { + const actual = jest.requireActual>("react-native"); + + return new Proxy(actual, { + get: (target, property): unknown => + property === "AccessibilityInfo" + ? accessibilityInfo + : Reflect.get(target, property), + }); + }); + + return jest.requireActual( + "../../native/reactivity", + ); +} + +// Every promise the module chains settles before a macrotask runs +function settle() { + return new Promise((resolve) => { + setImmediate(resolve); + }); +} + +function controlledAccessibilityInfo() { + const listeners: ReduceMotionListener[] = []; + let answer: (isReduceMotionEnabled: boolean) => void = () => undefined; + const answered = new Promise((resolve) => { + answer = resolve; + }); + + return { + accessibilityInfo: { + isReduceMotionEnabled: () => answered, + addEventListener: (event: string, listener: ReduceMotionListener) => { + if (event === "reduceMotionChanged") listeners.push(listener); + return { remove: () => undefined }; + }, + }, + answer, + change: (isReduceMotionEnabled: boolean) => { + for (const listener of listeners) listener(isReduceMotionEnabled); + }, + }; +} + +describe("the reduced-motion preference", () => { + test("is unknown until AccessibilityInfo answers", () => { + const { accessibilityInfo } = controlledAccessibilityInfo(); + + const { reducedMotion } = importReactivityWith(accessibilityInfo); + + expect(reducedMotion.get()).toBeUndefined(); + }); + + test("takes AccessibilityInfo's answer, then follows its change event", async () => { + const { accessibilityInfo, answer, change } = controlledAccessibilityInfo(); + const { reducedMotion } = importReactivityWith(accessibilityInfo); + + answer(true); + await settle(); + expect(reducedMotion.get()).toBe("reduce"); + + change(false); + expect(reducedMotion.get()).toBe("no-preference"); + }); + + test("keeps a change event over an answer that resolves after it", async () => { + const { accessibilityInfo, answer, change } = controlledAccessibilityInfo(); + const { reducedMotion } = importReactivityWith(accessibilityInfo); + + change(true); + answer(false); + await settle(); + + expect(reducedMotion.get()).toBe("reduce"); + }); + + test("is no-preference where AccessibilityInfo rejects, without an unhandled rejection", async () => { + const { reducedMotion } = importReactivityWith({ + isReduceMotionEnabled: () => + Promise.reject(new Error("NativeAccessibilityManager unavailable")), + addEventListener: () => ({ remove: () => undefined }), + }); + await settle(); + + expect(reducedMotion.get()).toBe("no-preference"); + }); +}); 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__/native/style-cache.test.tsx b/src/__tests__/native/style-cache.test.tsx index b2dcc38a..d4f8919c 100644 --- a/src/__tests__/native/style-cache.test.tsx +++ b/src/__tests__/native/style-cache.test.tsx @@ -1,7 +1,10 @@ +import { Activity, StrictMode, type ReactNode } from "react"; import { Button as RNButton, type ButtonProps } from "react-native"; -import { render, screen } from "@testing-library/react-native"; +import { act, render, screen } from "@testing-library/react-native"; +import { VariableContextProvider } from "react-native-css"; import { copyComponentProperties } from "react-native-css/components/copyComponentProperties"; +import { Text } from "react-native-css/components/Text"; import { View } from "react-native-css/components/View"; import { registerCSS } from "react-native-css/jest"; import { useCssElement } from "react-native-css/native"; @@ -11,6 +14,7 @@ import type { } from "react-native-css/runtime.types"; import { mappingToConfig } from "../../native/react/useNativeCss"; +import { colorScheme, dimensions, type Effect } from "../../native/reactivity"; import { stylesFamily } from "../../native/styles"; const buttonMapping: StyledConfiguration = { @@ -26,6 +30,12 @@ const Button = copyComponentProperties( const titleColor = (title: string): unknown => screen.getByText(title).props.style?.[1]?.color; +const withFreshVariables = (className: string, name: string) => ( + + + +); + test("identical elements share one resolved-style cache entry", () => { registerCSS(`.probe { color: red; width: 10px; }`); stylesFamily.clear(); @@ -92,3 +102,289 @@ test("a shared entry is not consumed by the first element that reads it", () => "#ffa500", ]); }); + +test("re-rendering an element keeps the value its mapping took from the shared entry", () => { + registerCSS(`.drain-once { color: orange; }`); + + const tree = render( +