diff --git a/.config/jest.setup.js b/.config/jest.setup.js
index 53b5b12d..99790a95 100644
--- a/.config/jest.setup.js
+++ b/.config/jest.setup.js
@@ -1,3 +1,11 @@
import { setUpTests } from "react-native-reanimated";
+/* global jest */
+
+// Worklets 0.10 requires its native implementation to be mocked in Jest.
+jest.mock("react-native-worklets", () =>
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return -- Jest returns the untyped Worklets mock module.
+ jest.requireActual("react-native-worklets/src/mock"),
+);
+
setUpTests();
diff --git a/.github/actions/ios-dev-app/action.yml b/.github/actions/ios-dev-app/action.yml
index 1b4e83f6..af5bd11b 100644
--- a/.github/actions/ios-dev-app/action.yml
+++ b/.github/actions/ios-dev-app/action.yml
@@ -4,15 +4,19 @@ description: Create IOS Development App
runs:
using: composite
steps:
+ - name: Verify Xcode
+ shell: bash
+ run: xcodebuild -version
+
- name: Cache iOS development build
id: ios-dev-cache
uses: actions/cache@v4
with:
path: |
example/ios/build/DerivedData
- key: ios-dev-${{ runner.os }}-${{ hashFiles('example/ios/**', 'example/package.json', 'package.json') }}
+ key: ios-dev-${{ runner.os }}-${{ runner.arch }}-xcode26.6-${{ hashFiles('example/ios/**', 'example/package.json', 'package.json', 'yarn.lock') }}
restore-keys: |
- ios-dev-${{ runner.os }}-
+ ios-dev-${{ runner.os }}-${{ runner.arch }}-xcode26.6-
- name: Check for cached build
shell: bash
@@ -55,9 +59,11 @@ runs:
-scheme example \
-configuration Release \
-sdk iphonesimulator \
+ -destination 'generic/platform=iOS Simulator' \
-derivedDataPath build/DerivedData \
+ -resultBundlePath "$RUNNER_TEMP/ios-build.xcresult" \
CODE_SIGNING_ALLOWED=NO \
- build | xcpretty
+ build 2>&1 | tee "$RUNNER_TEMP/ios-build.log" | xcpretty
cd ..
@@ -78,6 +84,17 @@ runs:
# Create a tar for better caching (go back to example directory)
tar -czf ios-dev-build.tar.gz -C "$(dirname "$APP_PATH")" "$(basename "$APP_PATH")"
+ - name: Upload iOS build diagnostics
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: ios-build-diagnostics
+ path: |
+ ${{ runner.temp }}/ios-build.log
+ ${{ runner.temp }}/ios-build.xcresult
+ if-no-files-found: ignore
+ retention-days: 7
+
- name: Upload development build
if: steps.ios-dev-cache.outputs.cache-hit != 'true'
uses: actions/upload-artifact@v4
diff --git a/.github/releases/3.1.0-rc.0.json b/.github/releases/3.1.0-rc.0.json
new file mode 100644
index 00000000..fb50f35e
--- /dev/null
+++ b/.github/releases/3.1.0-rc.0.json
@@ -0,0 +1,19 @@
+{
+ "name": "react-native-css",
+ "version": "3.1.0-rc.0",
+ "sourceCommit": "a5002c598dae6e58904613b07fb5e0ffb55fd732",
+ "archive": "react-native-css-3.1.0-rc.0.tgz",
+ "sha256": "a03235e206ef49e48fb960e59eebea14bbb69e623aa168250d8ccca2ff200072",
+ "integrity": "sha512-/wfPJ8pXiPxvHUs0QcocN3ViV4QJdnXpKukNirZJcJ/MeZKrStSEHm2rBq+KuZm8/2XDl4GfeuaVvJctYGtdgA==",
+ "consumerDependencies": {
+ "@babel/core": "7.29.7",
+ "@expo/metro-config": "57.0.12",
+ "expo": "57.0.22",
+ "lightningcss": "1.30.1",
+ "react": "19.2.3",
+ "react-native": "0.86.3",
+ "react-native-reanimated": "4.5.1",
+ "react-native-worklets": "0.10.1",
+ "typescript": "6.0.3"
+ }
+}
diff --git a/.github/releases/3.1.0-rc.1.json b/.github/releases/3.1.0-rc.1.json
new file mode 100644
index 00000000..f18db8d4
--- /dev/null
+++ b/.github/releases/3.1.0-rc.1.json
@@ -0,0 +1,19 @@
+{
+ "name": "react-native-css",
+ "version": "3.1.0-rc.1",
+ "sourceCommit": "a37903f594905813517a17aac85adeadfe678762",
+ "archive": "react-native-css-3.1.0-rc.1.tgz",
+ "sha256": "f2d37969b9309c537ba810492ca9e3f1b56edd5afe00143324773f90badfc749",
+ "integrity": "sha512-TT5NnkSK1TRlzbZWeJCyjYwEj7IWOZkGR+e42+PU5X6TQM/wW3CPplI44EbWyNz8QN0WeFzrkQTh3EvhO4cEWA==",
+ "consumerDependencies": {
+ "@babel/core": "7.29.7",
+ "@expo/metro-config": "57.0.12",
+ "expo": "57.0.22",
+ "lightningcss": "1.30.1",
+ "react": "19.2.3",
+ "react-native": "0.86.3",
+ "react-native-reanimated": "4.5.1",
+ "react-native-worklets": "0.10.1",
+ "typescript": "6.0.3"
+ }
+}
diff --git a/.github/releases/README.md b/.github/releases/README.md
new file mode 100644
index 00000000..ca01d262
--- /dev/null
+++ b/.github/releases/README.md
@@ -0,0 +1,11 @@
+# RC publication
+
+The existing Release & Publish to NPM workflow accepts `rc`, an exact RC version, and a publication checkbox. An unchecked publication checkbox runs authentication and archive preflight only. Stable and preview releases continue to use release-it.
+
+Each RC has a reviewed JSON descriptor in this directory. It identifies the merged source commit, package version, archive checksums, and Expo consumer dependencies. The exact audited archive is attached to a draft GitHub prerelease whose tag is the package version and whose target is the recorded source commit.
+
+The RC job verifies the descriptor and archive, then publishes the archive under `rc-staging` without rebuilding. An existing npm version is accepted only when its integrity matches. The job downloads the registry archive, verifies both checksums, installs the exact version in a fresh Expo consumer, and runs the engine Node tooling tests against that installation. It checks that only one engine runtime is installed.
+
+After those checks pass, the job advances `rc`, verifies that `latest` is unchanged, and makes the GitHub prerelease public. A failed run retains its publication receipt. Retries accept an already published matching archive and repeat the registry checks before advancing `rc`.
+
+The runner uses the existing `NPM_TOKEN` secret. Authentication is checked before the publication step. Registry authentication failures require fixing the repository's npm publishing credential.
diff --git a/.github/scripts/release_rc.py b/.github/scripts/release_rc.py
new file mode 100644
index 00000000..62249134
--- /dev/null
+++ b/.github/scripts/release_rc.py
@@ -0,0 +1,174 @@
+"""Publish a reviewed archive without rebuilding or changing the stable tag."""
+
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tarfile
+import time
+import urllib.error
+import urllib.request
+
+
+REGISTRY = "https://registry.npmjs.org"
+
+
+def check(condition, message):
+ if not condition:
+ raise RuntimeError(message)
+
+
+def validate_version(version):
+ check(re.fullmatch(r"\d+\.\d+\.\d+-rc\.\d+", version), "Invalid RC version")
+
+
+def verify_archive(archive, descriptor):
+ data = archive.read_bytes()
+ check(hashlib.sha256(data).hexdigest() == descriptor["sha256"], "Archive SHA256 mismatch")
+ integrity = "sha512-" + base64.b64encode(hashlib.sha512(data).digest()).decode()
+ check(integrity == descriptor["integrity"], "Archive integrity mismatch")
+ with tarfile.open(archive) as tar:
+ package = json.load(tar.extractfile("package/package.json"))
+ check(package["name"] == descriptor["name"], "Wrong package")
+ check(package["version"] == descriptor["version"], "Wrong version")
+ for field in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
+ check(not any(value.startswith(("file:", "link:", "workspace:"))
+ for value in package.get(field, {}).values()), "Local dependency in archive")
+
+
+def verify_registry(metadata, descriptor):
+ check(metadata["name"] == descriptor["name"], "Registry package mismatch")
+ check(metadata["version"] == descriptor["version"], "Registry version mismatch")
+ check(metadata["dist"]["integrity"] == descriptor["integrity"], "Published version has different bytes")
+
+
+def verify_latest(before, after):
+ check(before.get("latest") == after.get("latest"), "The stable latest tag changed")
+
+
+def registry_json(route, missing_ok=False, attempts=1):
+ for attempt in range(attempts):
+ try:
+ request = urllib.request.Request(REGISTRY + route, headers={"Cache-Control": "no-cache"})
+ with urllib.request.urlopen(request, timeout=60) as response:
+ return json.load(response)
+ except urllib.error.HTTPError as error:
+ if error.code != 404:
+ raise
+ if attempt + 1 < attempts:
+ print("Waiting for npm registry visibility...", flush=True)
+ time.sleep(10)
+ continue
+ if missing_ok:
+ return None
+ raise
+
+
+def wait_for_rc_tag(before, version, attempts=31):
+ for attempt in range(attempts):
+ after = registry_json("/-/package/react-native-css/dist-tags")
+ verify_latest(before, after)
+ if after.get("rc") == version:
+ return after
+ if attempt + 1 < attempts:
+ time.sleep(10)
+ raise RuntimeError("RC tag is not visible after waiting for the registry")
+
+
+def run(*args, cwd=None, env=None):
+ subprocess.run(args, cwd=cwd, env=env, check=True)
+
+
+def verify_consumer(root, work, descriptor):
+ consumer = work / "consumer"
+ consumer.mkdir()
+ dependencies = {**descriptor["consumerDependencies"], descriptor["name"]: descriptor["version"]}
+ (consumer / "package.json").write_text(json.dumps({"name": "rc-registry-check", "private": True,
+ "version": "0.0.0", "dependencies": dependencies}))
+ public_env = {key: value for key, value in os.environ.items()
+ if key not in ("GH_TOKEN", "GITHUB_TOKEN", "NPM_TOKEN", "NODE_AUTH_TOKEN")}
+ public_env["NODE_AUTH_TOKEN"] = ""
+ run("npm", "install", "--no-audit", "--no-fund", "--registry=" + REGISTRY, cwd=consumer, env=public_env)
+ lock = json.loads((consumer / "package-lock.json").read_text())
+ engines = {key: value for key, value in lock["packages"].items()
+ if key.endswith("node_modules/react-native-css")}
+ check(list(engines) == ["node_modules/react-native-css"], "Expected one engine runtime")
+ installed = engines["node_modules/react-native-css"]
+ check(installed["version"] == descriptor["version"], "Installed version mismatch")
+ check(installed["integrity"] == descriptor["integrity"], "Installed archive integrity mismatch")
+ check(installed["resolved"].startswith(REGISTRY + "/react-native-css/-/"), "Engine did not come from npm")
+ engine = consumer / "node_modules/react-native-css"
+ tests = consumer / "tests"
+ tests.mkdir()
+ for source in (root / "node/__tests__").glob("*.mjs"):
+ # Only relocate private helper entry paths; keep every assertion unchanged.
+ content = source.read_text().replace("../../dist/", str(engine / "dist") + "/")
+ (tests / source.name).write_text(content)
+ public_env["CSS_COMPONENT_REGISTRY_ROOT"] = str(engine)
+ public_env["CSS_TYPESCRIPT_SETUP_ENTRY"] = str(engine / "dist/commonjs/metro/typescript.js")
+ public_env["CSS_LOADER_UNDER_TEST"] = str(engine / "dist/commonjs/compiler/lightningcss-loader.js")
+ run("node", "--test", *map(str, sorted(tests.glob("*.mjs"))), cwd=consumer, env=public_env)
+
+
+def main():
+ version = os.environ["RC_VERSION"]
+ validate_version(version)
+ root = Path(__file__).resolve().parents[2]
+ descriptor = json.loads((root / ".github/releases" / (version + ".json")).read_text())
+ check(descriptor["name"] == "react-native-css" and descriptor["version"] == version, "Invalid release descriptor")
+ check(descriptor["archive"] == "react-native-css-" + version + ".tgz", "Invalid archive name")
+ run("git", "merge-base", "--is-ancestor", descriptor["sourceCommit"], "HEAD", cwd=root)
+ release = json.loads(subprocess.check_output(
+ ["gh", "release", "view", version, "--json", "isDraft,isPrerelease,targetCommitish"], text=True))
+ check(release["targetCommitish"] == descriptor["sourceCommit"], "Release targets different source")
+ check(release["isPrerelease"], "Expected a GitHub prerelease")
+ work = Path(os.environ["RUNNER_TEMP"]) / "rc-publication"
+ work.mkdir(exist_ok=True)
+ run("gh", "release", "download", version, "--pattern", descriptor["archive"], "--dir", str(work))
+ archive = work / descriptor["archive"]
+ verify_archive(archive, descriptor)
+ tag_route = "/-/package/react-native-css/dist-tags"
+ version_route = "/react-native-css/" + version
+ before = registry_json(tag_route)
+ existing = registry_json(version_route, missing_ok=True)
+ if existing is not None:
+ verify_registry(existing, descriptor)
+ receipt = {"descriptor": descriptor, "tagsBefore": before, "stage": "preflight-passed"}
+ receipt_file = work / "publication.json"
+
+ def save(stage):
+ receipt["stage"] = stage
+ receipt_file.write_text(json.dumps(receipt, indent=2) + "\n")
+
+ save("preflight-passed")
+ if os.environ.get("RC_PUBLISH") != "true":
+ print("RC preflight passed; publication was not requested.")
+ return
+ if existing is None:
+ run("npm", "publish", str(archive), "--tag", "rc-staging", "--access", "public",
+ "--ignore-scripts", "--registry=" + REGISTRY, "--loglevel=warn")
+ metadata = registry_json(version_route, attempts=31)
+ verify_registry(metadata, descriptor)
+ receipt["registry"] = metadata
+ save("registry-integrity-verified")
+ downloaded = work / "registry"
+ downloaded.mkdir()
+ run("npm", "pack", "react-native-css@" + version, "--ignore-scripts", "--pack-destination",
+ str(downloaded), "--registry=" + REGISTRY, "--loglevel=warn")
+ verify_archive(downloaded / descriptor["archive"], descriptor)
+ verify_consumer(root, work, descriptor)
+ save("registry-consumer-passed")
+ verify_latest(before, registry_json(tag_route))
+ run("npm", "dist-tag", "add", "react-native-css@" + version, "rc", "--registry=" + REGISTRY)
+ after = wait_for_rc_tag(before, version)
+ receipt["tagsAfter"] = after
+ save("rc-published")
+ run("gh", "release", "edit", version, "--draft=false", "--prerelease", "--latest=false")
+ save("complete")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.github/scripts/test_release_rc.py b/.github/scripts/test_release_rc.py
new file mode 100644
index 00000000..1f536199
--- /dev/null
+++ b/.github/scripts/test_release_rc.py
@@ -0,0 +1,134 @@
+import base64
+import hashlib
+import io
+import json
+from pathlib import Path
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+from urllib.error import HTTPError
+
+from release_rc import registry_json, validate_version, verify_archive, verify_latest, verify_registry, wait_for_rc_tag
+
+
+class ReleaseGuards(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.archive = Path(self.temp.name) / "package.tgz"
+ self.descriptor = {"name": "react-native-css", "version": "3.1.0-rc.0"}
+
+ def pack(self, **metadata):
+ package = {**self.descriptor, **metadata}
+ data = json.dumps(package).encode()
+ with tarfile.open(self.archive, "w:gz") as tar:
+ entry = tarfile.TarInfo("package/package.json")
+ entry.size = len(data)
+ tar.addfile(entry, io.BytesIO(data))
+ archive_bytes = self.archive.read_bytes()
+ self.descriptor.update({
+ "sha256": hashlib.sha256(archive_bytes).hexdigest(),
+ "integrity": "sha512-" + base64.b64encode(hashlib.sha512(archive_bytes).digest()).decode(),
+ })
+
+ def test_only_exact_rc_versions_are_accepted(self):
+ validate_version("3.1.0-rc.0")
+ for version in ("3.1.0", "3.1.0-preview.0", "rc", "../../3.1.0-rc.0", "3.1.0-rc.0; npm publish"):
+ with self.subTest(version=version), self.assertRaises(RuntimeError):
+ validate_version(version)
+
+ def test_reviewed_archive_passes(self):
+ self.pack()
+ verify_archive(self.archive, self.descriptor)
+
+ def test_changed_archive_is_rejected_before_publication(self):
+ self.pack()
+ self.archive.write_bytes(self.archive.read_bytes() + b"unreviewed bytes")
+ with self.assertRaisesRegex(RuntimeError, "SHA256"):
+ verify_archive(self.archive, self.descriptor)
+
+ def test_mismatched_integrity_is_rejected(self):
+ self.pack()
+ self.descriptor["integrity"] = "sha512-other"
+ with self.assertRaisesRegex(RuntimeError, "integrity"):
+ verify_archive(self.archive, self.descriptor)
+
+ def test_different_package_or_version_is_rejected(self):
+ for metadata in ({"name": "other-package"}, {"version": "3.1.0"}):
+ with self.subTest(metadata=metadata):
+ self.pack(**metadata)
+ with self.assertRaises(RuntimeError):
+ verify_archive(self.archive, self.descriptor)
+
+ def test_local_dependencies_are_rejected(self):
+ for field in ("dependencies", "devDependencies", "peerDependencies", "optionalDependencies"):
+ for dependency in ("file:../engine.tgz", "link:../engine", "workspace:*"):
+ with self.subTest(field=field, dependency=dependency):
+ self.pack(**{field: {"engine": dependency}})
+ with self.assertRaisesRegex(RuntimeError, "Local dependency"):
+ verify_archive(self.archive, self.descriptor)
+
+ def test_retry_accepts_identical_registry_bytes(self):
+ self.pack()
+ metadata = {"name": self.descriptor["name"], "version": self.descriptor["version"],
+ "dist": {"integrity": self.descriptor["integrity"]}}
+ verify_registry(metadata, self.descriptor)
+
+ def test_registry_collision_is_rejected(self):
+ self.pack()
+ metadata = {"name": self.descriptor["name"], "version": self.descriptor["version"],
+ "dist": {"integrity": "sha512-other"}}
+ with self.assertRaisesRegex(RuntimeError, "different bytes"):
+ verify_registry(metadata, self.descriptor)
+
+ def test_rc_tag_can_advance_without_changing_latest(self):
+ verify_latest({"latest": "3.0.7"}, {"latest": "3.0.7", "rc": "3.1.0-rc.0"})
+
+ def test_stable_tag_change_is_rejected(self):
+ with self.assertRaisesRegex(RuntimeError, "latest"):
+ verify_latest({"latest": "3.0.7"}, {"latest": "3.1.0-rc.0"})
+
+ def test_new_registry_version_can_become_visible_after_404(self):
+ missing = HTTPError("https://registry.npmjs.org/example", 404, "Not found", {}, None)
+ with patch("release_rc.urllib.request.urlopen", side_effect=[missing, io.BytesIO(b'{"version":"3.1.0-rc.0"}')]) as fetch:
+ with patch("release_rc.time.sleep") as sleep:
+ self.assertEqual(registry_json("/example", attempts=3)["version"], "3.1.0-rc.0")
+ self.assertEqual(fetch.call_count, 2)
+ sleep.assert_called_once_with(10)
+
+ def test_missing_version_retry_is_bounded(self):
+ missing = HTTPError("https://registry.npmjs.org/example", 404, "Not found", {}, None)
+ with patch("release_rc.urllib.request.urlopen", side_effect=missing) as fetch:
+ with patch("release_rc.time.sleep") as sleep:
+ with self.assertRaises(HTTPError):
+ registry_json("/example", attempts=3)
+ self.assertEqual(fetch.call_count, 3)
+ self.assertEqual(sleep.call_count, 2)
+
+ def test_authentication_errors_are_not_retried_as_propagation(self):
+ forbidden = HTTPError("https://registry.npmjs.org/example", 403, "Forbidden", {}, None)
+ with patch("release_rc.urllib.request.urlopen", side_effect=forbidden):
+ with patch("release_rc.time.sleep") as sleep:
+ with self.assertRaises(HTTPError):
+ registry_json("/example", attempts=3)
+ sleep.assert_not_called()
+
+ def test_rc_tag_can_become_visible_after_stale_response(self):
+ before = {"latest": "3.0.7"}
+ after = {**before, "rc": "3.1.0-rc.0"}
+ with patch("release_rc.registry_json", side_effect=[before, after]):
+ with patch("release_rc.time.sleep") as sleep:
+ self.assertEqual(wait_for_rc_tag(before, "3.1.0-rc.0", attempts=3), after)
+ sleep.assert_called_once_with(10)
+
+ def test_rc_polling_never_accepts_a_stable_tag_change(self):
+ with patch("release_rc.registry_json", return_value={"latest": "3.1.0-rc.0", "rc": "3.1.0-rc.0"}):
+ with patch("release_rc.time.sleep") as sleep:
+ with self.assertRaisesRegex(RuntimeError, "latest"):
+ wait_for_rc_tag({"latest": "3.0.7"}, "3.1.0-rc.0")
+ sleep.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8fdb0f9c..a9c07e62 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -23,6 +23,9 @@ jobs:
- name: Setup
uses: ./.github/actions/setup
+ - name: Build package
+ run: yarn build
+
- name: Lint files
run: yarn lint
@@ -53,6 +56,9 @@ jobs:
- name: Build package
run: yarn build
+ - name: Verify Node tooling
+ run: node --test node/__tests__/*.mjs
+
- name: Check for unstaged files
uses: ./.github/actions/check-unstaged-files
@@ -76,7 +82,9 @@ jobs:
uses: ./.github/actions/check-unstaged-files
build-ios-dev:
- runs-on: macos-15
+ runs-on: macos-26
+ env:
+ DEVELOPER_DIR: /Applications/Xcode_26.6.app/Contents/Developer
steps:
- name: Checkout Repository
uses: actions/checkout@v4
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 400c17be..5fdf202c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -13,12 +13,25 @@ on:
- minor
- major
- preview
+ - rc
+ rc-version:
+ description: "Reviewed RC version (required for rc)"
+ type: string
+ rc-publish:
+ description: "Publish the verified RC; leave unchecked for a preflight"
+ type: boolean
+ default: false
permissions:
contents: write
+concurrency:
+ group: npm-release
+ cancel-in-progress: false
+
jobs:
release:
+ if: inputs.release-type != 'rc'
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
@@ -51,3 +64,36 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+
+ release-rc:
+ if: inputs.release-type == 'rc'
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-node@v4
+ with:
+ node-version-file: ".nvmrc"
+ registry-url: https://registry.npmjs.org
+ - name: Test publication guards
+ run: python3 -m unittest discover -s .github/scripts -p 'test_release_rc.py'
+ - name: Verify npm authentication
+ run: npm whoami --registry=https://registry.npmjs.org
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ - name: Verify and publish reviewed RC
+ run: python3 .github/scripts/release_rc.py
+ env:
+ RC_VERSION: ${{ inputs.rc-version }}
+ RC_PUBLISH: ${{ inputs.rc-publish }}
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ - name: Retain publication receipt
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: rc-publication-receipt
+ path: ${{ runner.temp }}/rc-publication/*.json
diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md
index 4ce58467..5125ac7c 100644
--- a/DEVELOPMENT.md
+++ b/DEVELOPMENT.md
@@ -47,7 +47,7 @@ This enables `className` prop support on all React Native components.
- **Reactive style system** (`src/native/reactivity.ts`) — custom observables for media queries, container queries, color scheme changes
- **StyleCollection singleton** (`src/native-internal/`) — isolated to prevent circular dependencies between native runtime and CSS file imports
- **Platform-aware compilation** — different outputs for native (JSON) vs web (browser CSS)
-- **Inline variable optimization** — single-use CSS variables are inlined at compile time; multi-use preserved
+- **Inline variable optimization** — single-use CSS variables are inlined at compile time; multi-use, those an `@property` registers `inherits: false` (unless declared only on `*` outside `@media` and `@container`), and those whose value refers to one, preserved
## Package Entry Points
diff --git a/README.md b/README.md
index bafb2302..b1135760 100644
--- a/README.md
+++ b/README.md
@@ -235,6 +235,30 @@ This API only allows for setting CSS variables as primitive values. For more com
> [!IMPORTANT]
> By using `VariableContext` you may need to disable the `inlineVariable` optimization
+## Compiler warnings
+
+Not every CSS declaration has a React Native equivalent. When the compiler cannot translate one it drops that declaration, and Metro prints a summary for the stylesheet it came from:
+
+```
+react-native-css: src/global.css - 3 declarations dropped, no React Native equivalent
+ properties: columns, float
+ values: z-index: auto
+```
+
+The block also counts the syntax warnings lightningcss gives for CSS it cannot parse, such as an unknown at-rule, and lists their messages under `syntax:`. Those are fixed in the stylesheet itself.
+
+A block is printed the first time a file is compiled, and after that only when the file's set of warnings changes — an incremental rebuild that changes nothing about them stays quiet. Warnings are advisory and never fail a build.
+
+Use the `warnings` option to change how much is printed:
+
+```tsx
+export default withReactNativeCSS(defaultConfig, {
+ warnings: "verbose", // "summary" (the default) | "verbose" | "none"
+});
+```
+
+`summary` lists the first ten entries of each channel, `verbose` lists every entry, and `none` prints nothing. A web bundle never runs the compiler, so this only affects native builds.
+
## Optimizations
CSS is a dynamic styling language that use highly optimized engines that are not available in React Native. Instead, we optimize the styles to improve performance
@@ -296,6 +320,12 @@ export default withReactNativeCSS(defaultConfig, {
});
```
+### Registered Custom Properties (`@property`)
+
+A custom property registered with `inherits: false` is inlined only when its single declaration is on a universal selector (`*`) outside a media or container query. A custom property whose value refers to one registered with `inherits: false` is never inlined.
+
+An `@property` rule inside `@media` is ignored on native, even when the media query matches.
+
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
diff --git a/css.d.ts b/css.d.ts
new file mode 100644
index 00000000..cbe652db
--- /dev/null
+++ b/css.d.ts
@@ -0,0 +1 @@
+declare module "*.css";
diff --git a/docs/css-variable-inputs.md b/docs/css-variable-inputs.md
new file mode 100644
index 00000000..d8680f15
--- /dev/null
+++ b/docs/css-variable-inputs.md
@@ -0,0 +1,22 @@
+# CSS variable input units
+
+Use explicit CSS lengths when a variable supplies a dimension in an application that also targets browsers:
+
+```tsx
+
+
+
+```
+
+```css
+.card {
+ width: var(--card-width);
+ opacity: var(--opacity);
+}
+```
+
+The native engine converts pixel strings to React Native numeric dimensions. Fractional values must remain fractional when the variable is inherited or updated. The proposed Expo upgrade fixes the previous truncation of `80.5px` to `80`.
+
+Browser custom properties retain their CSS token values. A nonzero unitless number is invalid when substituted directly into `width`, while a unitless opacity or scale factor is valid. The library cannot append `px` to every numeric variable without changing those other uses. Use a pixel string for lengths.
+
+`vars()` remains a deprecated input path; the same unit contract applies. Prefer `VariableContextProvider` for new code. Source tests cover fractional pixel values through both APIs and their updates. Compatibility evidence keeps the original numeric width case distinct from the explicit length case rather than changing the original expectation.
diff --git a/docs/expo57-rc.md b/docs/expo57-rc.md
new file mode 100644
index 00000000..8651bad2
--- /dev/null
+++ b/docs/expo57-rc.md
@@ -0,0 +1,21 @@
+# react-native-css Expo 57 release candidate
+
+react-native-css 3.1.0-rc.1 is published under the `rc` tag, paired with Nativewind 5.0.0-rc.1. Nativewind requires this exact engine candidate. The stable `latest` tag stays on 3.0.7.
+
+The audited target is Expo 57.0.22, React Native 0.86.3, React 19.2.3, Reanimated 4.5.1 and Worklets 0.10.1. Keep native dependency versions aligned with Expo. Native dependency changes require rebuilding the application.
+
+Install the exact engine and Nativewind pair:
+
+```sh
+npm install --save-exact nativewind@5.0.0-rc.1 react-native-css@3.1.0-rc.1
+```
+
+3.1.0-rc.1 is built from commit a37903f594905813517a17aac85adeadfe678762. The archive SHA256 is f2d37969b9309c537ba810492ca9e3f1b56edd5afe00143324773f90badfc749, recorded in `.github/releases/3.1.0-rc.1.json`. Compared with 3.1.0-rc.0, it adds Metro build warnings and fixes Babel, compiler and native variable handling. See the [3.1.0-rc.1 release notes](https://github.com/nativewind/react-native-css/releases/tag/3.1.0-rc.1).
+
+The RC updates Expo integration, Node ESM tooling exports, TypeScript setup, style and prop mappings, variable resolution, compiler behavior, component identities and cache invalidation. Each accepted contract is associated with explicit expected values and deliberately incorrect controls in the compatibility audit. The full library run passed 1434 tests across the two libraries plus 42 engine Node tests. The release verifier passed 670 tests with no skips. The reviewed inventory accounts for 6129 entries and requires 4985 execution cells. All 4985 passed the final release checker, with zero missing assertions. These audit results were recorded for 3.1.0-rc.0.
+
+Android animation cancellation remains affected by [Reanimated issue 10507](https://github.com/software-mansion/react-native-reanimated/issues/10507), which also reproduces without react-native-css or Nativewind. The exact Android animate-none reset case is retained as an accepted upstream defect and excluded from passing support claims. Its isolated result can pass, so the cancellation behavior remains intermittent. iPhone and browser cancellation and every other motion requirement remain independently verified. No Reanimated patch is bundled. Physical Android verification was waived; a Release emulator and physical iPhone are required. Browser object fitting in the original React Native Web and Expo Image adapters requires explicit component props. Some browser selection, backface and fragmentation examples remain explicitly limited. These are not universal CSS support claims.
+
+Use React Native Appearance and useColorScheme for native dark mode. Appearance.setColorScheme('unspecified') restores the system preference on this Expo target. The full [Nativewind RC compatibility guide](https://github.com/nativewind/nativewind/blob/main/docs/rc-compatibility.md) records supported value domains, migration requirements and exact platform limitations. The [installation guide](https://github.com/nativewind/nativewind/blob/main/docs/expo57-rc.md) includes Tailwind, PostCSS, Metro and Babel configuration.
+
+Report problems with exact package and Expo versions, platform, build mode, configuration and a minimal reproduction. Include whether a direct React Native or Reanimated reference also fails. The public v4 to v5 migration skill follows RC publication and must be verified against the published packages before stable promotion. Stable npm tags stay unchanged during the RC release.
diff --git a/docs/known-issues.md b/docs/known-issues.md
new file mode 100644
index 00000000..4111a708
--- /dev/null
+++ b/docs/known-issues.md
@@ -0,0 +1,9 @@
+# Known Expo 57 dependency limitation
+
+With Expo 57.0.22, React Native 0.86.3, Reanimated 4.5.1, and Worklets 0.10.1, cancelling a CSS animation on Android can leave the component at its last animated transform. A spinning view can remain tilted after switching to `animationName: "none"` or removing the animation styles. In Nativewind, this affects changing `animate-spin` to `animate-none`.
+
+The original Expo 57.0.21 diagnostic reproduced both forms. Fresh Expo 57.0.22 checks reproduce direct style removal and integrated animate-none failure, while isolated none checks can pass. The behavior is intermittent. The failure reproduces with a direct Reanimated `Animated.View` without Nativewind or react-native-css. It is tracked in [Reanimated #10507](https://github.com/software-mansion/react-native-reanimated/issues/10507). The confirmed environment is an Android API 34 emulator with Fabric, Hermes, and a Release build. The integrated physical iPhone cancellation case passed. Later Reanimated versions and physical Android have not been verified.
+
+The planned RC retains Expo's exact dependency versions and discloses this limitation. Neither library includes the experimental Reanimated patch. Applications relying on CSS animation cancellation must account for this known behavior. No production workaround is currently verified by this release effort.
+
+The issue includes a [standalone reproduction](https://gist.github.com/danstepanov/03d34ece59f03628deb77a028e8a9a03). When an official fix becomes available in the supported Expo environment, rerun the cancellation and motion checks before removing this notice. The full RC gate is complete as described in [the release guide](expo57-rc.md). The packages have not been published.
diff --git a/docs/v5-engine-contracts.md b/docs/v5-engine-contracts.md
new file mode 100644
index 00000000..6a5652d8
--- /dev/null
+++ b/docs/v5-engine-contracts.md
@@ -0,0 +1,11 @@
+# V5 engine contract migration notes
+
+Nativewind v5 dark mode follows the [documented Appearance API](https://www.nativewind.dev/v5/core-concepts/dark-mode). The default `dark:` variant compiles to `prefers-color-scheme: dark`. On native, use React Native `Appearance.setColorScheme("light")` or `Appearance.setColorScheme("dark")` for manual selection, and `useColorScheme` from `react-native` to read it. On this Expo target, `Appearance.setColorScheme("unspecified")` restores the system preference. Web uses its CSS media query; native override verification does not establish a browser override mechanism.
+
+Legacy `@cssInterop set darkMode ...` configuration and class-qualified `:root` selectors have no native document root contract. The compiler now reports an explicit error before variable optimization can accidentally apply conditional values unconditionally. Migrate theme behavior to media queries and Appearance. Ordinary ancestor class selectors remain supported as selectors; adding a `dark` ancestor is not required by the documented default v5 theme API.
+
+For preserved CSS variables, use the compiler option `inlineVariables: { exclude: ["--variable-name"] }`. The old `@react-native config { preserve-variables: ... }` directive reports a migration error rather than silently ignoring the option.
+
+The declared deprecated `nativeStyleToProp` option remains supported as an alias for `nativeStyleMapping`. The current option takes precedence when both are provided, including an empty mapping. `target: false` discards unmapped compiled styles while retaining original inline styles.
+
+Unit verification covers compiler semantics, Appearance event subscription, mapping destinations and restoration, and animation metadata delivered to Reanimated. It does not prove native frame interpolation or OS event delivery. The new engine package still requires renderer verification before RC approval.
diff --git a/example/example-env.d.ts b/example/example-env.d.ts
index 473923c5..29390898 100644
--- a/example/example-env.d.ts
+++ b/example/example-env.d.ts
@@ -1,57 +1 @@
-// This file is should be auto generated, you do not need to use this file
-
-export * from "react-native";
-
-declare module "react-native" {
- interface ScrollViewProps
- extends ViewProps,
- ScrollViewPropsIOS,
- ScrollViewPropsAndroid,
- Touchable {
- contentContainerClassName?: string;
- indicatorClassName?: string;
- }
- interface FlatListProps extends VirtualizedListProps {
- columnWrapperClassName?: string;
- }
- interface ImageBackgroundProps extends ImagePropsBase {
- imageClassName?: string;
- }
- interface ImagePropsBase {
- className?: string;
- cssInterop?: boolean;
- }
- interface ViewProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface TextInputProps {
- placeholderClassName?: string;
- }
- interface TextProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface SwitchProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface InputAccessoryViewProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface TouchableWithoutFeedbackProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface StatusBarProps {
- className?: string;
- cssInterop?: boolean;
- }
- interface KeyboardAvoidingViewProps extends ViewProps {
- contentContainerClassName?: string;
- }
- interface ModalBaseProps {
- presentationClassName?: string;
- }
-}
+///
diff --git a/example/package.json b/example/package.json
index 38b14908..294de3bd 100644
--- a/example/package.json
+++ b/example/package.json
@@ -11,17 +11,21 @@
"web": "expo start --web"
},
"dependencies": {
- "@expo/metro-runtime": "~6.1.2",
+ "@babel/core": "^7.29.0",
+ "@expo/metro-config": "57.0.12",
+ "@expo/metro-runtime": "~57.0.15",
+ "@react-native/metro-config": "0.86.3",
"@tailwindcss/postcss": "^4.1.11",
- "expo": "54.0.10",
- "expo-status-bar": "~3.0.8",
- "react": "19.1.0",
- "react-dom": "19.1.0",
- "react-native": "0.81.4",
+ "expo": "57.0.22",
+ "expo-status-bar": "~57.0.1",
+ "lightningcss": "^1.30.1",
+ "react": "19.2.3",
+ "react-dom": "19.2.3",
+ "react-native": "0.86.3",
"react-native-css": "link:../",
- "react-native-reanimated": "~4.1.0",
- "react-native-web": "~0.21.1",
- "react-native-worklets": "~0.5.0"
+ "react-native-reanimated": "4.5.1",
+ "react-native-web": "~0.21.0",
+ "react-native-worklets": "0.10.1"
},
"private": true
}
diff --git a/node/__tests__/cache-version.mjs b/node/__tests__/cache-version.mjs
new file mode 100644
index 00000000..f1f0bac7
--- /dev/null
+++ b/node/__tests__/cache-version.mjs
@@ -0,0 +1,99 @@
+import assert from "node:assert/strict";
+import {
+ copyFileSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { test } from "node:test";
+
+const require = createRequire(import.meta.url);
+const helper = require.resolve("../../dist/commonjs/metro/cache-version.js");
+
+/** @param {import("node:test").TestContext} t */
+function fixture(t) {
+ const root = mkdtempSync(join(tmpdir(), "css-cache-version-"));
+ t.after(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+ mkdirSync(join(root, "metro"));
+ mkdirSync(join(root, "compiler"));
+ copyFileSync(helper, join(root, "metro/cache-version.cjs"));
+ writeFileSync(join(root, "compiler/value.js"), "exports.value = 14;");
+ return {
+ root,
+ key: /** @type {{getCacheVersion: (version?: string, options?: object) => string}} */ (
+ require(join(root, "metro/cache-version.cjs"))
+ ).getCacheVersion,
+ };
+}
+
+await test("unchanged input and relocated packages have the same fingerprint", (t) => {
+ const a = fixture(t),
+ b = fixture(t);
+ assert.equal(a.key("user", {}), a.key("user", {}));
+ assert.equal(a.key("user", {}), b.key("user", {}));
+});
+
+await test("compiler code changes invalidate and restoration recovers the key", (t) => {
+ const { root, key } = fixture(t);
+ const before = key("user", {});
+ writeFileSync(join(root, "compiler/value.js"), "exports.value = 18;");
+ assert.notEqual(key("user", {}), before);
+ writeFileSync(join(root, "compiler/value.js"), "exports.value = 14;");
+ assert.equal(key("user", {}), before);
+});
+
+await test("new source modules invalidate and removal recovers the key", (t) => {
+ const { root, key } = fixture(t);
+ const before = key("user", {});
+ writeFileSync(join(root, "compiler/new.js"), "exports.value = 18;");
+ assert.notEqual(key("user", {}), before);
+ rmSync(join(root, "compiler/new.js"));
+ assert.equal(key("user", {}), before);
+});
+
+await test("compiler options invalidate the cache", (t) => {
+ const { key } = fixture(t);
+ assert.notEqual(
+ key("user", { inlineRem: 14 }),
+ key("user", { inlineRem: 18 }),
+ );
+ assert.notEqual(key("user", { inlineVariables: false }), key("user", {}));
+ assert.notEqual(key("user", { features: { test: true } }), key("user", {}));
+});
+
+await test("user cacheVersion is preserved and remains an invalidation input", (t) => {
+ const { key } = fixture(t);
+ assert.match(key("user", {}), /^user:react-native-css:[0-9a-f]{64}$/);
+ assert.notEqual(key("user", {}), key("other", {}));
+ assert.equal(key(undefined, undefined), key("", {}));
+});
+
+await test("maps, declarations, tests, and unrelated files do not invalidate", (t) => {
+ const { root, key } = fixture(t);
+ const before = key("user", {});
+ mkdirSync(join(root, "compiler/__tests__"));
+ for (const name of [
+ "compiler/value.js.map",
+ "compiler/value.d.ts",
+ "compiler/__tests__/value.js",
+ "compiler/value.test.js",
+ "compiler/value.spec.ts",
+ "README.md",
+ ]) {
+ writeFileSync(join(root, name), "ignored");
+ }
+ assert.equal(key("user", {}), before);
+});
+
+await test("source condition TypeScript modules invalidate", (t) => {
+ const { root, key } = fixture(t);
+ const before = key("user", {});
+ writeFileSync(join(root, "compiler/source.ts"), "export const value = 18;");
+ assert.notEqual(key("user", {}), before);
+});
diff --git a/node/__tests__/component-registry.mjs b/node/__tests__/component-registry.mjs
new file mode 100644
index 00000000..36aa58a8
--- /dev/null
+++ b/node/__tests__/component-registry.mjs
@@ -0,0 +1,115 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import path from "node:path";
+import process from "node:process";
+import { test } from "node:test";
+import vm from "node:vm";
+
+const require = createRequire(import.meta.url);
+const root = String(
+ process.env.CSS_COMPONENT_REGISTRY_ROOT ??
+ path.resolve(import.meta.dirname, "../.."),
+);
+const rnSource = fs.readFileSync(require.resolve("react-native"), "utf8");
+const rnKeys = [...rnSource.matchAll(/^ {2}get (\w+)\(\) \{/gm)].map((match) =>
+ String(match[1]),
+);
+assert(
+ rnKeys.length > 80,
+ "React Native export declarations were not recognized",
+);
+const wrappers = [
+ "ActivityIndicator",
+ "Button",
+ "FlatList",
+ "Image",
+ "ImageBackground",
+ "KeyboardAvoidingView",
+ "Pressable",
+ "ScrollView",
+ "Switch",
+ "Text",
+ "TextInput",
+ "TouchableHighlight",
+ "TouchableOpacity",
+ "TouchableWithoutFeedback",
+ "View",
+ "VirtualizedList",
+];
+
+/** @param {string} format */
+function registry(format) {
+ /** @type {string[]} */
+ const requests = [];
+ /** @type {Map>} */
+ const components = new Map();
+ /** @type {Record} */
+ const core = Object.fromEntries(
+ rnKeys.map((name) => [name, { name, module: "react-native" }]),
+ );
+ for (const name of wrappers)
+ components.set("./" + name, { [name]: { name, module: "./" + name } });
+ /** @type {{exports: Record}} */
+ const module = { exports: {} };
+ const filename = path.join(root, "dist", format, "components/index.cjs");
+ vm.runInNewContext(
+ fs.readFileSync(filename, "utf8"),
+ {
+ module,
+ /** @param {string} specifier */
+ require(specifier) {
+ requests.push(specifier);
+ if (specifier === "react-native") return core;
+ assert(
+ components.has(specifier),
+ "Unexpected component module " + specifier,
+ );
+ return components.get(specifier);
+ },
+ },
+ { filename },
+ );
+ return { exports: module.exports, requests, components, core };
+}
+
+for (const format of ["commonjs", "module"]) {
+ void test(
+ format +
+ " component registry preserves the installed React Native export surface lazily",
+ () => {
+ const result = registry(format);
+ assert.deepEqual(result.requests, []);
+ const names = Object.getOwnPropertyNames(result.exports);
+ assert.deepEqual(
+ rnKeys.filter((name) => !names.includes(name)),
+ [],
+ );
+ for (const name of rnKeys.filter((name) => !wrappers.includes(name))) {
+ assert.equal(
+ result.exports[name],
+ result.core[name],
+ "Incorrect core forwarding: " + name,
+ );
+ }
+ },
+ );
+ void test(
+ format +
+ " component registry uses every styled wrapper, including TouchableWithoutFeedback",
+ () => {
+ const result = registry(format);
+ for (const name of wrappers) {
+ assert.equal(
+ result.exports[name],
+ result.components.get("./" + name)?.[name],
+ "Incorrect wrapper: " + name,
+ );
+ }
+ assert.deepEqual(
+ result.requests,
+ wrappers.map((name) => "./" + name),
+ );
+ },
+ );
+}
diff --git a/node/__tests__/lightningcss-loader.mjs b/node/__tests__/lightningcss-loader.mjs
new file mode 100644
index 00000000..05eec02c
--- /dev/null
+++ b/node/__tests__/lightningcss-loader.mjs
@@ -0,0 +1,139 @@
+import assert from "node:assert/strict";
+import {
+ copyFileSync,
+ mkdirSync,
+ mkdtempSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { env } from "node:process";
+import { test } from "node:test";
+
+const require = createRequire(import.meta.url);
+const override = env.CSS_LOADER_UNDER_TEST;
+const helper =
+ typeof override === "string"
+ ? override
+ : require.resolve("../../dist/commonjs/compiler/lightningcss-loader.js");
+
+/** @param {import("node:test").TestContext} t */
+function fixture(t) {
+ const root = mkdtempSync(join(tmpdir(), "css-lightning-loader-"));
+ t.after(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+ /** @param {string} file @param {string} content */
+ const put = (file, content) => {
+ mkdirSync(dirname(join(root, file)), { recursive: true });
+ writeFileSync(join(root, file), content);
+ };
+ copyFileSync(helper, join(root, "loader.cjs"));
+ return {
+ put,
+ expo() {
+ put(
+ "node_modules/@expo/metro-config/package.json",
+ JSON.stringify({ name: "@expo/metro-config", version: "57.0.12" }),
+ );
+ },
+ /** @param {string} version */
+ lightning(
+ version,
+ nested = false,
+ code = 'exports.transform = () => "' +
+ version +
+ '"; exports.Features = { selected: "' +
+ version +
+ '" };',
+ ) {
+ const base =
+ "node_modules/" +
+ (nested ? "@expo/metro-config/node_modules/" : "") +
+ "lightningcss/";
+ put(
+ base + "package.json",
+ JSON.stringify({
+ name: "lightningcss",
+ version,
+ exports: { require: "./node/index.js" },
+ }),
+ );
+ put(base + "node/index.js", code);
+ },
+ load() {
+ const loader =
+ /** @type {{lightningcssLoader: () => {lightningcss: () => string, Features: {selected: string}}}} */ (
+ require(join(root, "loader.cjs"))
+ );
+ return loader.lightningcssLoader();
+ },
+ };
+}
+
+await test("uses the Expo dependency before the consumer dependency", (t) => {
+ const f = fixture(t);
+ f.expo();
+ f.lightning("1.30.1", true);
+ f.lightning("1.30.2");
+ const result = f.load();
+ assert.equal(result.lightningcss(), "1.30.1");
+ assert.deepEqual(result.Features, { selected: "1.30.1" });
+});
+await test("rejects Expo's blocked version even when the consumer has a good version", (t) => {
+ const f = fixture(t);
+ f.expo();
+ f.lightning("1.30.2", true);
+ f.lightning("1.30.1");
+ assert.throws(
+ () => f.load(),
+ /lightningcss version 1\.30\.2 has a critical bug/,
+ );
+});
+await test("rejects the blocked version in a standalone consumer", (t) => {
+ const f = fixture(t);
+ f.lightning("1.30.2");
+ assert.throws(
+ () => f.load(),
+ /lightningcss version 1\.30\.2 has a critical bug/,
+ );
+});
+await test("standalone consumer loads a supported version", (t) => {
+ const f = fixture(t);
+ f.lightning("1.30.1");
+ assert.equal(f.load().lightningcss(), "1.30.1");
+});
+await test("Expo without a private dependency uses the hoisted consumer copy", (t) => {
+ const f = fixture(t);
+ f.expo();
+ f.lightning("1.30.1");
+ assert.equal(f.load().lightningcss(), "1.30.1");
+});
+await test("missing compiler reports the engine installation error", (t) => {
+ const f = fixture(t);
+ f.expo();
+ assert.throws(() => f.load(), /unable to determine the path to lightningcss/);
+});
+await test("native compiler load errors propagate without silently selecting another copy", (t) => {
+ const f = fixture(t);
+ f.expo();
+ f.lightning("1.30.1", true, 'throw new Error("native binding missing");');
+ f.lightning("1.30.1");
+ assert.throws(() => f.load(), /native binding missing/);
+});
+await test("later versions are not rejected by the exact version guard", (t) => {
+ const f = fixture(t);
+ f.lightning("1.30.3");
+ assert.equal(f.load().lightningcss(), "1.30.3");
+});
+
+await test("missing optional package metadata does not prevent loading", (t) => {
+ const f = fixture(t);
+ f.put(
+ "node_modules/lightningcss.js",
+ 'exports.transform = () => "custom"; exports.Features = {};',
+ );
+ assert.equal(f.load().lightningcss(), "custom");
+});
diff --git a/node/__tests__/tooling.mjs b/node/__tests__/tooling.mjs
new file mode 100644
index 00000000..bd79d564
--- /dev/null
+++ b/node/__tests__/tooling.mjs
@@ -0,0 +1,53 @@
+import assert from "node:assert/strict";
+import { createRequire } from "node:module";
+import { test } from "node:test";
+
+const require = createRequire(import.meta.url);
+
+await test("Node ESM compiler uses the CommonJS compiler", async () => {
+ const esm = await import("react-native-css/compiler");
+ const commonjs = require("react-native-css/compiler");
+ assert.equal(esm.compile, commonjs.compile);
+ const result = esm.compile(".probe { width: 37px }").stylesheet();
+ assert.equal(result.s[0][0], "probe");
+ assert.equal(result.s[0][1][0].d[0].width, 37);
+});
+
+await test("Node ESM Metro accepts object and lazy configurations", async () => {
+ const esm = await import("react-native-css/metro");
+ const commonjs = require("react-native-css/metro");
+ assert.equal(esm.withReactNativeCSS, commonjs.withReactNativeCSS);
+ const config = { resolver: { sourceExts: ["js"] }, marker: 37 };
+ const options = { disableTypeScriptGeneration: true };
+ const output = esm.withReactNativeCSS(config, options);
+ assert.equal(output.marker, 37);
+ assert.deepEqual(output.resolver.sourceExts, ["js", "css"]);
+ let calls = 0;
+ const lazy = esm.withReactNativeCSS(() => {
+ calls++;
+ return Promise.resolve(config);
+ }, options);
+ assert.equal(calls, 0);
+ assert.equal((await lazy()).marker, 37);
+ assert.equal(calls, 1);
+});
+
+await test("Node ESM Babel default remains callable and rewrites imports", async () => {
+ const esm = await import("react-native-css/babel");
+ const commonjs = require("react-native-css/babel");
+ assert.equal(esm.default, commonjs.default);
+ const preset = esm.default();
+ assert.equal(typeof preset.plugins[0], "function");
+ assert(preset.plugins.includes("react-native-worklets/plugin"));
+ const babel = require("@babel/core");
+ const result = await babel.transformAsync(
+ 'import { View } from "react-native";',
+ {
+ filename: "/tmp/node-tooling-consumer.js",
+ babelrc: false,
+ configFile: false,
+ presets: [esm.default],
+ },
+ );
+ assert.match(result.code, /react-native-css\/components/);
+});
diff --git a/node/__tests__/typescript.mjs b/node/__tests__/typescript.mjs
new file mode 100644
index 00000000..54689660
--- /dev/null
+++ b/node/__tests__/typescript.mjs
@@ -0,0 +1,173 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { createRequire } from "node:module";
+import os from "node:os";
+import path from "node:path";
+import process from "node:process";
+import { test } from "node:test";
+
+const require = createRequire(import.meta.url);
+const ts = require("typescript");
+const { setupTypeScript } =
+ /** @type {{setupTypeScript: (envPath?: string, name?: string) => void}} */ (
+ require(
+ String(
+ process.env.CSS_TYPESCRIPT_SETUP_ENTRY ??
+ "../../dist/commonjs/metro/typescript.js",
+ ),
+ )
+ );
+
+const scenarios = [
+ {
+ name: "relative inherited files",
+ config: { extends: "./config/base.json" },
+ basePath: "config/base.json",
+ base: { files: ["../src/app.ts"] },
+ },
+ { name: "implicit include", config: {} },
+ { name: "explicit include", config: { include: ["src"] } },
+ {
+ name: "inherited include",
+ config: { extends: "./base.json" },
+ base: { include: ["src"] },
+ },
+ { name: "files only", config: { files: ["src/app.ts"] } },
+ {
+ name: "inherited files",
+ config: { extends: "./base.json" },
+ base: { files: ["src/app.ts"] },
+ },
+ {
+ name: "excluded environment",
+ config: { exclude: ["react-native-css-env.d.ts"] },
+ },
+ {
+ name: "inherited exclusion",
+ config: { extends: "./base.json" },
+ base: { exclude: ["react-native-css-env.d.ts"] },
+ },
+ { name: "nested invocation", config: { include: ["src"] }, cwd: "src" },
+ {
+ name: "custom environment",
+ config: { include: ["src"] },
+ env: "custom.d.ts",
+ },
+ {
+ name: "relative inherited include",
+ config: { extends: "./config/base.json" },
+ basePath: "config/base.json",
+ base: { include: ["../src"] },
+ },
+];
+for (const scenario of scenarios) {
+ await test(`TypeScript setup includes declarations and preserves project files: ${scenario.name}`, () => {
+ const directory = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), "css-typescript-")),
+ );
+ const previous = process.cwd();
+ try {
+ fs.mkdirSync(directory + "/src");
+ fs.writeFileSync(directory + "/src/app.ts", "export const value = 1;");
+ fs.writeFileSync(directory + "/outside.ts", "export const outside = 1;");
+ fs.writeFileSync(
+ directory + "/tsconfig.json",
+ "// Preserve this project comment\n" + JSON.stringify(scenario.config),
+ );
+ if (scenario.base) {
+ const file = directory + "/" + (scenario.basePath ?? "base.json");
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(scenario.base));
+ }
+ const parsed = () =>
+ ts.getParsedCommandLineOfConfigFile(
+ directory + "/tsconfig.json",
+ {},
+ {
+ ...ts.sys,
+ onUnRecoverableConfigFileDiagnostic: (d) => {
+ throw new Error(
+ ts.flattenDiagnosticMessageText(d.messageText, "\n"),
+ );
+ },
+ },
+ );
+ const before = parsed().fileNames;
+ process.chdir(directory + (scenario.cwd ? "/" + scenario.cwd : ""));
+ const env = scenario.env ?? "react-native-css-env.d.ts";
+ setupTypeScript(scenario.env);
+ const envFile = path.resolve(env);
+ assert(fs.existsSync(envFile));
+ const after = parsed().fileNames;
+ assert(
+ after.includes(envFile),
+ "Generated declaration is absent from the TypeScript project",
+ );
+ assert.deepEqual(
+ after.filter((f) => f !== envFile).sort(),
+ before.sort(),
+ "Existing project membership changed",
+ );
+ const configBytes = fs.readFileSync(directory + "/tsconfig.json", "utf8");
+ const envBytes = fs.readFileSync(envFile, "utf8");
+ assert(configBytes.includes("// Preserve this project comment"));
+ setupTypeScript(scenario.env);
+ assert.equal(
+ fs.readFileSync(directory + "/tsconfig.json", "utf8"),
+ configBytes,
+ );
+ assert.equal(fs.readFileSync(envFile, "utf8"), envBytes);
+ } finally {
+ process.chdir(previous);
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+ });
+}
+
+await test("TypeScript setup preserves a user owned environment file", () => {
+ const directory = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), "css-typescript-")),
+ );
+ const previous = process.cwd();
+ try {
+ process.chdir(directory);
+ fs.writeFileSync("tsconfig.json", '{"include":[]}');
+ fs.writeFileSync("custom.d.ts", "// existing custom declaration\n");
+ setupTypeScript("custom.d.ts");
+ assert.equal(
+ fs.readFileSync("custom.d.ts", "utf8"),
+ "// existing custom declaration\n",
+ );
+ } finally {
+ process.chdir(previous);
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+for (const content of [
+ null,
+ "invalid config",
+ "[]",
+ "null",
+ "42",
+ "true",
+ '"hello"',
+]) {
+ await test(`TypeScript setup leaves unavailable or invalid configs alone: ${JSON.stringify(content)}`, () => {
+ const directory = fs.realpathSync(
+ fs.mkdtempSync(path.join(os.tmpdir(), "css-typescript-")),
+ );
+ const previous = process.cwd();
+ try {
+ process.chdir(directory);
+ if (content !== null) fs.writeFileSync("tsconfig.json", content);
+ setupTypeScript();
+ assert(!fs.existsSync("react-native-css-env.d.ts"));
+ if (content !== null)
+ assert.equal(fs.readFileSync("tsconfig.json", "utf8"), content);
+ } finally {
+ process.chdir(previous);
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+ });
+}
diff --git a/node/babel.mjs b/node/babel.mjs
new file mode 100644
index 00000000..0d716848
--- /dev/null
+++ b/node/babel.mjs
@@ -0,0 +1,4 @@
+// Preserve the callable default export when Node loads the preset as ESM.
+import implementation from "../dist/commonjs/babel/index.js";
+
+export default implementation.default;
diff --git a/node/compiler.mjs b/node/compiler.mjs
new file mode 100644
index 00000000..c87974dc
--- /dev/null
+++ b/node/compiler.mjs
@@ -0,0 +1,2 @@
+// Node ESM entry for the CommonJS tooling implementation.
+export { compile } from "../dist/commonjs/compiler/index.js";
diff --git a/node/metro.mjs b/node/metro.mjs
new file mode 100644
index 00000000..b50b5ad3
--- /dev/null
+++ b/node/metro.mjs
@@ -0,0 +1,2 @@
+// Node ESM entry for the CommonJS tooling implementation.
+export { withReactNativeCSS } from "../dist/commonjs/metro/index.js";
diff --git a/package.json b/package.json
index 17b9aa8c..130d8971 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@scatterlab/react-native-css",
- "version": "3.0.7-zeta.8",
+ "version": "3.1.0-rc.1-zeta.1",
"description": "Use CSS stylesheets in React Native",
"exports": {
".": {
@@ -22,7 +22,7 @@
"source": "./src/compiler/index.ts",
"import": {
"types": "./dist/typescript/module/src/compiler/index.d.ts",
- "default": "./dist/module/compiler/index.js"
+ "default": "./node/compiler.mjs"
},
"require": {
"types": "./dist/typescript/commonjs/src/compiler/index.d.ts",
@@ -33,7 +33,7 @@
"source": "./src/babel/index.ts",
"import": {
"types": "./dist/typescript/module/src/babel/index.d.ts",
- "default": "./dist/module/babel/index.js"
+ "default": "./node/babel.mjs"
},
"require": {
"types": "./dist/typescript/commonjs/src/babel/index.d.ts",
@@ -67,6 +67,30 @@
"default": "./dist/commonjs/components/react-native-safe-area-context.js"
}
},
+ "./components/copyComponentProperties": {
+ "source": "./src/components/copyComponentProperties.ts",
+ "react-native": "./src/components/copyComponentProperties.ts",
+ "import": {
+ "types": "./dist/typescript/module/src/components/copyComponentProperties.d.ts",
+ "default": "./dist/module/components/copyComponentProperties.js"
+ },
+ "require": {
+ "types": "./dist/typescript/commonjs/src/components/copyComponentProperties.d.ts",
+ "default": "./dist/commonjs/components/copyComponentProperties.js"
+ }
+ },
+ "./components/index": {
+ "source": "./src/components/index.cts",
+ "import": {
+ "default": "./dist/module/components/index.cjs",
+ "types": "./dist/typescript/module/src/components/index.d.ts"
+ },
+ "require": {
+ "default": "./dist/commonjs/components/index.cjs",
+ "types": "./dist/typescript/commonjs/src/components/index.d.ts"
+ },
+ "react-native": "./src/components/index.cts"
+ },
"./components/*": {
"source": "./src/components/*.tsx",
"react-native": "./src/components/*.tsx",
@@ -95,7 +119,7 @@
"source": "./src/metro/index.ts",
"import": {
"types": "./dist/typescript/module/src/metro/index.d.ts",
- "default": "./dist/module/metro/index.js"
+ "default": "./node/metro.mjs"
},
"require": {
"types": "./dist/typescript/commonjs/src/metro/index.d.ts",
@@ -179,12 +203,13 @@
"example": "yarn workspace react-native-css-example",
"lint": "eslint",
"prepare": "bob build",
+ "prepack": "bob build",
"prepublishOnly": "bob build",
"release": "release-it --config ./.config/release-it.config.ts",
"start": "yarn example start",
"start:build": "yarn build && yarn example build",
"start:debug": "yarn build && yarn example debug",
- "test": "NODE_OPTIONS=\"${NODE_OPTIONS:-} --experimental-vm-modules\" jest",
+ "test": "jest",
"typecheck": "tsc --noEmit"
},
"keywords": [
@@ -211,10 +236,13 @@
"files": [
"src",
"dist",
+ "node",
"types.d.ts",
"!**/__tests__",
"!**/__fixtures__",
- "!**/__mocks__"
+ "!**/__mocks__",
+ "!**/*.test.*",
+ "!**/*.spec.*"
],
"dependencies": {
"@types/debug": "^4.1.12",
@@ -230,46 +258,47 @@
"react-native": ">=0.88"
},
"devDependencies": {
- "@babel/core": "^7.28.0",
- "@commitlint/config-conventional": "^20.5.0",
+ "@babel/core": "^7.29.0",
+ "@commitlint/config-conventional": "^21.2.0",
"@eslint/js": "^10.0.1",
- "@expo/metro-config": "~54.0.5",
+ "@expo/metro-config": "57.0.12",
"@ianvs/prettier-plugin-sort-imports": "^4.4.2",
+ "@react-native/jest-preset": "0.86.3",
+ "@react-native/metro-config": "0.86.3",
"@release-it/conventional-changelog": "10.0.1",
- "@tailwindcss/postcss": "^4.1.12",
+ "@tailwindcss/node": "^4.1.12",
"@testing-library/react-native": "^13.3.3",
"@tsconfig/react-native": "^3.0.6",
"@types/babel__core": "^7",
"@types/jest": "^30.0.0",
- "@types/react": "^19.1.10",
+ "@types/react": "~19.2.0",
"@types/react-test-renderer": "^19",
"babel-plugin-tester": "^12.0.0",
- "babel-preset-expo": "~54.0.3",
+ "babel-preset-expo": "57.0.11",
"commitlint": "^20.0.0",
"eas-build-cache-provider": "^16.4.2",
"eslint": "^9.30.1",
"eslint-config-prettier": "^10.1.5",
"eslint-plugin-prettier": "^5.5.1",
- "expo": "54.0.10",
+ "expo": "57.0.22",
"jest": "^29.7.0",
- "jest-expo": "~56.0.5",
+ "jest-expo": "57.0.5",
"lefthook": "^2.1.5",
"lightningcss": "^1.30.1",
"metro-runtime": "^0.84.2",
- "postcss": "^8.5.6",
"prettier": "^3.6.2",
- "react": "19.1.0",
- "react-native": "0.81.4",
+ "react": "19.2.3",
+ "react-native": "0.86.3",
"react-native-builder-bob": "^0.43.0",
- "react-native-reanimated": "~4.1.0",
- "react-native-safe-area-context": "5.6.1",
- "react-native-worklets": "~0.5.0",
+ "react-native-reanimated": "4.5.1",
+ "react-native-safe-area-context": "~5.7.0",
+ "react-native-worklets": "0.10.1",
"react-refresh": "^0.17.0",
- "react-test-renderer": "19.1.0",
+ "react-test-renderer": "19.2.3",
"release-it": "^20.2.1",
"tailwindcss": "^4.1.12",
"tailwindcss-safe-area": "^1.1.0",
- "typescript": "^5.9.2",
+ "typescript": "~6.0.3",
"typescript-eslint": "^8.40.0"
},
"react-native-builder-bob": {
@@ -288,7 +317,12 @@
"esm": true
}
],
- "typescript"
+ [
+ "typescript",
+ {
+ "project": "tsconfig.build.json"
+ }
+ ]
]
},
"packageManager": "yarn@4.9.2",
diff --git a/src/__fixtures__/types/component-mapping.tsx b/src/__fixtures__/types/component-mapping.tsx
new file mode 100644
index 00000000..d18a1213
--- /dev/null
+++ b/src/__fixtures__/types/component-mapping.tsx
@@ -0,0 +1,21 @@
+/* eslint-disable @typescript-eslint/no-deprecated -- Verify the supported vars migration input. */
+import { FlatList, Pressable, ScrollView } from "react-native";
+
+import { vars as publicVars } from "react-native-css";
+import { View } from "react-native-css/components";
+import { styled, vars } from "react-native-css/native";
+
+// Type checks cover recursive React Native component props without widening paths.
+styled(FlatList, { className: "style" });
+styled(Pressable, { className: "style" });
+styled(ScrollView, {
+ contentClassName: "contentContainerStyle",
+});
+
+// @ts-expect-error The mapping must still reject an unknown destination.
+styled(ScrollView, { className: "missingStyle" });
+
+export const variableStyle = ;
+export const publicVariableStyle = (
+
+);
diff --git a/src/__tests__/babel/no-filename.test.ts b/src/__tests__/babel/no-filename.test.ts
new file mode 100644
index 00000000..5f8776e3
--- /dev/null
+++ b/src/__tests__/babel/no-filename.test.ts
@@ -0,0 +1,15 @@
+import { transformSync } from "@babel/core";
+
+import plugin from "../../babel/import-plugin";
+
+test("a file transformed without a filename is left as written", () => {
+ const source = `import { View } from "react-native";`;
+
+ const output = transformSync(source, {
+ configFile: false,
+ babelrc: false,
+ plugins: [plugin],
+ })?.code;
+
+ expect(output).toBe(source);
+});
diff --git a/src/__tests__/babel/plugin.test.mts b/src/__tests__/babel/plugin.test.ts
similarity index 62%
rename from src/__tests__/babel/plugin.test.mts
rename to src/__tests__/babel/plugin.test.ts
index 04144446..18d3acaa 100644
--- a/src/__tests__/babel/plugin.test.mts
+++ b/src/__tests__/babel/plugin.test.ts
@@ -11,35 +11,38 @@ pluginTester({
},
tests: {
"rewrite imports from within React Native": {
- only: true,
code: `import View from '../View/View';`,
- output: `import { View } from "react-native-css/dist/module/components/View";`,
+ output: `import { View } from "react-native-css/components/View";`,
babelOptions: {
filename:
"node_modules/react-native/Libraries/Components/ScrollView/ScrollView.js",
},
},
"rewrite react-native imports": {
+ babelOptions: { filename: "/consumer/component.js" },
code: `import { View, Text, StyleSheet, Dimensions } from "react-native";`,
- output: `import { View } from "react-native-css/dist/module/components/View";
-import { Text } from "react-native-css/dist/module/components/Text";
+ output: `import { View } from "react-native-css/components/View";
+import { Text } from "react-native-css/components/Text";
import { StyleSheet } from "react-native";
import { Dimensions } from "react-native";`,
},
"rewrite react-native deep imports": {
+ babelOptions: { filename: "/consumer/component.js" },
code: `import { View } from "react-native/lib/components/View";`,
- output: `import { View } from "react-native-css/dist/module/components/View";`,
+ output: `import { View } from "react-native-css/components/View";`,
},
"rewrite react-native-web imports": {
+ babelOptions: { filename: "/consumer/component.js" },
code: `import { View, Text, StyleSheet, Dimensions } from "react-native-web";`,
- output: `import { View } from "react-native-css/dist/module/components/View";
-import { Text } from "react-native-css/dist/module/components/Text";
+ output: `import { View } from "react-native-css/components/View";
+import { Text } from "react-native-css/components/Text";
import { StyleSheet } from "react-native-web";
import { Dimensions } from "react-native-web";`,
},
"rewrite react-native-web deep imports": {
+ babelOptions: { filename: "/consumer/component.js" },
code: `import { View } from "react-native-web/lib/components/View";`,
- output: `import { View } from "react-native-css/dist/module/components/View";`,
+ output: `import { View } from "react-native-css/components/View";`,
},
},
});
diff --git a/src/__tests__/babel/react-native-web.test.ts b/src/__tests__/babel/react-native-web.test.ts
index 5d54a4da..cdd322da 100644
--- a/src/__tests__/babel/react-native-web.test.ts
+++ b/src/__tests__/babel/react-native-web.test.ts
@@ -1,9 +1,15 @@
import { pluginTester, type TestObject } from "babel-plugin-tester";
+import { format } from "prettier";
+
import plugin from "../../babel/import-plugin";
const appendTitles = (tests: TestObject[]) => {
- return tests.map((test) => ({ ...test, title: test.code }));
+ return tests.map((test) => ({
+ ...test,
+ title: test.code,
+ babelOptions: { filename: "/consumer/component.js", ...test.babelOptions },
+ }));
};
describe("react-native-web", () => {
@@ -14,6 +20,27 @@ describe("react-native-web", () => {
plugins: ["@babel/plugin-syntax-jsx"],
},
tests: appendTitles([
+ {
+ code: `import typeof View from 'react-native-web';`,
+ output: `import typeof View from "react-native-web";`,
+ babelOptions: { parserOpts: { plugins: ["flow"] } },
+ formatResult: (code) => format(code, { parser: "babel-flow" }),
+ },
+ {
+ code: `import { type View, Text } from 'react-native-web';`,
+ output: `import { type View } from "react-native-web";
+import { Text } from "react-native-css/components/Text";`,
+ babelOptions: { parserOpts: { plugins: ["typescript"] } },
+ },
+ {
+ code: `import type { View } from 'react-native-web';`,
+ output: `import type { View } from "react-native-web";`,
+ babelOptions: { parserOpts: { plugins: ["typescript"] } },
+ },
+ {
+ code: `import NativeView from 'react-native-web/dist/exports/View';`,
+ output: `import { View as NativeView } from "react-native-css/components/View";`,
+ },
/* import tests */
{
code: `import 'react-native-web';`,
@@ -74,19 +101,27 @@ describe("react-native-web", () => {
},
{
code: `const _Text = _interopRequireDefault(require('react-native-web/dist/Text'));`,
- output: `const { Text: _Text } = require("react-native-css/components/Text");`,
+ output: `const _Text = _interopRequireDefault(
+ require("react-native-css/components/Text"),
+);`,
},
{
code: `const _Text = _interopRequireDefault(require('react-native-web/dist/modules/Text'));`,
- output: `const { Text: _Text } = require("react-native-css/components/Text");`,
+ output: `const _Text = _interopRequireDefault(
+ require("react-native-css/components/Text"),
+);`,
},
{
code: `const _Text = _interopRequireDefault(require('react-native-web/dist/cjs/Text'));`,
- output: `const { Text: _Text } = require("react-native-css/components/Text");`,
+ output: `const _Text = _interopRequireDefault(
+ require("react-native-css/components/Text"),
+);`,
},
{
code: `const View = _interopRequireDefault(require('../View'));`,
- output: `const { View } = require("react-native-css/components/View");`,
+ output: `const View = _interopRequireDefault(
+ require("react-native-css/components/View"),
+);`,
babelOptions: {
filename: "react-native-web/dist/modules/ScrollView/index.js",
},
diff --git a/src/__tests__/babel/react-native.test.ts b/src/__tests__/babel/react-native.test.ts
index a0472936..6ec71b3c 100644
--- a/src/__tests__/babel/react-native.test.ts
+++ b/src/__tests__/babel/react-native.test.ts
@@ -1,9 +1,15 @@
import { pluginTester, type TestObject } from "babel-plugin-tester";
+import { format } from "prettier";
+
import plugin from "../../babel/import-plugin";
const appendTitles = (tests: TestObject[]) => {
- return tests.map((test) => ({ ...test, title: test.code }));
+ return tests.map((test) => ({
+ ...test,
+ title: test.code,
+ babelOptions: { filename: "/consumer/component.js", ...test.babelOptions },
+ }));
};
describe("react-native", () => {
@@ -15,6 +21,27 @@ describe("react-native", () => {
filename: "/someFile.js",
},
tests: appendTitles([
+ {
+ code: `import typeof View from 'react-native';`,
+ output: `import typeof View from "react-native";`,
+ babelOptions: { parserOpts: { plugins: ["flow"] } },
+ formatResult: (code) => format(code, { parser: "babel-flow" }),
+ },
+ {
+ code: `import { type View, Text } from 'react-native';`,
+ output: `import { type View } from "react-native";
+import { Text } from "react-native-css/components/Text";`,
+ babelOptions: { parserOpts: { plugins: ["typescript"] } },
+ },
+ {
+ code: `import type { View } from 'react-native';`,
+ output: `import type { View } from "react-native";`,
+ babelOptions: { parserOpts: { plugins: ["typescript"] } },
+ },
+ {
+ code: `import NativeView from 'react-native/Libraries/Components/View/View';`,
+ output: `import { View as NativeView } from "react-native-css/components/View";`,
+ },
{
code: `import 'react-native';`,
output: `import "react-native-css/components";`,
diff --git a/src/__tests__/babel/runtime-interop.test.ts b/src/__tests__/babel/runtime-interop.test.ts
new file mode 100644
index 00000000..57d96645
--- /dev/null
+++ b/src/__tests__/babel/runtime-interop.test.ts
@@ -0,0 +1,118 @@
+import { resolve } from "node:path";
+import { transformSync } from "@babel/core";
+
+import plugin from "../../babel/import-plugin";
+
+const component = () => null;
+function execute(
+ source: string,
+ modules: Record,
+ filename = "/consumer/index.js",
+) {
+ const output = transformSync(source, {
+ configFile: false,
+ babelrc: false,
+ filename,
+ plugins: [plugin],
+ })?.code;
+ expect(output).toBeDefined();
+ if (output === undefined || output === null)
+ throw new Error("Missing transformed output");
+ const module = { exports: {} };
+ // Execute emitted CommonJS against explicit module identities.
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
+ const run = new Function("require", "module", output) as (
+ require: (id: string) => unknown,
+ module: { exports: unknown },
+ ) => void;
+ run((id: string) => {
+ if (!(id in modules)) throw new Error(`Unexpected import ${id}`);
+ return modules[id];
+ }, module);
+ return module.exports;
+}
+
+test.each([
+ "react-native-web/dist/Text",
+ "react-native-web/dist/cjs/Text",
+ "react-native-web/dist/modules/Text",
+])("preserves default interop for %s", (source) => {
+ expect(
+ execute(
+ `function _interopRequireDefault(value) { return value && value.__esModule ? value : { default: value }; }
+ const Text = _interopRequireDefault(require(${JSON.stringify(source)}));
+ module.exports = Text.default;`,
+ {
+ "react-native-css/components/Text": {
+ __esModule: true,
+ default: component,
+ Text: component,
+ },
+ },
+ ),
+ ).toBe(component);
+});
+
+test("preserves the default wrapper for a CommonJS component", () => {
+ expect(
+ execute(
+ `function _interopRequireDefault(value) { return value && value.__esModule ? value : { default: value }; }
+ const Text = _interopRequireDefault(require("react-native-web/dist/Text"));
+ module.exports = Text.default;`,
+ { "react-native-css/components/Text": component },
+ ),
+ ).toBe(component);
+});
+
+test.each(["react-native", "react-native-web"])(
+ "preserves computed destructuring keys in %s",
+ (source) => {
+ expect(
+ execute(
+ `const View = "Text";
+ const { [View]: Selected } = require(${JSON.stringify(source)});
+ module.exports = Selected;`,
+ { [source]: { Text: component } },
+ ),
+ ).toBe(component);
+ },
+);
+
+test.each([
+ 'const { Text, ...other } = require("react-native"); module.exports = Text;',
+ 'const { Text = null } = require("react-native"); module.exports = Text;',
+ 'const Text = require("react-native").Text; module.exports = Text;',
+ 'const { Text } = require("react-native"), other = 1; module.exports = Text;',
+ 'let Text; Text = require("react-native").Text; module.exports = Text;',
+ 'const name = "react-native"; const { Text } = require(name); module.exports = Text;',
+])("preserves unsupported dynamic or combined declaration: %s", (source) => {
+ expect(execute(source, { "react-native": { Text: component } })).toBe(
+ component,
+ );
+});
+
+test("does not rewrite the package own source imports", () => {
+ expect(
+ execute(
+ 'const { Text } = require("react-native"); module.exports = Text;',
+ { "react-native": { Text: component } },
+ resolve(__dirname, "../../components/Text.tsx"),
+ ),
+ ).toBe(component);
+});
+
+test.each(["react-native", "react-native-web"])(
+ "does not rewrite a locally bound require for %s",
+ (name) => {
+ expect(
+ execute(
+ `function load(require) {
+ const { Text } = require(${JSON.stringify(name)});
+ return Text;
+ }
+ module.exports = load(name => ({ Text: name === ${JSON.stringify(name)} ? 37 : 99 }));`,
+ {},
+ ),
+ ).toBe(37);
+ },
+);
diff --git a/src/__tests__/babel/smoke.test.ts b/src/__tests__/babel/smoke.test.ts
index ad5c202c..89df40ac 100644
--- a/src/__tests__/babel/smoke.test.ts
+++ b/src/__tests__/babel/smoke.test.ts
@@ -3,7 +3,11 @@ import { pluginTester, type TestObject } from "babel-plugin-tester";
import plugin from "../../babel/import-plugin";
const appendTitles = (tests: TestObject[]) => {
- return tests.map((test) => ({ ...test, title: test.code }));
+ return tests.map((test) => ({
+ ...test,
+ title: test.code,
+ babelOptions: { filename: "/consumer/component.js", ...test.babelOptions },
+ }));
};
describe("plugin smoke tests", () => {
diff --git a/src/__tests__/babel/tsconfig.json b/src/__tests__/babel/tsconfig.json
index 2b8f5fbd..dcb0087b 100644
--- a/src/__tests__/babel/tsconfig.json
+++ b/src/__tests__/babel/tsconfig.json
@@ -1,6 +1,4 @@
{
"extends": "../../../tsconfig.json",
- "include": [
- "./*"
- ]
-}
\ No newline at end of file
+ "include": ["./*"]
+}
diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx
index 7a9fbea8..a1a6906b 100644
--- a/src/__tests__/compiler/compiler.test.tsx
+++ b/src/__tests__/compiler/compiler.test.tsx
@@ -77,71 +77,26 @@ test(":root CSS variables with media queries", () => {
});
});
-test.skip("removes unused CSS variables", () => {
- const compiled = compile(`
- .test {
- --blue: blue;
- --green: green;
- --red: red;
- color: var(--red, var(--blue))
- }
- `);
-
- expect(compiled.stylesheet()).toStrictEqual({
- s: [
- [
- "test",
- [
- [
- {
- s: [1, 1],
- v: [
- ["blue", "blue"],
- ["red", "red"],
- ],
- dv: 1,
- d: [[[{}, "var", ["red", [{}, "var", ["blue"]]]], "color", 1]],
- },
- ],
- ],
- ],
- ],
- });
+test("removes unused CSS variables while preserving the resolved value", () => {
+ const result = compile(
+ `.test { --blue: blue; --green: green; --red: red; color: var(--red, var(--blue)); }`,
+ ).stylesheet();
+ const rule = result.s?.[0]?.[1][0];
+ expect(rule?.d).toContainEqual({ color: "#f00" });
+ expect(
+ rule?.v?.filter(([name]) => ["red", "blue", "green"].includes(name)) ?? [],
+ ).toEqual([]);
});
-test.skip("preserves unused CSS variables with preserve-variables", () => {
- const compiled = compile(`
- @react-native config {
- preserve-variables: --green, --blue;
- }
-
- .test {
- --green: green;
- --red: red;
- color: var(--red)
- }
- `);
-
- expect(compiled.stylesheet()).toStrictEqual({
- s: [
- [
- "test",
- [
- [
- {
- s: [1, 1],
- v: [
- ["green", "green"],
- ["red", "red"],
- ],
- d: [[[{}, "var", ["red"]], "color", 1]],
- dv: 1,
- },
- ],
- ],
- ],
- ],
- });
+test("preserves excluded CSS variables using the public compiler option", () => {
+ const result = compile(
+ `.test { --green: green; --red: red; color: var(--red); }`,
+ { inlineVariables: { exclude: ["--green"] } },
+ ).stylesheet();
+ const rule = result.s?.[0]?.[1][0];
+ expect(rule?.v).toContainEqual(["green", "green"]);
+ expect(rule?.d).toContainEqual({ color: "#f00" });
+ expect(rule?.v?.some(([name]) => name === "red")).toBe(false);
});
test("multiple rules with same selector", () => {
@@ -187,107 +142,84 @@ test("multiple rules with same selector", () => {
});
});
-test.skip("transitions", () => {
- const compiled = compile(`
- .test {
- color: red;
- transition: color 1s linear;
- }
- `);
-
- expect(compiled.stylesheet()).toStrictEqual({
- s: [
- [
- "test",
- [
- [
- {
- d: [
- {
- color: "#ff0000",
- transitionDelay: [0],
- transitionDuration: [1000],
- transitionProperty: ["color"],
- transitionTimingFunction: ["linear"],
- },
- ],
- s: [1, 1],
- },
- ],
- ],
- ],
- ],
+test("transitions retain duration, property, timing, and the animated rule marker", () => {
+ const rule = compile(
+ `.test { color: red; transition: color 1s linear; }`,
+ ).stylesheet().s?.[0]?.[1][0];
+ expect(rule?.a).toBe(true);
+ expect(rule?.d).toContainEqual({
+ color: "#f00",
+ transitionProperty: ["color"],
+ transitionDuration: [1000],
+ transitionDelay: [0],
+ transitionTimingFunction: "linear",
});
});
-test.skip("animations", () => {
- const compiled = compile(`
- .test {
- animation: spin 1s linear infinite;
- }
+test("animations preserve named keyframes and their timing contract", () => {
+ const result = compile(
+ `.test { animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } }`,
+ ).stylesheet();
+ const rule = result.s?.[0]?.[1][0];
+ expect(rule?.a).toBe(true);
+ expect(rule?.d).toContainEqual(
+ expect.objectContaining({
+ animationDuration: [1000],
+ animationIterationCount: ["infinite"],
+ animationTimingFunction: "linear",
+ }),
+ );
+ expect(rule?.d).toContainEqual([
+ [[{}, "animationName", ["spin"], 1]],
+ "animationName",
+ ]);
+ expect(result.k).toEqual([
+ [
+ "spin",
+ [["to", [[[{}, "transform", [[{}, "rotate", "360deg"]]], "transform"]]]],
+ ],
+ ]);
+});
- @keyframes spin {
- to {
- transform: rotate(360deg);
- }
- }
- `);
+// css-variables-1 §2.1: a custom property's value is its tokens, its commas among them
+test.each([
+ ["blue, green", [["blue"], ["green"]]],
+ ["blue ,green", [["blue"], ["green"]]],
+ ["blue/**/, green", [["blue"], ["green"]]],
+ ["blue green", ["blue", "green"]],
+ [
+ "1px 2px #000, 3px 4px #fff",
+ [
+ [1, 2, "#000"],
+ [3, 4, "#fff"],
+ ],
+ ],
+ ["1px 2px #000 3px 4px #fff", [1, 2, "#000", 3, 4, "#fff"]],
+])("--test: %s keeps its separator", (value, expected) => {
+ const compiled = compile(`:root { --test: ${value}; }`, {
+ inlineVariables: false,
+ });
expect(compiled.stylesheet()).toStrictEqual({
- k: [
- [
- "spin",
- [
- {
- 0: { transform: [[{}, "rotate", "0deg"]] },
- 100: { transform: [[{}, "rotate", "360deg"]] },
- },
- ],
- ],
- ],
- s: [
- [
- "test",
- [
- [
- {
- a: 1,
- d: [
- {
- animationDelay: [0],
- animationDirection: ["normal"],
- animationDuration: [1000],
- animationFillMode: ["none"],
- animationIterationCount: ["infinite"],
- animationName: [[{}, "animation", ["spin"], 1]],
- animationPlayState: ["running"],
- animationTimingFunction: ["linear"],
- },
- ],
- s: [1, 1],
- },
- ],
- ],
- ],
- ],
+ vr: [["test", [[expected]]]],
});
});
-test("breaks apart comma separated variables", () => {
- const compiled = compile(
- `
- :root {
- --test: blue, green;
- }
- `,
- {
- inlineVariables: false,
- },
- );
+test.each([
+ ["var(--a), var(--b)", [[[{}, "var", "a", 1]], [[{}, "var", "b", 1]]]],
+ [
+ "var(--a) var(--b)",
+ [
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ ],
+ ],
+])("box-shadow: %s keeps its separator", (value, expected) => {
+ const compiled = compile(`.my-class { box-shadow: ${value}; }`);
- expect(compiled.stylesheet()).toStrictEqual({
- vr: [["test", [[["blue", "green"]]]]],
- });
+ expect(compiled.stylesheet().s?.[0]?.[1][0]?.d).toStrictEqual([
+ [[{}, "boxShadow", expected, 1], "boxShadow", 1],
+ ]);
});
test("light-dark()", () => {
@@ -381,6 +313,31 @@ test("media query nested in rules", () => {
});
});
+test.each([
+ ["@media", "@media (min-width: 0px) { color: blue; }"],
+ ["@container", "@container (min-width: 0px) { color: blue; }"],
+ ["&:hover", "&:hover { color: blue; }"],
+])(
+ "a %s rule nested in a descendant selector applies to that selector's subject",
+ (_kind, nested) => {
+ const stylesheet = compile(
+ `.group .x { color: red; ${nested} }`,
+ ).stylesheet();
+ const rules = (name: string) =>
+ stylesheet.s?.find(([className]) => className === name)?.[1] ?? [];
+
+ expect(rules("x").map((rule) => rule.d)).toStrictEqual([
+ [{ color: "#f00" }],
+ [{ color: "#00f" }],
+ ]);
+ for (const rule of rules("x")) {
+ expect(rule.cq).toContainEqual({ n: "g:group" });
+ }
+ expect(rules("x").flatMap((rule) => rule.c ?? [])).toStrictEqual([]);
+ expect(rules("group").flatMap((rule) => rule.d ?? [])).toStrictEqual([]);
+ },
+);
+
test("container queries", () => {
const compiled = compile(`
@container (width > 400px) {
@@ -425,6 +382,48 @@ test("warnings", () => {
});
});
+test("a transform value the compiler cannot convert is ignored, with a warning", () => {
+ const compiled = compile(`
+.my-class {
+ transform: translate(10px, 1cap);
+ rotate: 1grad;
+ scale: 2;
+}
+.alone {
+ translate: calc(1em + 5px) 5px;
+}`);
+
+ 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 93db29b1..5aaaf060 100644
--- a/src/__tests__/compiler/declarations.test.tsx
+++ b/src/__tests__/compiler/declarations.test.tsx
@@ -12,12 +12,12 @@ const tests = [
["background-repeat: space round, no-repeat;", [{ d: [{ backgroundRepeat: "space round, no-repeat" }], s: [1, 1] }]],
["background-size: 10px 50%;", [{ d: [{ backgroundSize: "10px 50%" }], s: [1, 1] }]],
["background-size: cover, 20px auto;", [{ d: [{ backgroundSize: "cover, 20px auto" }], s: [1, 1] }]],
- ["caret-color: black",[{ d: [["#000", ["cursorColor"]]], s: [1, 1] }]],
+ ["caret-color: black", [{ d: [["#000", ["cursorColor"]]], s: [1, 1] }]],
["font-variation-settings: 'wght' 600, \"wdth\" 80.5;", [{ d: [{ fontVariationSettings: "'wght' 600, 'wdth' 80.5" }], s: [1, 1] }]],
["font-variation-settings: normal;", [{ d: [{ fontVariationSettings: "normal" }], 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] }]],
["transform-origin: 12.5px -4px;", [{ d: [{ transformOrigin: [12.5, -4, 0] }], s: [1, 1] }]],
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__/compiler/logical-borders.test.ts b/src/__tests__/compiler/logical-borders.test.ts
new file mode 100644
index 00000000..83c66bce
--- /dev/null
+++ b/src/__tests__/compiler/logical-borders.test.ts
@@ -0,0 +1,401 @@
+import { compile } from "react-native-css/compiler";
+
+const getRule = (css: string) => {
+ const compiled = compile(`.my-class { ${css} }`);
+ return {
+ rule: compiled.stylesheet().s?.find((rule) => rule[0] === "my-class")?.[1],
+ warnings: compiled.warnings(),
+ };
+};
+
+describe("logical border colors", () => {
+ test("border-inline-start-color", () => {
+ expect(getRule("border-inline-start-color: red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderStartColor: "#f00" }] },
+ ]);
+ });
+
+ test("border-inline-end-color", () => {
+ expect(getRule("border-inline-end-color: red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderEndColor: "#f00" }] },
+ ]);
+ });
+
+ test("border-inline-color", () => {
+ expect(getRule("border-inline-color: red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderStartColor: "#f00", borderEndColor: "#f00" }] },
+ ]);
+ });
+
+ // nativewind/nativewind#1737: colors that resolve at runtime take the
+ // unparsed path, which previously skipped the border-inline-* renames
+ test("border-inline-start-color with var()", () => {
+ expect(
+ getRule("border-inline-start-color: hsl(var(--primary));").rule,
+ ).toStrictEqual([
+ {
+ s: [1, 1],
+ d: [[[{}, "hsl", [{}, "var", "primary", 1]], "borderStartColor", 1]],
+ dv: 1,
+ },
+ ]);
+ });
+});
+
+describe("logical border widths", () => {
+ test("border-inline-start-width", () => {
+ expect(getRule("border-inline-start-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderStartWidth: 2 }] },
+ ]);
+ });
+
+ test("border-inline-end-width", () => {
+ expect(getRule("border-inline-end-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderEndWidth: 2 }] },
+ ]);
+ });
+
+ test("border-inline-width", () => {
+ expect(getRule("border-inline-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderStartWidth: 2, borderEndWidth: 2 }] },
+ ]);
+ });
+});
+
+describe("logical border shorthands", () => {
+ test("border-inline-start", () => {
+ expect(getRule("border-inline-start: 2px solid red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderStartColor: "#f00", borderStartWidth: 2 }] },
+ ]);
+ });
+
+ test("border-inline-end", () => {
+ expect(getRule("border-inline-end: 2px solid red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderEndColor: "#f00", borderEndWidth: 2 }] },
+ ]);
+ });
+
+ test("border-inline", () => {
+ expect(getRule("border-inline: 2px solid red;").rule).toStrictEqual([
+ {
+ s: [1, 1],
+ d: [
+ {
+ borderStartColor: "#f00",
+ borderEndColor: "#f00",
+ borderStartWidth: 2,
+ borderEndWidth: 2,
+ },
+ ],
+ },
+ ]);
+ });
+});
+
+describe("logical border styles", () => {
+ // React Native only has a uniform borderStyle. solid matches the native
+ // default and is dropped silently, anything else drops with a warning
+ test("border-inline-start-style: solid is dropped without warning", () => {
+ const { rule, warnings } = getRule("border-inline-start-style: solid;");
+ expect(rule).toBeUndefined();
+ expect(warnings).toStrictEqual({});
+ });
+
+ test("border-inline-start-style: dashed is dropped with a warning", () => {
+ const { rule, warnings } = getRule("border-inline-start-style: dashed;");
+ expect(rule).toBeUndefined();
+ expect(warnings).toStrictEqual({
+ values: { "border-inline-start-style": ["dashed"] },
+ });
+ });
+
+ test("border-inline shorthand with a dashed style warns", () => {
+ const { warnings } = getRule("border-inline: 2px dashed red;");
+ expect(warnings).toStrictEqual({
+ values: { "border-inline-style": ["dashed"] },
+ });
+ });
+});
+
+describe("a two-edge logical property via var() compiles to a runtime call", () => {
+ // An axis colour lands on its edge pair as two declarations, so a later edge colour replaces it in cascade order
+ test.each([
+ [
+ "border-inline-color: hsl(var(--primary));",
+ ["borderStartColor", "borderEndColor"],
+ [{}, "hsl", [{}, "var", "primary", 1]],
+ [{}, "hsl", [{}, "var", "primary", 1]],
+ ],
+ [
+ "border-inline-color: var(--c);",
+ ["borderStartColor", "borderEndColor"],
+ [{}, "var", "c", 1],
+ [{}, "var", "c", 1],
+ ],
+ [
+ "border-inline-color: var(--c, red);",
+ ["borderStartColor", "borderEndColor"],
+ [{}, "var", ["c", "red"], 1],
+ [{}, "var", ["c", "red"], 1],
+ ],
+ [
+ "border-inline-color: var(--a) var(--b);",
+ ["borderStartColor", "borderEndColor"],
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ ],
+ [
+ "border-inline-color: red var(--b);",
+ ["borderStartColor", "borderEndColor"],
+ "red",
+ [{}, "var", "b", 1],
+ ],
+ [
+ "border-block-color: var(--c);",
+ ["borderTopColor", "borderBottomColor"],
+ [{}, "var", "c", 1],
+ [{}, "var", "c", 1],
+ ],
+ [
+ "border-block-color: var(--a) var(--b);",
+ ["borderTopColor", "borderBottomColor"],
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ ],
+ ] as const)(
+ "%s lands on its edge pair",
+ (css, [startKey, endKey], start, end) => {
+ const { rule, warnings } = getRule(css);
+
+ expect(rule).toStrictEqual([
+ {
+ s: [1, 1],
+ d: [
+ // A literal edge is static, a var() edge resolves in place
+ typeof start === "string"
+ ? { [startKey]: start }
+ : [start, startKey, 1],
+ [end, endKey, 1],
+ ],
+ dv: 1,
+ },
+ ]);
+ expect(warnings).toStrictEqual({});
+ },
+ );
+
+ // A var() can substitute any number of values, so the runtime handler reads the arity once it resolves, as it does for border
+ test.each([
+ [
+ "border-inline-width: var(--w);",
+ "borderInlineWidth",
+ [{}, "var", "w", 1],
+ ],
+ [
+ "border-inline-width: var(--w, 3px);",
+ "borderInlineWidth",
+ [{}, "var", ["w", 3], 1],
+ ],
+ [
+ "border-inline-width: calc(var(--w) * 2);",
+ "borderInlineWidth",
+ [{}, "calc", [[{}, "var", "w", 1], "*", 2]],
+ ],
+ [
+ "border-inline-width: var(--a) var(--b);",
+ "borderInlineWidth",
+ [
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ ],
+ ],
+ [
+ "border-inline-width: var(--a) var(--b) var(--c);",
+ "borderInlineWidth",
+ [
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ [{}, "var", "c", 1],
+ ],
+ ],
+ [
+ "border-inline-width: 1px var(--b);",
+ "borderInlineWidth",
+ [1, [{}, "var", "b", 1]],
+ ],
+ ["border-block-width: var(--w);", "borderBlockWidth", [{}, "var", "w", 1]],
+ [
+ "border-block-width: var(--a) var(--b);",
+ "borderBlockWidth",
+ [
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ ],
+ ],
+ [
+ "border-block-width: var(--a) var(--b) var(--c);",
+ "borderBlockWidth",
+ [
+ [{}, "var", "a", 1],
+ [{}, "var", "b", 1],
+ [{}, "var", "c", 1],
+ ],
+ ],
+ ] as const)("%s", (css, resolver, args) => {
+ const { rule, warnings } = getRule(css);
+
+ expect(rule).toStrictEqual([
+ { s: [1, 1], d: [[[{}, resolver, args, 1], resolver, 1]], dv: 1 },
+ ]);
+ expect(warnings).toStrictEqual({});
+ });
+
+ test("a value that compiles to nothing declares nothing", () => {
+ const { rule, warnings } = getRule("border-inline-color: inherit;");
+
+ expect(rule).toBeUndefined();
+ expect(warnings).toStrictEqual({
+ values: { "border-inline-color": ["inherit"] },
+ });
+ });
+});
+
+/**
+ * The block axis, which React Native supports differently from the inline one.
+ *
+ * The per-EDGE block colours are real props — `borderBlockStartColor` and
+ * `borderBlockEndColor` are in `ReactNativeStyleAttributes`, in both
+ * `BaseViewConfig`s and in `ViewStyle` — and each is the highest-precedence
+ * name for its edge on both platforms, so they are emitted as-is. The block
+ * WIDTHS appear only in `BaseViewConfig.ios.js`, so emitting them paints on
+ * iOS and nowhere else, and the axis-wide `borderBlockColor` is real but
+ * ordered against `borderTopColor` oppositely by the two platforms; both map
+ * to the physical edges instead. `direction` never flips the block axis, so
+ * block-start is the top edge on every platform.
+ */
+describe("block border widths", () => {
+ test("border-block-start-width", () => {
+ expect(getRule("border-block-start-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderTopWidth: 2 }] },
+ ]);
+ });
+
+ test("border-block-end-width", () => {
+ expect(getRule("border-block-end-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderBottomWidth: 2 }] },
+ ]);
+ });
+
+ test("border-block-width", () => {
+ expect(getRule("border-block-width: 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderTopWidth: 2, borderBottomWidth: 2 }] },
+ ]);
+ });
+
+ test("border-block-width with two values", () => {
+ expect(getRule("border-block-width: 1px 2px;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderTopWidth: 1, borderBottomWidth: 2 }] },
+ ]);
+ });
+});
+
+describe("block border colors", () => {
+ test.each([
+ ["border-block-start-color", "borderBlockStartColor"],
+ ["border-block-end-color", "borderBlockEndColor"],
+ ])("%s keeps React Native's own prop", (property, key) => {
+ expect(getRule(`${property}: red;`).rule).toStrictEqual([
+ { s: [1, 1], d: [{ [key]: "#f00" }] },
+ ]);
+ });
+
+ test("border-block-color reaches the edge pair", () => {
+ expect(getRule("border-block-color: red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderTopColor: "#f00", borderBottomColor: "#f00" }] },
+ ]);
+ });
+});
+
+describe("block border styles", () => {
+ // React Native has no per-edge border style on either axis.
+ test.each([
+ "border-block-style",
+ "border-block-start-style",
+ "border-block-end-style",
+ ])("%s: solid is dropped without warning", (property) => {
+ const { rule, warnings } = getRule(`${property}: solid;`);
+
+ expect(rule).toBeUndefined();
+ expect(warnings).toStrictEqual({});
+ });
+
+ test("border-block-start-style: dashed is dropped with a warning", () => {
+ const { rule, warnings } = getRule("border-block-start-style: dashed;");
+
+ expect(rule).toBeUndefined();
+ expect(warnings).toStrictEqual({
+ values: { "border-block-start-style": ["dashed"] },
+ });
+ });
+
+ test("border-block-style: two values warn per edge", () => {
+ expect(
+ getRule("border-block-style: dashed dotted;").warnings,
+ ).toStrictEqual({
+ values: {
+ "border-block-start-style": ["dashed"],
+ "border-block-end-style": ["dotted"],
+ },
+ });
+ });
+});
+
+describe("block border shorthands", () => {
+ test("border-block", () => {
+ expect(getRule("border-block: 2px solid red;").rule).toStrictEqual([
+ {
+ s: [1, 1],
+ d: [
+ {
+ borderTopColor: "#f00",
+ borderBottomColor: "#f00",
+ borderTopWidth: 2,
+ borderBottomWidth: 2,
+ },
+ ],
+ },
+ ]);
+ });
+
+ test("border-block-start", () => {
+ expect(getRule("border-block-start: 2px solid red;").rule).toStrictEqual([
+ { s: [1, 1], d: [{ borderBlockStartColor: "#f00", borderTopWidth: 2 }] },
+ ]);
+ });
+
+ test("border-block-end", () => {
+ expect(getRule("border-block-end: 2px solid red;").rule).toStrictEqual([
+ {
+ s: [1, 1],
+ d: [{ borderBlockEndColor: "#f00", borderBottomWidth: 2 }],
+ },
+ ]);
+ });
+
+ test("a block shorthand with a dashed style warns", () => {
+ expect(getRule("border-block: 2px dashed red;").warnings).toStrictEqual({
+ values: { "border-block-style": ["dashed"] },
+ });
+ });
+});
+
+describe("block borders via var() (unparsed path)", () => {
+ test.each([
+ ["border-block-start-width", "borderTopWidth"],
+ ["border-block-end-width", "borderBottomWidth"],
+ ])("%s renames on the unparsed path too", (property, key) => {
+ expect(getRule(`${property}: var(--w);`).rule).toStrictEqual([
+ { s: [1, 1], d: [[[{}, "var", "w", 1], key, 1]], dv: 1 },
+ ]);
+ });
+});
diff --git a/src/__tests__/compiler/media-query.test.ts b/src/__tests__/compiler/media-query.test.ts
index 760ede29..76994001 100644
--- a/src/__tests__/compiler/media-query.test.ts
+++ b/src/__tests__/compiler/media-query.test.ts
@@ -1,66 +1,24 @@
import { compile } from "react-native-css/compiler";
-describe.skip("platform media queries", () => {
- test("android", () => {
- const compiled = compile(`
- @media android and (min-width: 500px) {
- .my-class { color: red; }
- }
- `);
-
- expect(compiled.stylesheet()).toStrictEqual({
- s: [
- [
- "my-class",
- [
- {
- s: [1, 1],
- d: [{ color: "#ff0000" }],
- m: [
- [
- "&",
- [
- ["=", "platform", "android"],
- [">=", "width", 500],
- ],
- ],
- ],
- },
- ],
- ],
- ],
- });
- });
-
- test("ios", () => {
- const compiled = compile(`
- @media ios and (min-width: 500px) {
- .my-class { color: red; }
- }
- `);
-
- expect(compiled.stylesheet()).toStrictEqual({
- s: [
+test.each(["android", "ios"])(
+ "platform media queries combine %s and width conditions",
+ (platform) => {
+ const result = compile(
+ `@media ${platform} and (min-width: 500px) { .my-class { color: red; } }`,
+ ).stylesheet();
+ const rule = result.s?.[0]?.[1][0];
+ expect(rule?.d).toContainEqual({ color: "#f00" });
+ expect(rule?.m).toEqual([
+ [
+ "&",
[
- "my-class",
- [
- {
- s: [1, 1],
- d: [{ color: "#ff0000" }],
- m: [
- "&",
- [
- ["=", "platform", "ios"],
- [">=", "width", 500],
- ],
- ],
- },
- ],
+ ["=", "platform", platform],
+ [">=", "width", 500],
],
],
- });
- });
-});
+ ]);
+ },
+);
test("@media (hover: hover)", () => {
const compiled = compile(`
diff --git a/src/__tests__/compiler/property.test.ts b/src/__tests__/compiler/property.test.ts
index 119c85d7..20ae04db 100644
--- a/src/__tests__/compiler/property.test.ts
+++ b/src/__tests__/compiler/property.test.ts
@@ -9,15 +9,12 @@ test("@property with length initial value", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.has("tw-translate-x")).toBe(true);
- expect(vrMap.get("tw-translate-x")).toStrictEqual([[0]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-translate-x", false, 0],
+ ]);
});
-test("@property without initial value is skipped", () => {
+test("@property without an initial value registers none", () => {
const compiled = compile(`
@property --tw-ring-color {
syntax: "*";
@@ -26,6 +23,7 @@ test("@property without initial value is skipped", () => {
`);
const result = compiled.stylesheet();
+ expect(result.vp).toStrictEqual([["tw-ring-color", false]]);
expect(result.vr).toBeUndefined();
});
@@ -38,11 +36,9 @@ test("@property with number initial value", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.get("tw-backdrop-opacity")).toStrictEqual([[1]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-backdrop-opacity", false, 1],
+ ]);
});
test("@property with color initial value", () => {
@@ -54,11 +50,9 @@ test("@property with color initial value", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.get("tw-ring-offset-color")).toStrictEqual([["#fff"]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-ring-offset-color", false, "#fff"],
+ ]);
});
test("@property with token-list initial value (shadow)", () => {
@@ -70,14 +64,12 @@ test("@property with token-list initial value (shadow)", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.get("tw-shadow")).toStrictEqual([[[0, 0, "#0000"]]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-shadow", false, [0, 0, "#0000"]],
+ ]);
});
-test("@property defaults are root variables, not universal", () => {
+test("@property defaults are neither root nor universal variables", () => {
const compiled = compile(`
@property --tw-shadow {
syntax: "*";
@@ -87,10 +79,27 @@ test("@property defaults are root variables, not universal", () => {
`);
const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
+ expect(result.vp).toStrictEqual([["tw-shadow", false, [0, 0, "#0000"]]]);
+ expect(result.vr).toBeUndefined();
expect(result.vu).toBeUndefined();
});
+test("a :root declaration and a registered default land in different slots", () => {
+ const compiled = compile(`
+@property --my-var {
+ syntax: "";
+ inherits: true;
+ initial-value: 0px;
+}
+:root { --my-var: 50px; }
+:root { --my-var: 50px; }
+`);
+
+ const result = compiled.stylesheet();
+ expect(new Map(result.vr).get("my-var")).toStrictEqual([[50]]);
+ expect(result.vp).toStrictEqual([["my-var", true, 0]]);
+});
+
test("@supports -moz-orient fallback no longer fires", () => {
const compiled = compile(`
@supports (-moz-orient: inline) {
@@ -139,7 +148,13 @@ test("@property + class override produces valid stylesheet", () => {
`);
const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
+ expect(result.vp).toStrictEqual([
+ ["tw-shadow", false, [0, 0, "#0000"]],
+ ["tw-inset-shadow", false, [0, 0, "#0000"]],
+ ["tw-ring-shadow", false, [0, 0, "#0000"]],
+ ["tw-inset-ring-shadow", false, [0, 0, "#0000"]],
+ ["tw-ring-offset-shadow", false, [0, 0, "#0000"]],
+ ]);
expect(result.s).toBeDefined();
const shadowRule = result.s?.find(([name]) => name === "shadow-md");
@@ -155,11 +170,9 @@ test("@property with percentage initial value", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.get("tw-shadow-alpha")).toStrictEqual([["100%"]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-shadow-alpha", false, "100%"],
+ ]);
});
test("multiple @property declarations with verified values", () => {
@@ -181,13 +194,11 @@ test("multiple @property declarations with verified values", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
- expect(vrMap.get("tw-translate-x")).toStrictEqual([[0]]);
- expect(vrMap.get("tw-translate-y")).toStrictEqual([[0]]);
- expect(vrMap.get("tw-rotate")).toStrictEqual([["0deg"]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-translate-x", false, 0],
+ ["tw-translate-y", false, 0],
+ ["tw-rotate", false, "0deg"],
+ ]);
});
test("@property with repeated single-child unwraps to scalar", () => {
@@ -199,13 +210,251 @@ test("@property with repeated single-child unwraps to scalar", () => {
}
`);
- const result = compiled.stylesheet();
- expect(result.vr).toBeDefined();
-
- const vrMap = new Map(result.vr);
// Single-child repeated (+ with one value) should unwrap
// to the same shape as a direct type
- expect(vrMap.get("my-offset")).toStrictEqual([[10]]);
+ expect(compiled.stylesheet().vp).toStrictEqual([["my-offset", false, 10]]);
+});
+
+test("@property inherits: false is recorded, initial value or not", () => {
+ const compiled = compile(`
+@property --tw-ring-shadow {
+ syntax: "*";
+ inherits: false;
+ initial-value: 0 0 #0000;
+}
+@property --tw-ring-color {
+ syntax: "*";
+ inherits: false;
+}
+`);
+
+ expect(compiled.stylesheet().vp).toStrictEqual([
+ ["tw-ring-shadow", false, [0, 0, "#0000"]],
+ ["tw-ring-color", false],
+ ]);
+});
+
+test("vp carries each registration's inherits", () => {
+ const declarations: [name: string, inherits: boolean][] = [
+ ["--a-off", false],
+ ["--b-on", true],
+ ["--c-off", false],
+ ["--d-on", true],
+ ];
+
+ const compiled = compile(
+ declarations
+ .map(
+ ([name, inherits]) =>
+ `@property ${name} { syntax: ""; inherits: ${inherits}; initial-value: 0px; }`,
+ )
+ .join("\n"),
+ );
+
+ expect(
+ compiled.stylesheet().vp?.map(([name, inherits]) => [name, inherits]),
+ ).toStrictEqual(
+ declarations.map(([name, inherits]) => [name.slice(2), inherits]),
+ );
+});
+
+test("a non-inheriting property is left to the runtime, however few rules declare it", () => {
+ const compiled = compile(`
+@property --pinned {
+ syntax: "";
+ inherits: false;
+ initial-value: 0px;
+}
+.parent { --pinned: 10px; }
+.child { width: var(--pinned); }
+`);
+
+ expect(compiled.stylesheet().s).toStrictEqual([
+ ["parent", [{ s: [1, 1], v: [["pinned", 10]] }]],
+ [
+ "child",
+ [{ s: [2, 1], d: [[[{}, "var", "pinned", 1], "width", 1]], dv: 1 }],
+ ],
+ ]);
+});
+
+test("a single declaration that refers to a non-inheriting property is left to the runtime", () => {
+ const compiled = compile(`
+@property --my-var {
+ syntax: "";
+ inherits: false;
+ initial-value: 0px;
+}
+.parent { --alias: var(--my-var); --my-var: 10px; }
+.child { width: var(--alias); }
+`);
+
+ expect(compiled.stylesheet().s).toStrictEqual([
+ [
+ "parent",
+ [
+ {
+ s: [1, 1],
+ v: [
+ ["alias", [{}, "var", "my-var", 1]],
+ ["my-var", 10],
+ ],
+ },
+ ],
+ ],
+ [
+ "child",
+ [{ s: [2, 1], d: [[[{}, "var", "alias", 1], "width", 1]], dv: 1 }],
+ ],
+ ]);
+});
+
+test("an inheriting property with one declaration is still inlined", () => {
+ const compiled = compile(`
+@property --folded {
+ syntax: "";
+ inherits: true;
+ initial-value: 0px;
+}
+.parent { --folded: 10px; }
+.child { width: var(--folded); }
+`);
+
+ expect(compiled.stylesheet().s).toStrictEqual([
+ ["child", [{ s: [1, 1], d: [{ width: 10 }] }]],
+ ]);
+});
+
+test("@property inherits: true is recorded as inheriting", () => {
+ const compiled = compile(`
+@property --my-brand {
+ syntax: "";
+ inherits: true;
+ initial-value: red;
+}
+`);
+
+ expect(
+ compiled.stylesheet().vp?.map(([name, inherits]) => [name, inherits]),
+ ).toStrictEqual([["my-brand", true]]);
+});
+
+test("an unregistered custom property is not recorded", () => {
+ // Declared twice, since a single declaration is inlined away and the sheet would be empty
+ const compiled = compile(`
+.my-class { --my-var: 10px; }
+.other { --my-var: 20px; }
+`);
+
+ const result = compiled.stylesheet();
+ expect(result.s).toBeDefined();
+ expect(result.vp).toBeUndefined();
+});
+
+test("@property records a name once, however many rules declare it", () => {
+ // Different syntaxes, since lightningcss collapses identical @property rules
+ const compiled = compile(`
+@property --dup {
+ syntax: "";
+ inherits: false;
+ initial-value: 0px;
+}
+@property --dup {
+ syntax: "*";
+ inherits: false;
+}
+`);
+
+ expect(compiled.stylesheet().vp).toStrictEqual([["dup", false]]);
+});
+
+test("the last @property declaration of a name decides inherits", () => {
+ const inheritsLast = compile(`
+@property --flip { syntax: "*"; inherits: false; }
+@property --flip { syntax: ""; inherits: true; initial-value: 0px; }
+`);
+ expect(inheritsLast.stylesheet().vp).toStrictEqual([["flip", true, 0]]);
+
+ const nonInheritingLast = compile(`
+@property --flip { syntax: ""; inherits: true; initial-value: 0px; }
+@property --flip { syntax: "*"; inherits: false; }
+`);
+ expect(nonInheritingLast.stylesheet().vp).toStrictEqual([["flip", false]]);
+});
+
+test.each([
+ ["