diff --git a/package-lock.json b/package-lock.json index ae8c068..46ea766 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,24 +23,26 @@ "@babel/core": "^7.24.4", "@babel/preset-env": "^7.24.4", "@babel/preset-typescript": "^7.23.3", - "@nativescript-community/solid-js": "^0.1.2", + "@nativescript-community/react": "^19.0.0", + "@nativescript-community/solid-js": "^2.0.1", "@nativescript-dom/core-types": "1.0.32", "@nativescript-dom/solidjs-types": "1.0.25", "@nativescript/angular": "^19.0.0", - "@nativescript/core": "~9.0.0", + "@nativescript/core": "~9.1.4", "@nativescript/plugin-tools": "5.5.3", "@nativescript/tailwind": "~2.1.0", "@nativescript/types": "~9.0.0", "@nativescript/webpack": "~5.0.31", "@ngtools/webpack": "^19.0.0", - "@tanstack/history": "^1.161.6", - "@tanstack/react-router": "^1.169.1", - "@tanstack/router-core": "^1.169.1", - "@tanstack/solid-router": "^1.169.1", + "@solidjs/universal": "^2.0.3", + "@solidjs/web": "^2.0.3", + "@tanstack/history": "1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-core": "1.171.39", + "@tanstack/solid-router": "2.0.0-rc.12", "@triniwiz/nativescript-image-cache-it": "^8.0.1", "@types/react": "^19.0.0", "babel-loader": "^9.1.3", - "babel-preset-solid": "^1.8.19", "dominative": "^0.1.3", "husky": "~9.0.0", "jsdom": "^29.1.1", @@ -49,8 +51,7 @@ "react-reconciler": "^0.32.0", "rxjs": "~7.8.0", "sass": "1.53.0", - "solid-js": "^1.9.11", - "solid-refresh": "^0.7.5", + "solid-js": "^2.0.3", "tailwindcss": "~3.4.3", "tsup": "^8.3.5", "typescript": "~5.8.0", @@ -6963,10 +6964,26 @@ "@tybys/wasm-util": "^0.10.1" } }, + "node_modules/@nativescript-community/react": { + "version": "19.0.0", + "resolved": "https://registry.npmjs.org/@nativescript-community/react/-/react-19.0.0.tgz", + "integrity": "sha512-YVgy9QADIfGqq3GqHdzk8UpKxglqYwL0rD1K+5hLPZY/ad3xhDmhCbP1LqTxypvjlRWSa+lb9oDKEpVejlgR1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "react-reconciler": "^0.32.0" + }, + "peerDependencies": { + "@nativescript/core": ">=8.6.2", + "dominative": "^0.1.2", + "react": ">=19.0.0", + "undom-ng": "^1.1.2" + } + }, "node_modules/@nativescript-community/solid-js": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/@nativescript-community/solid-js/-/solid-js-0.1.2.tgz", - "integrity": "sha512-lfVmI8T1rCRuDFUCyDUSQWccwiTaSyhtDFPh2swOP/lbGG+/I4NVdjrPnie6Rf1YFtyYl3ksoyU/mbGpFh7Adw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@nativescript-community/solid-js/-/solid-js-2.0.1.tgz", + "integrity": "sha512-VK5rS2Ns8uIKjBCf0pUpHtZqYIIat+mUzagxZ4LJr53kG7DhkUBYRsdrow6879TERYEKspzSCDrXGAioyUMQ9g==", "dev": true, "license": "MIT", "dependencies": { @@ -6975,9 +6992,10 @@ }, "peerDependencies": { "@babel/preset-typescript": "^7.23.3", - "babel-preset-solid": "^1.8.9", + "@solidjs/babel-plugin": "^2.0.0", + "@solidjs/universal": "^2.0.0", "dominative": "^0.1.2", - "solid-js": "^1.8.11" + "solid-js": "^2.0.0" } }, "node_modules/@nativescript-dom/core-types": { @@ -7012,9 +7030,9 @@ } }, "node_modules/@nativescript/core": { - "version": "9.0.17", - "resolved": "https://registry.npmjs.org/@nativescript/core/-/core-9.0.17.tgz", - "integrity": "sha512-NjewrlOLOxj3NAYYqpCw2VE6XhZIZVnmwopp12739cB0XkQ0penbDatZioxnkFnbaksPg8gyQXUlHF3qBfgjMw==", + "version": "9.1.4", + "resolved": "https://registry.npmjs.org/@nativescript/core/-/core-9.1.4.tgz", + "integrity": "sha512-S8HQDKi7Md9SIr7rzBHvobS3X3HC9RG5qMCLqnXsOzW1u8Kp8W4TuCVIdjoyRoj5/V8xLMv+ZpMYsJ7K5iE9Ug==", "dev": true, "funding": [ { @@ -7038,6 +7056,7 @@ "css-tree": "^3.1.0", "css-what": "^7.0.0", "emoji-regex": "^10.2.1", + "semver": "^7.0.0", "source-map": "0.7.6", "source-map-js": "^1.2.1", "tslib": "^2.0.0" @@ -10288,55 +10307,58 @@ "solid-js": ">=1.8.4" } }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "node_modules/@solidjs/signals": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@solidjs/signals/-/signals-2.0.3.tgz", + "integrity": "sha512-M6+kiJflqSvJRHRcmdsdIXpPLPkQrY817zWKKfxZ3z3ZRE5eEtddtWPrDXY4IM1Wz3zAqG+3Fx/HQIkAtpRwnA==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } }, - "node_modules/@tanstack/history": { - "version": "1.161.6", - "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.161.6.tgz", - "integrity": "sha512-NaOGLRrddszbQj9upGat6HG/4TKvXLvu+osAIgfxPYA+eIvYKv8GKDJOrY2D3/U9MRnKfMWD7bU4jeD4xmqyIg==", + "node_modules/@solidjs/universal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@solidjs/universal/-/universal-2.0.3.tgz", + "integrity": "sha512-WovRaLg0lDjPIZ+hRBg30rqx8O8fjxM89k0W2FL+EdEiKcFo24Txon4lOvV7jVI8ylX5cLi34HLHUX0rmj1Xrw==", "dev": true, "license": "MIT", "engines": { - "node": ">=20.19" + "node": ">=22.12.0" }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/tannerlinsley" + "peerDependencies": { + "solid-js": "^2.0.3" } }, - "node_modules/@tanstack/react-router": { - "version": "1.170.16", - "resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.170.16.tgz", - "integrity": "sha512-w6eq1IJklujs1tESazaK/FxH0+H2l8vm/QPuu1cD3oRW/ubgKneQpd7b64ti/8gUyEimzimJQZDmJr6YHfP5+g==", + "node_modules/@solidjs/web": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@solidjs/web/-/web-2.0.3.tgz", + "integrity": "sha512-XYl9JGOtQ8yJSZRnd6uC+5gYXsYvnIRNxhn89m+F1v6D4d4ZFdTJY2Lq/8XJ3YcjckkCrK/mNfd3kIiqqgnG7w==", "dev": true, "license": "MIT", "dependencies": { - "@tanstack/history": "1.162.0", - "@tanstack/react-store": "^0.9.3", - "@tanstack/router-core": "1.171.13", - "isbot": "^5.1.22" + "csstype": "^3.1.0", + "seroval": "^1.8.0", + "seroval-plugins": "^1.8.0" }, "engines": { - "node": ">=20.19" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/tannerlinsley" + "node": ">=22.12.0" }, "peerDependencies": { - "react": ">=18.0.0 || >=19.0.0", - "react-dom": ">=18.0.0 || >=19.0.0" + "solid-js": "^2.0.3" } }, - "node_modules/@tanstack/react-router/node_modules/@tanstack/history": { - "version": "1.162.0", - "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.0.tgz", - "integrity": "sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA==", + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tanstack/history": { + "version": "1.162.5", + "resolved": "https://registry.npmjs.org/@tanstack/history/-/history-1.162.5.tgz", + "integrity": "sha512-w1+YvwmTkwt5n8yUqEH3IWZ9DsmorCZW/EQ3KYHnqEgIkOZpH54NvW6/Epq3Dzb8H0ifIeYX8PExvrNLIH5FIA==", "dev": true, "license": "MIT", "engines": { @@ -10347,17 +10369,17 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, - "node_modules/@tanstack/react-router/node_modules/@tanstack/router-core": { - "version": "1.171.13", - "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.13.tgz", - "integrity": "sha512-+NOwEj1kO/6IGmpHRIZHasYxYWpyBQGNIZAST9aNrk9Q3YlU9SgqVnl1pbLa9qAKfeNdXQIRve0RQb/0kyDeDA==", + "node_modules/@tanstack/react-router": { + "version": "1.170.46", + "resolved": "https://registry.npmjs.org/@tanstack/react-router/-/react-router-1.170.46.tgz", + "integrity": "sha512-ez1iNIhsPjGlaDHg3BXWs67EWVIYzB2tbopEHYDESdkO7owgkGb5de52+5Kv2v1fxdkggcNzo35bdk4arTVGQw==", "dev": true, "license": "MIT", "dependencies": { - "@tanstack/history": "1.162.0", - "cookie-es": "^3.0.0", - "seroval": "^1.5.4", - "seroval-plugins": "^1.5.4" + "@tanstack/history": "1.162.5", + "@tanstack/react-store": "^0.11.2", + "@tanstack/router-core": "1.171.39", + "isbot": "^5.1.22" }, "engines": { "node": ">=20.19" @@ -10365,16 +10387,20 @@ "funding": { "type": "github", "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": ">=18.0.0 || >=19.0.0", + "react-dom": ">=18.0.0 || >=19.0.0" } }, "node_modules/@tanstack/react-store": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.9.3.tgz", - "integrity": "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==", + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/@tanstack/react-store/-/react-store-0.11.4.tgz", + "integrity": "sha512-JAQz7LcABVRbxZ6qCd4u/KqDaqBc1qmcOWz7XBTdav1Ib363HQdihCQF1A755nDhoi9VEd6UqZ5thWVKTwIIXw==", "dev": true, "license": "MIT", "dependencies": { - "@tanstack/store": "0.9.3", + "@tanstack/store": "0.11.3", "use-sync-external-store": "^1.6.0" }, "funding": { @@ -10382,24 +10408,27 @@ "url": "https://github.com/sponsors/tannerlinsley" }, "peerDependencies": { + "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } } }, "node_modules/@tanstack/router-core": { - "version": "1.169.1", - "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.169.1.tgz", - "integrity": "sha512-x+2gIGKTTE1qAn7tLieGfrB5ciOviDmmi2ox9fAWUubRV+yTU5ruGFXocoCIWF+lB+SOtnHjo2E9BLSWyYoEmA==", + "version": "1.171.39", + "resolved": "https://registry.npmjs.org/@tanstack/router-core/-/router-core-1.171.39.tgz", + "integrity": "sha512-qUhoJ0meuSUqGYQbHbcJYdASr06YtK+bulbj6vtrhKYFkLgkSsZ6tXmMyym7sFxiSJSPYgasgozrL01LyyR/6A==", "dev": true, "license": "MIT", "dependencies": { - "@tanstack/history": "1.161.6", + "@tanstack/history": "1.162.5", "cookie-es": "^3.0.0", - "seroval": "^1.5.0", - "seroval-plugins": "^1.5.0" - }, - "bin": { - "intent": "bin/intent.js" + "seroval": "^1.6.7", + "seroval-plugins": "^1.6.7" }, "engines": { "node": ">=20.19" @@ -10410,22 +10439,20 @@ } }, "node_modules/@tanstack/solid-router": { - "version": "1.169.1", - "resolved": "https://registry.npmjs.org/@tanstack/solid-router/-/solid-router-1.169.1.tgz", - "integrity": "sha512-Ij0kD/nh8h7JupF6obPZvmYFLPF74tlPDuwIGdWWS3vJWYx8SXuDrI11rMTJPmftnkgYDfhrwvhYQzz4K3/+cQ==", + "version": "2.0.0-rc.12", + "resolved": "https://registry.npmjs.org/@tanstack/solid-router/-/solid-router-2.0.0-rc.12.tgz", + "integrity": "sha512-AShRCk1Nv61j6+Pxx9DtyJbqq5dL9NzNwOQ6Jf3Q/cbMdqh636sroAO2rHgMqWKEad7fc3Cw8KEODlRlgdHfRA==", "dev": true, "license": "MIT", "dependencies": { "@solid-devtools/logger": "^0.9.4", "@solid-primitives/refs": "^1.0.8", "@solidjs/meta": "^0.29.4", - "@tanstack/history": "1.161.6", - "@tanstack/router-core": "1.169.1", + "@solidjs/web": "^2.0.1", + "@tanstack/history": "1.162.5", + "@tanstack/router-core": "1.171.39", "isbot": "^5.1.22" }, - "bin": { - "intent": "bin/intent.js" - }, "engines": { "node": ">=20.19" }, @@ -10434,13 +10461,14 @@ "url": "https://github.com/sponsors/tannerlinsley" }, "peerDependencies": { - "solid-js": "^1.9.10" + "@solidjs/web": ">=2.0.1 <3.0.0", + "solid-js": ">=2.0.1 <3.0.0" } }, "node_modules/@tanstack/store": { - "version": "0.9.3", - "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.9.3.tgz", - "integrity": "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==", + "version": "0.11.3", + "resolved": "https://registry.npmjs.org/@tanstack/store/-/store-0.11.3.tgz", + "integrity": "sha512-/Mt3h2Qe67HmRMc5SJ+8jM2Fp7O4fBbwOlS0ujUvx34KgAvkvdLSHrJatv0PJG5fbvlDsACTawMMY4ptCpVI8w==", "dev": true, "license": "MIT", "funding": { @@ -12392,69 +12420,6 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, - "node_modules/babel-plugin-jsx-dom-expressions": { - "version": "0.40.5", - "resolved": "https://registry.npmjs.org/babel-plugin-jsx-dom-expressions/-/babel-plugin-jsx-dom-expressions-0.40.5.tgz", - "integrity": "sha512-8TFKemVLDYezqqv4mWz+PhRrkryTzivTGu0twyLrOkVZ0P63COx2Y04eVsUjFlwSOXui1z3P3Pn209dokWnirg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "7.18.6", - "@babel/plugin-syntax-jsx": "^7.18.6", - "@babel/types": "^7.20.7", - "html-entities": "2.3.3", - "parse5": "^7.1.2" - }, - "peerDependencies": { - "@babel/core": "^7.20.12" - } - }, - "node_modules/babel-plugin-jsx-dom-expressions/node_modules/@babel/helper-module-imports": { - "version": "7.18.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", - "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.18.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/babel-plugin-jsx-dom-expressions/node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/babel-plugin-jsx-dom-expressions/node_modules/html-entities": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.3.3.tgz", - "integrity": "sha512-DV5Ln36z34NNTDgnz0EWGBLZENelNAtkiFA4kyNOG2tDI6Mz1uSWiq1wAKdyjnJwyDiDO7Fa2SO1CTxPXL8VxA==", - "dev": true, - "license": "MIT" - }, - "node_modules/babel-plugin-jsx-dom-expressions/node_modules/parse5": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", - "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "entities": "^6.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, "node_modules/babel-plugin-macros": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz", @@ -12577,25 +12542,6 @@ "@babel/core": "^7.0.0" } }, - "node_modules/babel-preset-solid": { - "version": "1.9.10", - "resolved": "https://registry.npmjs.org/babel-preset-solid/-/babel-preset-solid-1.9.10.tgz", - "integrity": "sha512-HCelrgua/Y+kqO8RyL04JBWS/cVdrtUv/h45GntgQY+cJl4eBcKkCDV3TdMjtKx1nXwRaR9QXslM/Npm1dxdZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "babel-plugin-jsx-dom-expressions": "^0.40.3" - }, - "peerDependencies": { - "@babel/core": "^7.0.0", - "solid-js": "^1.9.10" - }, - "peerDependenciesMeta": { - "solid-js": { - "optional": true - } - } - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -25778,26 +25724,26 @@ } }, "node_modules/seroval": { - "version": "1.5.4", - "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.5.4.tgz", - "integrity": "sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.8.2.tgz", + "integrity": "sha512-zmMxi/9MdLK1MKazLmIP6Rk39RuK0Xydd+QHeOYntS37olJeTjB3+nwVj4ce/ZWiZJeRhcO5htfxt0mUzQBscQ==", "dev": true, "license": "MIT", "engines": { - "node": ">=10" + "node": ">=20" } }, "node_modules/seroval-plugins": { - "version": "1.5.4", - "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.5.4.tgz", - "integrity": "sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/seroval-plugins/-/seroval-plugins-1.8.0.tgz", + "integrity": "sha512-96vBb12rDvPPwdKUgWw1op3fGq8AVBFOr0IllbnM72yR5J9WWXF18cQ4g1XfDO7HCyh2dt70P3XdtyRayP8FWg==", "dev": true, "license": "MIT", "engines": { - "node": ">=10" + "node": ">=20" }, "peerDependencies": { - "seroval": "^1.0" + "seroval": "^1.8.0" } }, "node_modules/serve-index": { @@ -26113,46 +26059,18 @@ } }, "node_modules/solid-js": { - "version": "1.9.11", - "resolved": "https://registry.npmjs.org/solid-js/-/solid-js-1.9.11.tgz", - "integrity": "sha512-WEJtcc5mkh/BnHA6Yrg4whlF8g6QwpmXXRg4P2ztPmcKeHHlH4+djYecBLhSpecZY2RRECXYUwIc/C2r3yzQ4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "csstype": "^3.1.0", - "seroval": "~1.5.0", - "seroval-plugins": "~1.5.0" - } - }, - "node_modules/solid-refresh": { - "version": "0.7.8", - "resolved": "https://registry.npmjs.org/solid-refresh/-/solid-refresh-0.7.8.tgz", - "integrity": "sha512-iG442T3HXJp5jEebCy8okETrWnmX7CnxNOKrJQVeufh6WXSn+xtLXaptUXXMHTWcRqTJOJwQ8UwzxrRtVFSIzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/generator": "^7.29.1", - "@babel/types": "^7.29.0" - }, - "peerDependencies": { - "solid-js": "^1.3" - } - }, - "node_modules/solid-refresh/node_modules/@babel/generator": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", - "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/solid-js/-/solid-js-2.0.3.tgz", + "integrity": "sha512-XOHstv+GAJjfcSGZU9xfX5q6Mbqmv72IcdWh2JuMx3KvBbfpQPdy/Yl00A1ouk7A0etjqhNe799CPdr6i7koWg==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" + "@solidjs/signals": "^2.0.3", + "seroval": "^1.8.0", + "seroval-plugins": "^1.8.0" }, "engines": { - "node": ">=6.9.0" + "node": ">=22.12.0" } }, "node_modules/sorted-array-functions": { @@ -28814,9 +28732,9 @@ "license": "MIT" }, "node_modules/use-sync-external-store": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", - "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.7.0.tgz", + "integrity": "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==", "dev": true, "license": "MIT", "peerDependencies": { diff --git a/package.json b/package.json index 62caef1..250a0b7 100644 --- a/package.json +++ b/package.json @@ -34,34 +34,35 @@ "@babel/core": "^7.24.4", "@babel/preset-env": "^7.24.4", "@babel/preset-typescript": "^7.23.3", - "@nativescript-community/solid-js": "^0.1.2", + "@nativescript-community/react": "^19.0.0", + "@nativescript-community/solid-js": "^2.0.1", "@nativescript-dom/core-types": "1.0.32", "@nativescript-dom/solidjs-types": "1.0.25", "@nativescript/angular": "^19.0.0", - "@nativescript/core": "~9.0.0", + "@nativescript/core": "~9.1.4", "@nativescript/plugin-tools": "5.5.3", "@nativescript/tailwind": "~2.1.0", "@nativescript/types": "~9.0.0", "@nativescript/webpack": "~5.0.31", "@ngtools/webpack": "^19.0.0", - "@tanstack/history": "^1.161.6", - "@tanstack/router-core": "^1.169.1", - "@tanstack/solid-router": "^1.169.1", - "@tanstack/react-router": "^1.169.1", + "@solidjs/universal": "^2.0.3", + "@solidjs/web": "^2.0.3", + "@tanstack/history": "1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-core": "1.171.39", + "@tanstack/solid-router": "2.0.0-rc.12", "@triniwiz/nativescript-image-cache-it": "^8.0.1", "@types/react": "^19.0.0", - "react": "^19.0.0", - "react-reconciler": "^0.32.0", "babel-loader": "^9.1.3", - "babel-preset-solid": "^1.8.19", "dominative": "^0.1.3", "husky": "~9.0.0", "jsdom": "^29.1.1", "ng-packagr": "^19.0.0", + "react": "^19.0.0", + "react-reconciler": "^0.32.0", "rxjs": "~7.8.0", "sass": "1.53.0", - "solid-js": "^1.9.11", - "solid-refresh": "^0.7.5", + "solid-js": "^2.0.3", "tailwindcss": "~3.4.3", "tsup": "^8.3.5", "typescript": "~5.8.0", diff --git a/packages/tanstack-router/CHANGELOG.md b/packages/tanstack-router/CHANGELOG.md index 7c7058d..2fcf6d1 100644 --- a/packages/tanstack-router/CHANGELOG.md +++ b/packages/tanstack-router/CHANGELOG.md @@ -1,3 +1,42 @@ +## 0.2.1 (2026-11-23) + +The 0.2.0 tarball on npm was built before the following changes landed; 0.2.1 publishes them. + +### ⚠️ Breaking Changes + +- `nativescript.vite.mjs` no longer registers the TanStack router plugin, and `@tanstack/router-plugin` is no longer a dependency. Apps using file-based routes add `tanstackRouter({ target: 'solid', autoCodeSplitting: false })` from `@tanstack/router-plugin/vite` to their own Vite config. With `@nativescript/vite` applying dependency plugins, shipping it here would register the plugin twice. + +### 🩹 Fixes + +- Modal routers no longer replace the app router registered on `globalThis.__ns_router`, so HMR keeps patching the live router after a modal opens. +- `scrollTo` is stubbed as a no-op global: router-core resets window scroll after every render and threw `ReferenceError: scrollTo is not defined` on each navigation. +- The provider's navigation signal is seeded without a top-level reactive read (no `STRICT_READ_UNTRACKED` dev warnings). + +## 0.2.0 (2026-11-23) + +### ⚠️ Breaking Changes + +- The Solid flavor now targets Solid 2 only: `solid-js` 2.x, `@solidjs/web` 2.x, `@nativescript-community/solid-js` 2.x and `@tanstack/solid-router` 2.x (`>=2.0.0-rc.12`). Solid 1 is no longer supported. +- `NativeScriptRouterProviderProps.actionBar` and `Link`'s `children` are typed with Solid 2's `Element` instead of `JSX.Element`. +- `solid-js-jsx-runtime-shim.js` is no longer shipped; the Solid sources are compiled without JSX. +- `nativescript.vite.mjs` no longer registers the TanStack router plugin, and `@tanstack/router-plugin` is no longer a dependency. Apps using file-based routes add `tanstackRouter({ target: 'solid', autoCodeSplitting: false })` from `@tanstack/router-plugin/vite` to their own Vite config. + +### πŸš€ Features + +- `solid-web-shim.js` now stands in for `@solidjs/web` (aliased by `nativescript.vite.mjs` and `nativescript.webpack.js`), binding the router's renderer helpers (`insert`, `spread`, `effect`, `memo`, `Dynamic`, ...) to the universal renderer of `@nativescript-community/solid-js`. +- React flavor updated to `@tanstack/react-router` 1.170 / `@tanstack/router-core` 1.171. + +### 🩹 Fixes + +- Pages render under `Errored` and keep their views through the native pop animation while their reactivity is torn down. +- Initial and history-driven loads run outside Solid owners, and Frame navigation runs after (not inside) the navigation effect, as Solid 2 requires. +- Modal routers no longer replace the app router registered on `globalThis.__ns_router`, so HMR keeps patching the live router after a modal opens. +- `scrollTo` is stubbed as a no-op global: router-core resets window scroll after every render and threw `ReferenceError: scrollTo is not defined` on each navigation. + +### πŸ”§ Chores + +- Drop solid-refresh proxy unwrapping from the HMR remount path; `@nativescript/vite` patches route components directly. + ## 0.1.2 (2026-05-03) ### πŸ§ͺ Tests diff --git a/packages/tanstack-router/README.md b/packages/tanstack-router/README.md index f817b8e..1207d65 100644 --- a/packages/tanstack-router/README.md +++ b/packages/tanstack-router/README.md @@ -15,14 +15,36 @@ The package is structured to support any framework (`react`, `vue`, `svelte`, `a ## Install ```bash -npm install @nativescript/tanstack-router @tanstack/solid-router @tanstack/history +npm install @nativescript/tanstack-router @tanstack/solid-router@^2.0.0-rc.12 @tanstack/history ``` -Peer dependencies expected in the host app: +The Solid flavor targets Solid 2. Peer dependencies expected in the host app: - `@nativescript/core` -- `@nativescript-community/solid-js` -- `solid-js` +- `@nativescript-community/solid-js` (2.x) +- `solid-js` and `@solidjs/web` (2.x) + +`@tanstack/solid-router` takes its renderer helpers from `@solidjs/web`. The package's +`nativescript.vite.mjs` (picked up automatically by `@nativescript/vite`) and +`nativescript.webpack.js` alias `@solidjs/web` to a NativeScript stand-in backed by +`@nativescript-community/solid-js`, so router internals and app JSX share one renderer. + +The router's built-in DOM fallbacks (default error / not-found components) cannot render +in NativeScript; supply NativeScript components through `defaultErrorComponent` / +`defaultNotFoundComponent` (or per-route `errorComponent` / `notFoundComponent`) when +you render nested routes through ``. + +## File-Based Routes + +Register the TanStack router plugin in the app's own Vite config, before the Solid plugin. It reads +`tsr.config.json` and regenerates the route tree: + +```ts +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +// inside defineConfig(...).plugins +tanstackRouter({ target: 'solid', autoCodeSplitting: false }), +``` ## Import Paths diff --git a/packages/tanstack-router/nativescript.vite.mjs b/packages/tanstack-router/nativescript.vite.mjs index e411c40..1fdb7f0 100644 --- a/packages/tanstack-router/nativescript.vite.mjs +++ b/packages/tanstack-router/nativescript.vite.mjs @@ -1,109 +1,13 @@ -import { createRequire } from 'node:module'; -import { dirname, join } from 'node:path'; -import { existsSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { tanstackRouter } from '@tanstack/router-plugin/vite'; -const require = createRequire(import.meta.url); -const projectRoot = process.cwd(); - -let solidJsRuntimePath; -let solidJsHPath; const solidWebShimPath = fileURLToPath(new URL('./solid-web-shim.js', import.meta.url)); -const jsxRuntimeShimPath = fileURLToPath(new URL('./solid-js-jsx-runtime-shim.js', import.meta.url)); -const tsrConfigPath = join(projectRoot, 'tsr.config.json'); -const defaultRoutesDirectory = join(projectRoot, 'src', 'routes'); - -function hasFileBasedRoutingConfig() { - return existsSync(tsrConfigPath) || existsSync(defaultRoutesDirectory); -} - -function forcePreEnforce(plugin) { - if (!plugin || typeof plugin !== 'object') { - return plugin; - } - - if (Array.isArray(plugin)) { - return plugin.map(forcePreEnforce); - } - - return { - ...plugin, - enforce: plugin.enforce ?? 'pre', - }; -} - -function getRouterPlugins() { - if (!hasFileBasedRoutingConfig()) { - return []; - } - - const plugin = tanstackRouter({ - // with other frameworks, we can embed different configs - target: 'solid', - autoCodeSplitting: false, - enableRouteGeneration: true, - }); - - const normalized = forcePreEnforce(plugin); - return Array.isArray(normalized) ? normalized : [normalized]; -} - -try { - const solidJsPackagePath = require.resolve('solid-js/package.json'); - const solidJsRoot = dirname(solidJsPackagePath); - - const candidateRuntimePath = join(solidJsRoot, 'h', 'jsx-runtime', 'dist', 'jsx.js'); - const candidateHPath = join(solidJsRoot, 'h', 'dist', 'h.js'); - - if (existsSync(candidateRuntimePath)) { - solidJsRuntimePath = candidateRuntimePath; - } - - if (existsSync(candidateHPath)) { - solidJsHPath = candidateHPath; - } - - if (!solidJsRuntimePath || !solidJsHPath) { - console.warn( - '[nativescript/tanstack-router] Could not resolve one or more SolidJS runtime alias paths for Vite.', - { - runtimeFound: !!solidJsRuntimePath, - hFound: !!solidJsHPath, - solidJsRoot, - }, - ); - } -} catch (error) { - console.warn( - '[nativescript/tanstack-router] Failed to resolve SolidJS package location for Vite aliases.', - error instanceof Error ? error.message : error, - ); -} export default () => ({ - plugins: [...getRouterPlugins()], resolve: { - alias: { - // Keep Vite behavior aligned with nativescript.webpack.js integration. - 'solid-js/web': solidWebShimPath, - // NOTE: do NOT alias `solid-js/jsx-runtime` / `solid-js/jsx-dev-runtime` to a - // shim file INSIDE this package. @nativescript/vite (solid flavor) already provides - // its own jsx-runtime shim and serves it over HTTP. When this alias pointed at - // `./solid-js-jsx-runtime-shim.js` (a subpath of this vendored runtime plugin), the - // @nativescript/vite device rewriter collapsed that subpath to the vendor-package - // ROOT binding β€” `jsx = __nsPick("@nativescript/tanstack-router", "jsx")` β€” and the - // root has no `jsx` export, so `jsx` was `undefined`. Every `jsx(...)` call in the - // bundled router JSX (e.g. renderPage's ``) - // then threw "jsx is not a function", the route Page never rendered, the Frame stayed - // empty, and the app showed a blank screen under HMR. Letting @nativescript/vite's - // HTTP-served shim resolve these keeps `jsx` a real function. (The webpack path still - // aliases them via nativescript.webpack.js, which has its own shim handling.) - ...(solidJsHPath - ? { - 'solid-js/h': solidJsHPath, - } - : {}), - }, + alias: [ + // Anchored: `@solidjs/web/*` subpaths (server-functions, storage) are + // renderer-independent and must keep resolving to the real package. + { find: /^@solidjs\/web$/, replacement: solidWebShimPath }, + ], }, }); diff --git a/packages/tanstack-router/nativescript.webpack.js b/packages/tanstack-router/nativescript.webpack.js index f452566..0fb959b 100644 --- a/packages/tanstack-router/nativescript.webpack.js +++ b/packages/tanstack-router/nativescript.webpack.js @@ -1,5 +1,4 @@ const path = require('path'); -const Webpack = require('webpack'); /** * @param {typeof import('@nativescript/webpack')} webpack @@ -7,24 +6,10 @@ const Webpack = require('webpack'); module.exports = (webpack) => { webpack.mergeWebpack((config) => { const shimPath = path.resolve(__dirname, 'solid-web-shim.js'); - const jsxRuntimeShimPath = path.resolve(__dirname, 'solid-js-jsx-runtime-shim.js'); - if (!config.resolve) { - config.resolve = {}; - } - - if (!config.resolve.alias) { - config.resolve.alias = {}; - } - - config.resolve.alias['solid-js/web$'] = shimPath; - config.resolve.alias['solid-js/web'] = shimPath; - config.resolve.alias['solid-js/jsx-runtime$'] = jsxRuntimeShimPath; - config.resolve.alias['solid-js/jsx-dev-runtime$'] = jsxRuntimeShimPath; - - config.plugins = config.plugins || []; - config.plugins.push(new Webpack.NormalModuleReplacementPlugin(/^solid-js\/web$/, shimPath)); - config.plugins.push(new Webpack.NormalModuleReplacementPlugin(/^solid-js\/jsx-runtime$/, jsxRuntimeShimPath)); - config.plugins.push(new Webpack.NormalModuleReplacementPlugin(/^solid-js\/jsx-dev-runtime$/, jsxRuntimeShimPath)); + config.resolve = config.resolve || {}; + config.resolve.alias = config.resolve.alias || {}; + // `$` keeps the match exact so `@solidjs/web/*` subpaths resolve normally. + config.resolve.alias['@solidjs/web$'] = shimPath; }); }; diff --git a/packages/tanstack-router/package.json b/packages/tanstack-router/package.json index 1a1feea..10d336a 100644 --- a/packages/tanstack-router/package.json +++ b/packages/tanstack-router/package.json @@ -1,19 +1,19 @@ { "name": "@nativescript/tanstack-router", - "version": "0.1.7", + "version": "0.2.1", "description": "TanStack Router for NativeScript", "main": "index.cjs", "types": "index.d.ts", "files": [ "index.cjs", "index.mjs", - "index.d.ts", + "*.d.ts", + "*.d.mts", "solid", "react", "nativescript.vite.mjs", "nativescript.webpack.js", "solid-web-shim.js", - "solid-js-jsx-runtime-shim.js", "README.md", "LICENSE" ], @@ -74,16 +74,14 @@ "license": "Apache-2.0", "homepage": "https://github.com/NativeScript/tanstack", "readmeFilename": "README.md", - "dependencies": { - "@tanstack/router-plugin": "~1.167.0" - }, "peerDependencies": { - "@nativescript-community/solid-js": ">=0.1.0", + "@nativescript-community/solid-js": ">=2.0.0", "@nativescript-community/react": ">=0.1.0", "@nativescript/core": ">=9.0.0", - "solid-js": ">=1.9.0", + "solid-js": ">=2.0.0 <3.0.0", + "@solidjs/web": ">=2.0.0 <3.0.0", "react": ">=19.0.0", - "@tanstack/solid-router": ">=1.169.0", + "@tanstack/solid-router": ">=2.0.0-rc.12 <3.0.0", "@tanstack/react-router": ">=1.169.0", "@tanstack/history": ">=1.161.0" }, @@ -97,6 +95,9 @@ "solid-js": { "optional": true }, + "@solidjs/web": { + "optional": true + }, "react": { "optional": true }, @@ -112,9 +113,9 @@ "typescript": "~5.9.0", "vitest": "^4.1.5", "@types/react": "^19.0.0", - "@tanstack/solid-router": "~1.169.0", - "@tanstack/react-router": "~1.169.0", - "@tanstack/history": "~1.161.0", - "@tanstack/router-core": "~1.169.0" + "@tanstack/solid-router": "2.0.0-rc.12", + "@tanstack/react-router": "~1.170.46", + "@tanstack/history": "1.162.5", + "@tanstack/router-core": "1.171.39" } } diff --git a/packages/tanstack-router/project.json b/packages/tanstack-router/project.json index ab78b80..7f118ac 100644 --- a/packages/tanstack-router/project.json +++ b/packages/tanstack-router/project.json @@ -7,18 +7,7 @@ "build": { "executor": "nx:run-commands", "options": { - "commands": [ - "rm -rf dist/packages/tanstack-router", - "tsc -p packages/tanstack-router/tsconfig.json --noEmit", - "tsup --config packages/tanstack-router/tsup.config.ts", - "cp packages/tanstack-router/package.json dist/packages/tanstack-router/package.json", - "cp packages/tanstack-router/README.md dist/packages/tanstack-router/README.md", - "cp packages/tanstack-router/nativescript.vite.mjs dist/packages/tanstack-router/nativescript.vite.mjs", - "cp packages/tanstack-router/nativescript.webpack.js dist/packages/tanstack-router/nativescript.webpack.js", - "cp packages/tanstack-router/solid-web-shim.js dist/packages/tanstack-router/solid-web-shim.js", - "cp packages/tanstack-router/solid-js-jsx-runtime-shim.js dist/packages/tanstack-router/solid-js-jsx-runtime-shim.js", - "cp LICENSE dist/packages/tanstack-router/LICENSE" - ], + "commands": ["rm -rf dist/packages/tanstack-router", "tsc -p packages/tanstack-router/tsconfig.json --noEmit", "tsup --config packages/tanstack-router/tsup.config.ts", "cp packages/tanstack-router/package.json dist/packages/tanstack-router/package.json", "cp packages/tanstack-router/README.md dist/packages/tanstack-router/README.md", "cp packages/tanstack-router/nativescript.vite.mjs dist/packages/tanstack-router/nativescript.vite.mjs", "cp packages/tanstack-router/nativescript.webpack.js dist/packages/tanstack-router/nativescript.webpack.js", "cp packages/tanstack-router/solid-web-shim.js dist/packages/tanstack-router/solid-web-shim.js", "cp LICENSE dist/packages/tanstack-router/LICENSE"], "parallel": false }, "outputs": ["{workspaceRoot}/dist/packages/tanstack-router"] diff --git a/packages/tanstack-router/solid-js-jsx-runtime-shim.js b/packages/tanstack-router/solid-js-jsx-runtime-shim.js deleted file mode 100644 index ccdf3be..0000000 --- a/packages/tanstack-router/solid-js-jsx-runtime-shim.js +++ /dev/null @@ -1,20 +0,0 @@ -// NativeScript-safe JSX runtime shim for packages that import solid-js/jsx-runtime. -// Keep this shim free of deep solid-js subpath imports because NativeScript -// webpack aliasing can redirect `solid-js` and break `solid-js/*` resolution. -import { createComponent } from 'solid-js'; - -export function Fragment(props) { - return props?.children ?? null; -} - -export function jsx(type, props) { - if (typeof type === 'function') { - return createComponent(type, props || {}); - } - - // For rare intrinsic tags in this package, return a minimal vnode-like shape. - return { type, props: props || {} }; -} - -export const jsxs = jsx; -export const jsxDEV = jsx; diff --git a/packages/tanstack-router/solid-web-shim.js b/packages/tanstack-router/solid-web-shim.js index fe557a0..9ac0ea7 100644 --- a/packages/tanstack-router/solid-web-shim.js +++ b/packages/tanstack-router/solid-web-shim.js @@ -1,105 +1,70 @@ -// Shim for solid-js/web in NativeScript. -// Re-exports core solid-js plus web-specific symbols used by router internals. -import { createMemo } from 'solid-js'; +// NativeScript stand-in for `@solidjs/web`, aliased by nativescript.vite.mjs and +// nativescript.webpack.js. @tanstack/solid-router's compiled output takes its +// renderer helpers from `@solidjs/web`; binding them to the universal renderer of +// @nativescript-community/solid-js keeps router internals and app JSX on one +// renderer. Everything here must import `solid-js` (never `@solidjs/web`) so the +// alias cannot loop back onto this file. +import { createComponent, omit } from 'solid-js'; +import { dynamicCore } from 'solid-js/internal'; +import { createElement, spread } from '@nativescript-community/solid-js'; -export * from 'solid-js'; +// Same surface @solidjs/web re-exports from core. +export { Errored, For, Hydration, Loading, Match, NoHydration, Repeat, Reveal, Show, Switch, createComponent, dynamicComponent, getOwner, merge as mergeProps, untrack } from 'solid-js'; +export { render, insert, spread, effect, memo, ref, applyRef } from '@nativescript-community/solid-js'; export const isServer = false; -export function Dynamic(props) { - const comp = typeof props.component === 'function' ? props.component : null; - if (comp) return comp(props); - return null; -} +// Must equal @solidjs/web's value: the router compares it against server-function +// response headers. +export const REVALIDATE_HEADER = 'X-Revalidate'; -export function delegateEvents() {} -export function clearDelegatedEvents() {} -export function spread() {} -export function assign() {} -export function setAttribute() {} -export function setProperty() {} -export function insert() {} -export function effect() {} -export function style() {} -export function classList() {} - -// IMPORTANT: must mirror solid-js/web's `memo` (which is `fn => createMemo(() => fn())`) -// rather than returning `fn` raw. The babel-emitted JSX from @tanstack/solid-router -// uses `memo(...)` wrappers around children to scope reactive subscriptions; in 1.168+ -// the router migrated to native Solid signals and those nested memo wrappers are now -// load-bearing for `getRouteMatchStore` and `nearestMatchContext` lookups in `` -// and ``. Returning `fn` raw here causes children that read those stores to -// run in the wrong owner, so `useMatch` cannot resolve the active match and throws -// "Could not find an active match" inside `createEffect`, blanking the page. -export function memo(fn) { - return createMemo(() => fn()); -} -export function template() { - return function () {}; -} -export function getNextElement() {} -export function getNextMarker() {} -export function getNextMatch() {} -export function escape(s) { - return s; +function createNativeElement(tag, props) { + const node = createElement(tag); + spread(node, props); + return node; } -export function ssrElement() { - return ''; -} -export function ssrAttribute() { - return ''; -} -export function ssrHydrationKey() { - return ''; -} -export function ssr() { - return ''; + +export function dynamic(source, options) { + return dynamicCore(source, options, createNativeElement); } -export function ssrSpread() { - return ''; + +export function Dynamic(props) { + return createComponent( + dynamic(() => props.component), + omit(props, 'component'), + ); } -export function resolveSSRNode() { - return ''; + +export function setAttribute(node, name, value) { + if (value == null) { + node.removeAttribute?.(name); + } else { + node.setAttribute(name, value); + } } -export function generateHydrationScript() { - return ''; + +// HTML templates only back the router's DOM defaults (ErrorComponent, +// DefaultGlobalNotFound, Asset, ScriptOnce, its web ). There is no HTML +// parser in NativeScript, so instantiating one fails loudly instead of handing +// `insert()` an undefined parent. +export function template(html) { + const tag = /^<([\w-]+)/.exec(html)?.[1] ?? 'unknown'; + return () => { + throw new Error(`[@nativescript/tanstack-router] The router's built-in <${tag}> DOM fallback cannot render in NativeScript. ` + "Provide NativeScript components through defaultErrorComponent / defaultNotFoundComponent (or a route's errorComponent / notFoundComponent)."); + }; } + +// Event delegation is a DOM concept; dominative dispatches events per node. +export function delegateEvents() {} + +// There is no document and no SSR hydration payload in NativeScript. +export function useHead() {} export function HydrationScript() { - return ''; -} -export function Hydration() { - return ''; -} -export function NoHydration() { - return ''; -} -export function getHydrationKey() {} -export function hydrate() {} -export function renderToString() { - return ''; -} -export function renderToStringAsync() { - return Promise.resolve(''); -} -export function renderToStream() { - return {}; -} -export function Assets() { return null; } -export function useAssets() {} -export function pipeToNodeWritable() {} -export function pipeToWritable() {} -export function addEventListener() {} -export function removeEventListener() {} -export function dynamicProperty() {} -export function setAttributeNS() {} -export const Aliases = {}; -export function getPropAlias(prop) { - return prop; +export function getHydrationWriter() { + return undefined; +} +export function takeHydrationValue() { + return undefined; } -export const Properties = new Set(); -export const ChildProperties = new Set(); -export const DelegatedEvents = new Set(); -export const SVGElements = new Set(); -export const SVGNamespace = {}; diff --git a/packages/tanstack-router/src/Link.ts b/packages/tanstack-router/src/Link.ts new file mode 100644 index 0000000..d3d6290 --- /dev/null +++ b/packages/tanstack-router/src/Link.ts @@ -0,0 +1,173 @@ +import { createMemo, onCleanup, type Element as SolidElement } from 'solid-js'; +import { createElement, effect, insert, setProp } from '@nativescript-community/solid-js'; +import type { AnyRouter, LinkOptions, RoutePaths } from '@tanstack/solid-router'; +import { useRouter, useMatchRoute } from '@tanstack/solid-router'; +import type { RegisteredRouter } from './register'; +import { resolveLinkTapAction, type LinkTapResult } from './link-action'; +import { MODAL_SEARCH_PARAM_KEY, withSingleModalPath } from './modal-state'; +import { closeModalFromRouterContext } from './modal-controller'; + +type LinkProps | string = string, TTo extends string | undefined = '.', TMaskFrom extends RoutePaths | string = TFrom, TMaskTo extends string = '.'> = Omit, 'to' | 'state'> & { + to?: LinkOptions['to']; + state?: true | object | ((prev: unknown) => unknown); + back?: boolean; + closeModal?: boolean; + modalTo?: string; + fallbackTo?: LinkOptions['to']; + onTap?: () => LinkTapResult; + children: SolidElement; + class?: string; + activeClass?: string; + inactiveClass?: string; + style?: string; +}; + +type AnyLinkProps = LinkProps; + +function resolveNextState(prev: unknown, stateInput: AnyLinkProps['state']): unknown { + if (stateInput === undefined || stateInput === true) { + return prev; + } + + const next = typeof stateInput === 'function' ? (stateInput as (previous: unknown) => unknown)(prev) : stateInput; + + if (!next || typeof next !== 'object') { + return next; + } + + if (!prev || typeof prev !== 'object') { + return next; + } + + return { + ...(prev as Record), + ...(next as Record), + }; +} + +function resolveNavigateState(stateInput: AnyLinkProps['state']): true | ((prev: any) => any) | undefined { + if (stateInput === undefined) { + return undefined; + } + + if (stateInput === true) { + return true; + } + + return (prev: any) => resolveNextState(prev, stateInput); +} + +export function Link | string = string, const TTo extends string | undefined = '.', const TMaskFrom extends RoutePaths | string = TFrom, const TMaskTo extends string = '.'>(props: LinkProps) { + const router = useRouter(); + const matchRoute = useMatchRoute(); + + const isActive = createMemo(() => { + if (!props.to) { + return false; + } + + return !!matchRoute({ + to: props.to as any, + params: props.params as any, + fuzzy: false, + })(); + }); + + const handleTap = () => { + const action = resolveLinkTapAction({ + onTapResult: props.onTap?.(), + back: props.back, + closeModal: props.closeModal, + canGoBack: router.history.canGoBack(), + fallbackTo: props.fallbackTo, + to: props.to, + }); + + if (action.type === 'none') { + return; + } + + if (action.type === 'back') { + router.history.back(); + return; + } + + if (action.type === 'close_modal') { + if (closeModalFromRouterContext(router)) { + return; + } + + router.navigate({ + to: '.', + search: (prev: unknown) => withSingleModalPath(prev, null), + replace: props.replace ?? true, + } as any); + return; + } + + if (props.modalTo) { + const modalTo = props.modalTo; + router.navigate({ + to: (props.to || '.') as TTo, + params: props.params as any, + state: resolveNavigateState(props.state), + hash: props.hash as any, + replace: props.replace, + search: (prev: unknown) => { + const base = + typeof props.search === 'function' + ? (props.search as (old: unknown) => unknown)(prev) + : ({ + ...(prev as Record), + ...(props.search as Record | undefined), + } as unknown); + + return withSingleModalPath(base, modalTo, MODAL_SEARCH_PARAM_KEY); + }, + } as any); + return; + } + + if (typeof action.to !== 'string') { + return; + } + + router.navigate({ + to: action.to, + params: props.params as any, + state: resolveNavigateState(props.state), + search: props.search as any, + hash: props.hash as any, + replace: props.replace, + }); + }; + + const currentClass = () => { + const base = props.class || ''; + const active = isActive() ? props.activeClass || '' : props.inactiveClass || ''; + return [base, active].filter(Boolean).join(' '); + }; + + const contentView = createElement('contentview') as any; + contentView.addEventListener('tap', handleTap); + + onCleanup(() => { + contentView.removeEventListener('tap', handleTap); + }); + + effect( + () => ({ class: currentClass(), style: props.style }), + (next: { class: string; style?: string }, prev?: { class: string; style?: string }) => { + setProp(contentView, 'class', next.class, prev?.class); + // The renderer's setProp treats `style` as an object to merge; inline CSS + // strings go through the attribute instead. + if (next.style !== prev?.style && (next.style !== undefined || prev?.style !== undefined)) { + contentView.setAttribute('style', next.style ?? ''); + } + }, + ); + + insert(contentView, () => props.children); + + return contentView; +} diff --git a/packages/tanstack-router/src/Link.tsx b/packages/tanstack-router/src/Link.tsx deleted file mode 100644 index 8dad5e8..0000000 --- a/packages/tanstack-router/src/Link.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import { createMemo, createRenderEffect, onCleanup, type JSX } from 'solid-js' -import { createElement, insert, setProp } from '@nativescript-community/solid-js' -import type { AnyRouter, LinkOptions, RoutePaths } from '@tanstack/solid-router' -import { useRouter, useMatchRoute } from '@tanstack/solid-router' -import type { RegisteredRouter } from './register' -import { resolveLinkTapAction, type LinkTapResult } from './link-action' -import { MODAL_SEARCH_PARAM_KEY, withSingleModalPath } from './modal-state' -import { closeModalFromRouterContext } from './modal-controller' - -type LinkProps< - TRouter extends AnyRouter = RegisteredRouter, - TFrom extends RoutePaths | string = string, - TTo extends string | undefined = '.', - TMaskFrom extends RoutePaths | string = TFrom, - TMaskTo extends string = '.', -> = Omit, 'to' | 'state'> & { - to?: LinkOptions['to'] - state?: true | object | ((prev: unknown) => unknown) - back?: boolean - closeModal?: boolean - modalTo?: string - fallbackTo?: LinkOptions['to'] - onTap?: () => LinkTapResult - children: JSX.Element - class?: string - activeClass?: string - inactiveClass?: string - style?: string -} - -type AnyLinkProps = LinkProps - -function resolveNextState( - prev: unknown, - stateInput: AnyLinkProps['state'], -): unknown { - if (stateInput === undefined || stateInput === true) { - return prev - } - - const next = - typeof stateInput === 'function' - ? (stateInput as (previous: unknown) => unknown)(prev) - : stateInput - - if (!next || typeof next !== 'object') { - return next - } - - if (!prev || typeof prev !== 'object') { - return next - } - - return { - ...(prev as Record), - ...(next as Record), - } -} - -function resolveNavigateState(stateInput: AnyLinkProps['state']): true | ((prev: any) => any) | undefined { - if (stateInput === undefined) { - return undefined - } - - if (stateInput === true) { - return true - } - - return (prev: any) => resolveNextState(prev, stateInput) -} - -export function Link< - TRouter extends AnyRouter = RegisteredRouter, - const TFrom extends RoutePaths | string = string, - const TTo extends string | undefined = '.', - const TMaskFrom extends RoutePaths | string = TFrom, - const TMaskTo extends string = '.', ->(props: LinkProps) { - const router = useRouter() - const matchRoute = useMatchRoute() - - const isActive = createMemo(() => { - if (!props.to) { - return false - } - - return !!matchRoute({ - to: props.to as any, - params: props.params as any, - fuzzy: false, - })() - }) - - const handleTap = () => { - const action = resolveLinkTapAction({ - onTapResult: props.onTap?.(), - back: props.back, - closeModal: props.closeModal, - canGoBack: router.history.canGoBack(), - fallbackTo: props.fallbackTo, - to: props.to, - }) - - if (action.type === 'none') { - return - } - - if (action.type === 'back') { - router.history.back() - return - } - - if (action.type === 'close_modal') { - if (closeModalFromRouterContext(router)) { - return - } - - router.navigate({ - to: '.', - search: (prev: unknown) => withSingleModalPath(prev, null), - replace: props.replace ?? true, - } as any) - return - } - - if (props.modalTo) { - const modalTo = props.modalTo - router.navigate({ - to: (props.to || '.') as TTo, - params: props.params as any, - state: resolveNavigateState(props.state), - hash: props.hash as any, - replace: props.replace, - search: (prev: unknown) => { - const base = - typeof props.search === 'function' - ? (props.search as (old: unknown) => unknown)(prev) - : ({ - ...(prev as Record), - ...(props.search as Record | undefined), - } as unknown) - - return withSingleModalPath(base, modalTo, MODAL_SEARCH_PARAM_KEY) - }, - } as any) - return - } - - if (typeof action.to !== 'string') { - return - } - - router.navigate({ - to: action.to, - params: props.params as any, - state: resolveNavigateState(props.state), - search: props.search as any, - hash: props.hash as any, - replace: props.replace, - }) - } - - const currentClass = () => { - const base = props.class || '' - const active = isActive() ? (props.activeClass || '') : (props.inactiveClass || '') - return [base, active].filter(Boolean).join(' ') - } - - const contentView = createElement('contentview') as any - contentView.addEventListener('tap', handleTap) - - onCleanup(() => { - contentView.removeEventListener('tap', handleTap) - }) - - createRenderEffect(() => { - setProp(contentView, 'class', currentClass()) - setProp(contentView, 'style', props.style) - }) - - insert(contentView, props.children as any) - - return contentView -} diff --git a/packages/tanstack-router/src/NativeScriptRouterProvider.ts b/packages/tanstack-router/src/NativeScriptRouterProvider.ts new file mode 100644 index 0000000..693a001 --- /dev/null +++ b/packages/tanstack-router/src/NativeScriptRouterProvider.ts @@ -0,0 +1,756 @@ +import { createEffect, createSignal, onSettled, runWithOwner, untrack } from 'solid-js'; +import type { Element as SolidElement } from 'solid-js'; +import type { AnyRouter } from '@tanstack/solid-router'; +import { Color, ShowModalOptions, Utils } from '@nativescript/core'; +import { renderPage } from './PageRenderer'; +import { setupBackHandler } from './back-handler'; +import { doesRouteIdMatchPathname, getHistoryIndex, getNativeScriptNavigationTransition, getNavigationSignalFromRouterState, getNavigationKind, shouldSkipPathNavigation } from './navigation-state'; +import { getNativeBackCallbackDecision, shouldCompleteNativeBackSyncOnVisiblePath } from './native-back-sync'; +import { createDebugLogger } from './debug-log'; +import type { NavigationGuard, NativeScriptModalOptionsResolver, NativeScriptModalPresentationOptions } from './types'; +import { describeComponentShape, normalizeRenderableComponent } from './component-shape'; +import { createDetachedNativeScriptRouter } from './router'; +import { getSingleModalPathFromSearch, withSingleModalPath } from './modal-state'; +import { subscribeSolidHmrRemount } from './solid-hmr-remount'; +import { installNativeScriptStartTransition } from './start-transition'; + +/** + * Context passed to {@link NativeScriptRouterProviderProps.actionBar} for the route + * whose Page is about to be created. + */ +export interface NativeScriptPageActionBarContext { + /** Resolved pathname for the page being created (e.g. `"/about"`). */ + path: string; + /** Matched leaf route id. */ + routeId: string; + /** The matched route object (`router.routesById[routeId]`). */ + route: any; + /** The route's `staticData` route option, or `{}` when none was declared. */ + staticData: Record; +} + +export interface NativeScriptRouterProviderProps { + router: AnyRouter; + actionBarVisibility?: 'auto' | 'never' | 'always'; + animated?: boolean; + transition?: { name?: string; duration?: number; curve?: any }; + debug?: boolean; + modalOptions?: NativeScriptModalPresentationOptions | NativeScriptModalOptionsResolver; + /** + * Optional per-page chrome β€” typically an `` β€” rendered into each route's + * native Page. Return an `` for the matched route and dominative slots it + * into `page.actionBar`, so iOS/visionOS show a native back button automatically on + * pushed pages; return `null`/`undefined` for no bar. Receives the matched route and + * its `staticData`, so titles/items can be derived per route. With this, the app no + * longer needs a persistent header above the Frame β€” each page owns its own bar. + */ + actionBar?: (ctx: NativeScriptPageActionBarContext) => SolidElement; +} + +export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProps) { + const router = props.router; + + // Mirrors RouterContextProvider. Detached from the component owner because the + // update may write router stores, which Solid forbids inside owned scopes. + runWithOwner(null, () => { + router.update({ + ...router.options, + context: { + ...router.options.context, + }, + }); + }); + + const log = createDebugLogger(props.debug); + let frameRef: any; + let prevIndex = -1; + let prevPathname = ''; + let prevModalPath: string | null = null; + let activeModalPath: string | null = null; + let activeModalPage: any; + let modalLifecycleLock = false; + let modalRequestId = 0; + let suppressedNativeBackCallbacks = 0; + let nativeBackSyncInFlight = false; + let nativeBackSyncFromPath: string | null = null; + let queuedNativeBackCount = 0; + let skipNextFrameBackNavigation = false; + // Shared guard to prevent circular updates between router and Frame + const guard: NavigationGuard = { isNavigating: false }; + + const releaseGuard = () => { + guard.isNavigating = false; + guard.lockReason = undefined; + if (guard.lockTimeoutId) { + clearTimeout(guard.lockTimeoutId); + guard.lockTimeoutId = undefined; + } + }; + + const acquireGuard = (reason: string) => { + guard.isNavigating = true; + guard.lockReason = reason; + if (guard.lockTimeoutId) { + clearTimeout(guard.lockTimeoutId); + } + + // Failsafe: never let navigation lock remain active indefinitely. + guard.lockTimeoutId = setTimeout(() => { + log('[NSRouter] force releasing stale guard:', guard.lockReason); + releaseGuard(); + }, 250); + }; + + installNativeScriptStartTransition(router); + + // Includes pathname so child-route swaps inside a layout (e.g. /virtual β†’ + // /virtual/inspector) register even when the match ids lag behind. + const readNavigationKey = () => { + const state = router.state; + return `${getNavigationSignalFromRouterState(state)}:${state.location?.pathname || ''}`; + }; + + // Seeded once, then driven only by the router subscriptions below so Frame + // sync follows router events rather than every intermediate store write. + // Router events fire from load/transition callbacks with no stable owner, so + // this internal signal opts into owned writes. + const [navigationSignal, setNavigationSignal] = createSignal(untrack(readNavigationKey), { ownedWrite: true }); + + const updateSignal = () => { + setNavigationSignal(readNavigationKey()); + }; + + const unsubLoad = router.subscribe('onLoad' as any, () => { + updateSignal(); + }); + + const unsubBeforeLoad = router.subscribe('onBeforeRouteMount' as any, () => { + updateSignal(); + }); + + const unsubResolved = router.subscribe('onResolved' as any, () => { + updateSignal(); + }); + + const closeModalFromRouterState = () => { + if (!activeModalPage) { + activeModalPath = null; + return; + } + + modalLifecycleLock = true; + const page = activeModalPage; + activeModalPage = undefined; + activeModalPath = null; + + try { + page.closeModal?.(); + } finally { + setTimeout(() => { + modalLifecycleLock = false; + }, 0); + } + }; + + const syncRouterOnNativeModalClose = () => { + if (modalLifecycleLock) { + return; + } + + const currentModalPath = getSingleModalPathFromSearch(router.state.location.search); + if (!currentModalPath) { + return; + } + + acquireGuard('native_modal_close'); + router.navigate({ + to: '.', + search: (prev: unknown) => withSingleModalPath(prev, null), + replace: true, + } as any); + setTimeout(releaseGuard, 0); + }; + + const openModalFromRouterState = async (modalPath: string) => { + const currentPage = frameRef?.currentPage; + if (!currentPage) { + log('[NSRouter] modal open skipped (no currentPage) for path:', modalPath); + return; + } + + const requestId = ++modalRequestId; + let modalPageRef: any; + const parentContext = (router as any).options?.context; + const modalContext = parentContext && typeof parentContext === 'object' ? { ...parentContext } : {}; + + (modalContext as any).__nsModalController = { + close: () => { + modalPageRef?.closeModal?.(); + }, + }; + + const modalRouter = createDetachedNativeScriptRouter({ + routeTree: router.routeTree as any, + initialPath: modalPath, + context: modalContext, + } as any); + installNativeScriptStartTransition(modalRouter); + + try { + await modalRouter.load(); + } catch (err) { + console.error('[NSRouter] Modal router load failed for path:', modalPath, err); + syncRouterOnNativeModalClose(); + return; + } + + if (requestId !== modalRequestId) { + return; + } + + const modalMatches = modalRouter.state.matches; + const leafMatch = modalMatches[modalMatches.length - 1]; + if (!leafMatch) { + console.error('[NSRouter] No modal match found for path:', modalPath); + syncRouterOnNativeModalClose(); + return; + } + + const route = (modalRouter as any).routesById[leafMatch.routeId]; + const rawComponent = route?.options?.component; + const Component = normalizeRenderableComponent(rawComponent); + + if (!Component) { + console.error('[NSRouter] Invalid modal route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); + syncRouterOnNativeModalClose(); + return; + } + + const modalPage = renderPage(modalRouter, Component, modalPath, undefined, undefined, props.debug); + modalPageRef = modalPage; + + const resolvedModalOptions = typeof props.modalOptions === 'function' ? props.modalOptions({ modalPath, routeId: leafMatch.routeId }) : props.modalOptions; + + const resolvedIOSOptions = resolvedModalOptions?.ios; + const detentNames = resolvedIOSOptions?.detents ?? ['medium', 'large']; + const selectedDetent = resolvedIOSOptions?.selectedDetent ?? 'medium'; + const showGrabber = resolvedIOSOptions?.prefersGrabberVisible ?? true; + const expandsOnScroll = resolvedIOSOptions?.prefersScrollingExpandsWhenScrolledToEdge ?? false; + const edgeAttachedCompact = resolvedIOSOptions?.prefersEdgeAttachedInCompactHeight ?? false; + const cornerRadius = resolvedIOSOptions?.preferredCornerRadius ?? 20; + const transparentOnIOS26 = resolvedIOSOptions?.transparentBackgroundOnIOS26 ?? true; + + const getiOSPresentationStyle = () => { + return resolvedIOSOptions?.presentationStyle ?? UIModalPresentationStyle.PageSheet; + }; + + const configureIOSModalSheet = () => { + if (!__IOS__) { + return; + } + + const vc = modalPage?.ios || modalPage?.viewController; + if (!vc) { + return; + } + + const detents = detentNames + .map((name) => { + if (name === 'large') { + return UISheetPresentationControllerDetent.largeDetent(); + } + + return UISheetPresentationControllerDetent.mediumDetent(); + }) + .filter(Boolean); + + vc.modalPresentationStyle = getiOSPresentationStyle(); + + const sheet = vc.sheetPresentationController || vc.parentViewController?.sheetPresentationController; + if (!sheet) { + return; + } + + if (detents.length) { + sheet.detents = Utils.ios.collections.jsArrayToNSArray(detents); + } + + sheet.selectedDetentIdentifier = selectedDetent === 'large' ? UISheetPresentationControllerDetentIdentifierLarge : UISheetPresentationControllerDetentIdentifierMedium; + sheet.prefersScrollingExpandsWhenScrolledToEdge = expandsOnScroll; + sheet.prefersEdgeAttachedInCompactHeight = edgeAttachedCompact; + sheet.prefersGrabberVisible = showGrabber; + sheet.preferredCornerRadius = cornerRadius; + + // iOS 26+ allows transparent backgrounds so system material can show through. + if (transparentOnIOS26 && Utils.SDK_VERSION >= 26) { + modalPage.backgroundColor = new Color('transparent'); + if (vc.view) { + vc.view.backgroundColor = UIColor.clearColor; + } + } + }; + + const showOptions: ShowModalOptions = { + context: modalContext, + animated: resolvedModalOptions?.animated ?? props.animated ?? true, + fullscreen: resolvedModalOptions?.fullscreen ?? __ANDROID__, + closeCallback: () => { + if (activeModalPage === modalPage) { + activeModalPage = undefined; + activeModalPath = null; + } + syncRouterOnNativeModalClose(); + }, + }; + + if (__IOS__) { + showOptions.ios = { + presentationStyle: getiOSPresentationStyle(), + }; + } + + const attemptShowModal = (hostPage: any) => { + try { + log('[NSRouter] showModal attempt:', 'path=', modalPath, 'hostLoaded=', !!hostPage?.isLoaded, 'frameLoaded=', !!hostPage?.frame?.isLoaded); + + hostPage.showModal(modalPage, showOptions as any); + activeModalPage = modalPage; + activeModalPath = modalPath; + } catch (err) { + activeModalPage = undefined; + activeModalPath = null; + console.error('[NSRouter] Failed to show modal for path:', modalPath, err); + syncRouterOnNativeModalClose(); + } + }; + + if (__ANDROID__) { + // Android modal dialogs rely on a ready host Page/Fragment manager. + // Opening before the host is loaded can no-op without visual presentation. + if (!currentPage?.isLoaded) { + log('[NSRouter] deferring Android modal until host page is loaded:', modalPath); + + const onHostLoaded = () => { + currentPage.removeEventListener?.('loaded', onHostLoaded); + + if (requestId !== modalRequestId) { + return; + } + + const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); + if (!latestModalPath || latestModalPath !== modalPath || activeModalPath) { + return; + } + + setTimeout(() => attemptShowModal(currentPage), 0); + }; + + currentPage.addEventListener?.('loaded', onHostLoaded); + } else { + setTimeout(() => attemptShowModal(currentPage), 0); + } + } else { + attemptShowModal(currentPage); + setTimeout(() => { + try { + configureIOSModalSheet(); + } catch (err) { + console.error('[NSRouter] Failed to configure iOS modal sheet:', err); + } + }, 0); + } + }; + + const runNativeBackSync = () => { + if (!router.history.canGoBack()) { + queuedNativeBackCount = 0; + return; + } + + nativeBackSyncInFlight = true; + nativeBackSyncFromPath = router.state.location.pathname; + // Native UI has already popped the page. Reflect it in router history + // without issuing a second Frame.goBack from the router effect. + skipNextFrameBackNavigation = true; + acquireGuard('native_back_callback'); + log('[NSRouter] native back pop -> router.history.back()'); + router.history.back(); + }; + + const reconcileRouterToVisiblePath = (visiblePath: string) => { + const activePath = router.state.location.pathname; + if (visiblePath === activePath) { + // Native visibility has aligned with router path, so any in-flight native + // back sync can be deterministically completed from this event. + if ( + shouldCompleteNativeBackSyncOnVisiblePath({ + inFlight: nativeBackSyncInFlight, + visiblePath, + activePath, + }) + ) { + nativeBackSyncInFlight = false; + nativeBackSyncFromPath = null; + if (guard.lockReason === 'native_back_callback') { + log('[NSRouter] native back sync completed on visible-path alignment'); + releaseGuard(); + } + setTimeout(tryDrainQueuedNativeBack, 0); + } + return; + } + + log('[NSRouter] reconciling router to visible native page:', 'visible=', visiblePath, 'active=', activePath); + + nativeBackSyncInFlight = false; + nativeBackSyncFromPath = null; + queuedNativeBackCount = 0; + skipNextFrameBackNavigation = false; + + acquireGuard('native_visible_path_reconcile'); + router.navigate({ + to: visiblePath, + replace: true, + } as any); + + const settlePromise = router.load?.(); + + if (settlePromise && typeof settlePromise.then === 'function') { + settlePromise + .then(() => { + log('[NSRouter] visible-path reconcile settled:', 'status=', router.state.status, 'path=', router.state.location.pathname); + }) + .catch((err: any) => { + console.error('[NSRouter] visible-path reconcile load rejected:', err); + }) + .finally(() => { + if (guard.lockReason === 'native_visible_path_reconcile') { + releaseGuard(); + } + setTimeout(tryDrainQueuedNativeBack, 0); + }); + return; + } + + if (guard.lockReason === 'native_visible_path_reconcile') { + releaseGuard(); + } + setTimeout(tryDrainQueuedNativeBack, 0); + }; + + const tryDrainQueuedNativeBack = () => { + if (queuedNativeBackCount <= 0) { + return; + } + + if (nativeBackSyncInFlight || guard.isNavigating) { + return; + } + + if (!router.history.canGoBack()) { + queuedNativeBackCount = 0; + return; + } + + queuedNativeBackCount -= 1; + log('[NSRouter] draining queued native back sync. remaining:', queuedNativeBackCount); + runNativeBackSync(); + }; + + const loadRouter = (reason: string) => { + // A microtask leaves whatever owner triggered the load, matching . + queueMicrotask(() => { + router.load().catch((err: any) => { + console.error(`[NSRouter] ${reason} load rejected:`, err); + }); + }); + }; + + // The rest of : reload on history changes, plus the initial load. + onSettled(() => { + const unsubHistory = router.history.subscribe(() => { + log('[NSRouter] history.subscribe fired, pathname:', router.state.location.pathname); + loadRouter('history'); + }); + + log('[NSRouter] initial load:', JSON.stringify(router.latestLocation?.pathname)); + loadRouter('initial'); + + const cleanupBack = setupBackHandler(router, () => frameRef, guard); + + // Route-file edits are hot-swapped per Page (see solid-hmr-remount.ts) so the + // navigation stack survives the edit. + const cleanupHmr = subscribeSolidHmrRemount({ + router, + getFrame: () => frameRef, + getActiveModalPage: () => activeModalPage, + getActiveModalPath: () => activeModalPath, + log, + }); + + return () => { + closeModalFromRouterState(); + unsubHistory(); + cleanupBack(); + cleanupHmr(); + unsubLoad(); + unsubBeforeLoad(); + unsubResolved(); + }; + }); + + const syncFrameToRouterState = () => { + if (!frameRef) { + log('[NSRouter] no frameRef'); + return; + } + const state = router.state; + const matches = state.matches; + log('[NSRouter] matches:', matches.length, 'status:', state.status); + if (!matches.length) return; + + // Release native-back sync lock only after router settles out of pending. + if (nativeBackSyncInFlight && (state.status !== 'pending' || (nativeBackSyncFromPath != null && state.location.pathname !== nativeBackSyncFromPath))) { + nativeBackSyncInFlight = false; + nativeBackSyncFromPath = null; + if (guard.lockReason === 'native_back_callback') { + log('[NSRouter] native back callback releasing guard'); + releaseGuard(); + } + } + + // Drain queued native-back requests one-by-one when router is stable. + if (queuedNativeBackCount > 0) { + tryDrainQueuedNativeBack(); + } + + if (nativeBackSyncInFlight || guard.isNavigating) { + return; + } + + const curIndex = getHistoryIndex(router.history.location.state as any); + const curTransition = getNativeScriptNavigationTransition(router.history.location.state); + const curPathname = state.location.pathname; + const curModalPath = getSingleModalPathFromSearch(state.location.search); + const hasPathChanged = !shouldSkipPathNavigation(curPathname, prevPathname, prevIndex); + + if (curModalPath !== prevModalPath) { + if (!curModalPath) { + closeModalFromRouterState(); + prevModalPath = curModalPath; + } else if (!activeModalPath) { + // Defer opening modal until the base path is settled on the active page. + if (hasPathChanged && prevPathname) { + log('[NSRouter] deferring modal open until pathname settles:', curModalPath); + } else { + void openModalFromRouterState(curModalPath); + prevModalPath = curModalPath; + } + } else if (activeModalPath !== curModalPath) { + closeModalFromRouterState(); + void openModalFromRouterState(curModalPath); + prevModalPath = curModalPath; + } + } + + if (guard.isNavigating) { + log('[NSRouter] guard active; syncing prev tracking only. reason:', guard.lockReason); + prevIndex = curIndex; + prevPathname = curPathname; + return; + } + + log('[NSRouter] curPathname:', curPathname, 'prevPathname:', prevPathname, 'curIndex:', curIndex, 'prevIndex:', prevIndex); + + // Skip if the pathname hasn't changed (e.g., only search params changed) + if (!hasPathChanged) { + prevIndex = curIndex; + return; + } + + const navigationKind = getNavigationKind(prevIndex, curIndex); + const isBack = navigationKind === 'back'; + const isReplace = navigationKind === 'replace'; + + if (isBack) { + if (skipNextFrameBackNavigation) { + skipNextFrameBackNavigation = false; + log('[NSRouter] skipping Frame.goBack for native-originated back sync'); + prevIndex = curIndex; + prevPathname = curPathname; + return; + } + + acquireGuard('router_state_back'); + if (frameRef.canGoBack()) { + // Router-initiated goBack causes a native navigatingFrom(back) event. + // Suppress exactly one sync callback for this controlled pop. + suppressedNativeBackCallbacks += 1; + frameRef.goBack(); + } + prevIndex = curIndex; + prevPathname = curPathname; + setTimeout(releaseGuard, 0); + return; + } + + // Forward or replace navigation + let leafMatch = matches[matches.length - 1]; + + // If the leaf match's routeId doesn't match the current pathname, the matches + // may be stale (common for child route swaps within a layout, or parameterized + // routes like /posts/$postId where the leaf shows /posts but pathname is /posts/2). + // Find the correct route by searching all routes for one that matches the pathname. + if (!doesRouteIdMatchPathname(leafMatch.routeId, curPathname)) { + const routesById = (router as any).routesById || {}; + let resolvedRouteId: string | null = null; + + // Search all routes for one whose ID pattern matches the current pathname + for (const routeId of Object.keys(routesById)) { + if (routeId === '__root__') continue; + if (doesRouteIdMatchPathname(routeId, curPathname)) { + // Prefer the most specific match (longest routeId) + if (!resolvedRouteId || routeId.length > resolvedRouteId.length) { + resolvedRouteId = routeId; + } + } + } + + if (resolvedRouteId) { + log('[NSRouter] match/path mismatch resolved:', leafMatch.routeId, '->', resolvedRouteId, 'for pathname:', curPathname); + leafMatch = { ...leafMatch, routeId: resolvedRouteId }; + // Schedule a delayed signal update so the match stores settle and + // useParams/useMatch can read correct data when the component renders. + setTimeout(() => updateSignal(), 16); + } else { + log('[NSRouter] deferring Frame navigation due to pending match/path mismatch:', 'routeId=', leafMatch.routeId, 'pathname=', curPathname, 'status=', state.status); + // Schedule retry β€” stores may settle on next tick + setTimeout(() => updateSignal(), 16); + return; + } + } + + const route = (router as any).routesById[leafMatch.routeId]; + const rawComponent = route?.options?.component; + const Component = normalizeRenderableComponent(rawComponent); + + log('[NSRouter] leafMatch:', leafMatch.routeId, 'Component:', !!Component); + + if (!Component) { + console.error('[NSRouter] Invalid route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); + prevIndex = curIndex; + prevPathname = curPathname; + return; + } + + acquireGuard('router_state_forward_or_replace'); + + // Build the per-page chrome thunk (e.g. ) for this route, if the + // consumer supplied an `actionBar` render fn. Passed into renderPage so it renders + // inside the page's own reactive scope and slots into page.actionBar. + const pageChrome = props.actionBar + ? () => + props.actionBar!({ + path: curPathname, + routeId: leafMatch.routeId, + route, + staticData: route?.options?.staticData ?? {}, + }) + : undefined; + + log('[NSRouter] navigating Frame to', curPathname); + frameRef.navigate({ + create: () => + renderPage( + router, + Component, + curPathname, + (sourcePath) => { + if (suppressedNativeBackCallbacks > 0) { + suppressedNativeBackCallbacks -= 1; + log('[NSRouter] native back callback suppressed (router-initiated goBack)'); + return; + } + + // A stale source path still indicates a real native pop event. + // This happens when multiple native pops occur while router state is + // still settling. Queue the sync instead of dropping it. + if (sourcePath !== router.state.location.pathname) { + queuedNativeBackCount += 1; + log('[NSRouter] queued native back sync (stale source path):', 'source=', sourcePath, 'active=', router.state.location.pathname, 'count=', queuedNativeBackCount); + setTimeout(tryDrainQueuedNativeBack, 0); + return; + } + + if (nativeBackSyncInFlight) { + queuedNativeBackCount += 1; + log('[NSRouter] queued native back sync while router is busy. count=', queuedNativeBackCount, 'status=', router.state.status); + setTimeout(tryDrainQueuedNativeBack, 0); + return; + } + + log('[NSRouter] native back callback. guard:', guard.isNavigating, 'path:', router.state.location.pathname); + const decision = getNativeBackCallbackDecision({ + guardActive: guard.isNavigating, + canGoBack: router.history.canGoBack(), + }); + if (decision === 'ignore_guard_active') { + queuedNativeBackCount += 1; + log('[NSRouter] queued native back sync (guard active). count=', queuedNativeBackCount); + setTimeout(tryDrainQueuedNativeBack, 0); + return; + } + + if (decision === 'ignore_cannot_go_back') { + log('[NSRouter] native back callback ignored (cannot go back)'); + queuedNativeBackCount = 0; + return; + } + + runNativeBackSync(); + }, + reconcileRouterToVisiblePath, + props.debug, + pageChrome, + ), + animated: prevIndex >= 0 ? (props.animated ?? true) : false, + transition: curTransition ?? props.transition, + backstackVisible: !isReplace, + clearHistory: false, + }); + + prevIndex = curIndex; + prevPathname = curPathname; + + // If a modal path is present on a path transition, open it after the + // new page has a chance to become current. + if (curModalPath && !activeModalPath) { + setTimeout(() => { + const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); + if (!latestModalPath || latestModalPath !== curModalPath || activeModalPath) { + return; + } + + void openModalFromRouterState(latestModalPath); + prevModalPath = latestModalPath; + }, 0); + } + + releaseGuard(); + }; + + createEffect( + () => navigationSignal(), + (signal) => { + log('[NSRouter] effect fired, navigationSignal:', signal, 'frameRef:', !!frameRef); + // Frame navigation renders a new Page root, and Solid forbids creating + // ownerless roots inside an effect callback, so the sync runs right after it. + queueMicrotask(syncFrameToRouterState); + }, + ); + + const frameEl = document.createElement('frame') as any; + frameRef = frameEl; + frameEl.setAttribute('actionBarVisibility', props.actionBarVisibility || 'never'); + return frameEl; +} diff --git a/packages/tanstack-router/src/NativeScriptRouterProvider.tsx b/packages/tanstack-router/src/NativeScriptRouterProvider.tsx deleted file mode 100644 index 911124a..0000000 --- a/packages/tanstack-router/src/NativeScriptRouterProvider.tsx +++ /dev/null @@ -1,826 +0,0 @@ -import { batch, createEffect, createMemo, createSignal, onMount, onCleanup, untrack } from 'solid-js'; -import type { JSX } from 'solid-js'; -import type { AnyRouter } from '@tanstack/solid-router'; -import { Color, ShowModalOptions, Utils } from '@nativescript/core'; -import { renderPage } from './PageRenderer'; -import { setupBackHandler } from './back-handler'; -import { doesRouteIdMatchPathname, getHistoryIndex, getNativeScriptNavigationTransition, getNavigationSignalFromRouterState, getNavigationKind, shouldSkipPathNavigation } from './navigation-state'; -import { getNativeBackCallbackDecision, shouldCompleteNativeBackSyncOnVisiblePath } from './native-back-sync'; -import { createDebugLogger } from './debug-log'; -import type { NavigationGuard, NativeScriptModalOptionsResolver, NativeScriptModalPresentationOptions } from './types'; -import { describeComponentShape, normalizeRenderableComponent } from './component-shape'; -import { createNativeScriptRouter } from './router'; -import { getSingleModalPathFromSearch, withSingleModalPath } from './modal-state'; -import { subscribeSolidHmrRemount } from './solid-hmr-remount'; - -/** - * Context passed to {@link NativeScriptRouterProviderProps.actionBar} for the route - * whose Page is about to be created. - */ -export interface NativeScriptPageActionBarContext { - /** Resolved pathname for the page being created (e.g. `"/about"`). */ - path: string; - /** Matched leaf route id. */ - routeId: string; - /** The matched route object (`router.routesById[routeId]`). */ - route: any; - /** The route's `staticData` route option, or `{}` when none was declared. */ - staticData: Record; -} - -export interface NativeScriptRouterProviderProps { - router: AnyRouter; - actionBarVisibility?: 'auto' | 'never' | 'always'; - animated?: boolean; - transition?: { name?: string; duration?: number; curve?: any }; - debug?: boolean; - modalOptions?: NativeScriptModalPresentationOptions | NativeScriptModalOptionsResolver; - /** - * Optional per-page chrome β€” typically an `` β€” rendered into each route's - * native Page. Return an `` for the matched route and dominative slots it - * into `page.actionBar`, so iOS/visionOS show a native back button automatically on - * pushed pages; return `null`/`undefined` for no bar. Receives the matched route and - * its `staticData`, so titles/items can be derived per route. With this, the app no - * longer needs a persistent header above the Frame β€” each page owns its own bar. - */ - actionBar?: (ctx: NativeScriptPageActionBarContext) => JSX.Element | null | undefined; -} - -export function NativeScriptRouterProvider(props: NativeScriptRouterProviderProps) { - const router = props.router; - - // Ensure router stores are initialized β€” mirrors RouterContextProvider behavior. - // Without this call, router.stores may be undefined when Transitioner logic - // and useRouterState try to access it. - router.update({ - ...router.options, - context: { - ...router.options.context, - }, - }); - - const log = createDebugLogger(props.debug); - let frameRef: any; - let prevIndex = -1; - let prevPathname = ''; - let prevModalPath: string | null = null; - let activeModalPath: string | null = null; - let activeModalPage: any; - let modalLifecycleLock = false; - let modalRequestId = 0; - let suppressedNativeBackCallbacks = 0; - let nativeBackSyncInFlight = false; - let nativeBackSyncFromPath: string | null = null; - let queuedNativeBackCount = 0; - let skipNextFrameBackNavigation = false; - // Shared guard to prevent circular updates between router and Frame - const guard: NavigationGuard = { isNavigating: false }; - - const releaseGuard = () => { - guard.isNavigating = false; - guard.lockReason = undefined; - if (guard.lockTimeoutId) { - clearTimeout(guard.lockTimeoutId); - guard.lockTimeoutId = undefined; - } - }; - - const acquireGuard = (reason: string) => { - guard.isNavigating = true; - guard.lockReason = reason; - if (guard.lockTimeoutId) { - clearTimeout(guard.lockTimeoutId); - } - - // Failsafe: never let navigation lock remain active indefinitely. - guard.lockTimeoutId = setTimeout(() => { - log('[NSRouter] force releasing stale guard:', guard.lockReason); - releaseGuard(); - }, 250); - }; - - // ── Simplified state tracking for NativeScript ── - // The standard solid-router renders inside . That - // component (a) calls `router.startTransition = Solid.startTransition` to - // wire concurrent rendering, (b) subscribes to history changes and calls - // `router.load()`, and (c) watches `isLoading || hasPending` and, when both - // clear, batches `status.set('idle')` + `resolvedLocation.set(location)` and - // emits the `onResolved` event. - // - // NativeScript renders Pages via Frame.navigate() instead of mounting - // in a single Solid tree, so is never on screen. - // We reproduce its responsibilities inline below: - // 1. Synchronous startTransition (no Suspense / concurrent rendering needed) - // 2. History subscription + router.load() β€” handled in onMount - // 3. Reactive effect that flips status pendingβ†’idle when the router settles - router.startTransition = (fn: () => void) => { - fn(); - }; - - // Create a Solid signal that updates whenever the router state changes. - // This bypasses the __store reactive chain which depends on Suspense context. - const [navigationSignal, setNavigationSignal] = createSignal( - getNavigationSignalFromRouterState(router.state) + ':' + (router.state.location?.pathname || ''), - ); - - // Update navigation signal from router state. Includes pathname to detect - // child route changes (e.g., /virtual β†’ /virtual/inspector) where match IDs - // may not update immediately through the __store memo chain. - const updateSignal = () => { - const state = router.state; - const pathname = state.location?.pathname || ''; - const base = getNavigationSignalFromRouterState(state); - // Append pathname to ensure child route navigations are detected - const next = `${base}:${pathname}`; - setNavigationSignal(next); - }; - - // Transitioner-equivalent: drive `status` to `idle` and update `resolvedLocation` - // whenever the router settles out of any pending state. Mirrors the - // pendingβ†’settled createRenderEffect inside @tanstack/solid-router's - // `` (which is never mounted in NS because we render Pages - // through Frame.navigate() instead of inside a single Solid tree). - // Uses Solid's accumulator-style effect so transitions never get lost between - // module load time and the first effect tick. - const isAnyPending = createMemo(() => { - const stores = (router as any).stores; - if (!stores) return false; - return Boolean(stores.isLoading?.get?.() ?? false) || Boolean(stores.hasPending?.get?.() ?? false); - }); - createEffect((prevIsAnyPending: boolean = false) => { - const cur = isAnyPending(); - if (prevIsAnyPending && !cur) { - const stores = (router as any).stores; - batch(() => { - stores.status?.set?.('idle'); - if (stores.resolvedLocation && stores.location) { - stores.resolvedLocation.set(stores.location.get()); - } - }); - // Emit onResolved so subscribers (e.g. devtools, scroll restoration) - // observe the navigation completion the same way they do under the - // standard . - try { - router.emit?.({ type: 'onResolved' } as any); - } catch { - // ignore β€” onResolved payload is purely informational for our consumers - } - updateSignal(); - } - return cur; - }); - - const unsubLoad = router.subscribe('onLoad' as any, () => { - updateSignal(); - }); - - const unsubBeforeLoad = router.subscribe('onBeforeRouteMount' as any, () => { - updateSignal(); - }); - - const closeModalFromRouterState = () => { - if (!activeModalPage) { - activeModalPath = null; - return; - } - - modalLifecycleLock = true; - const page = activeModalPage; - activeModalPage = undefined; - activeModalPath = null; - - try { - page.closeModal?.(); - } finally { - setTimeout(() => { - modalLifecycleLock = false; - }, 0); - } - }; - - const syncRouterOnNativeModalClose = () => { - if (modalLifecycleLock) { - return; - } - - const currentModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!currentModalPath) { - return; - } - - acquireGuard('native_modal_close'); - router.navigate({ - to: '.', - search: (prev: unknown) => withSingleModalPath(prev, null), - replace: true, - } as any); - setTimeout(releaseGuard, 0); - }; - - const openModalFromRouterState = async (modalPath: string) => { - const currentPage = frameRef?.currentPage; - if (!currentPage) { - log('[NSRouter] modal open skipped (no currentPage) for path:', modalPath); - return; - } - - const requestId = ++modalRequestId; - let modalPageRef: any; - const parentContext = (router as any).options?.context; - const modalContext = parentContext && typeof parentContext === 'object' ? { ...parentContext } : {}; - - (modalContext as any).__nsModalController = { - close: () => { - modalPageRef?.closeModal?.(); - }, - }; - - const modalRouter = createNativeScriptRouter({ - routeTree: router.routeTree as any, - initialPath: modalPath, - context: modalContext, - } as any); - - try { - await modalRouter.load(); - } catch (err) { - console.error('[NSRouter] Modal router load failed for path:', modalPath, err); - syncRouterOnNativeModalClose(); - return; - } - - if (requestId !== modalRequestId) { - return; - } - - const modalMatches = modalRouter.state.matches; - const leafMatch = modalMatches[modalMatches.length - 1]; - if (!leafMatch) { - console.error('[NSRouter] No modal match found for path:', modalPath); - syncRouterOnNativeModalClose(); - return; - } - - const route = (modalRouter as any).routesById[leafMatch.routeId]; - const rawComponent = route?.options?.component; - const Component = normalizeRenderableComponent(rawComponent); - - if (!Component) { - console.error('[NSRouter] Invalid modal route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); - syncRouterOnNativeModalClose(); - return; - } - - const modalPage = renderPage(modalRouter, Component, modalPath, undefined, undefined, props.debug); - modalPageRef = modalPage; - - const resolvedModalOptions = typeof props.modalOptions === 'function' ? props.modalOptions({ modalPath, routeId: leafMatch.routeId }) : props.modalOptions; - - const resolvedIOSOptions = resolvedModalOptions?.ios; - const detentNames = resolvedIOSOptions?.detents ?? ['medium', 'large']; - const selectedDetent = resolvedIOSOptions?.selectedDetent ?? 'medium'; - const showGrabber = resolvedIOSOptions?.prefersGrabberVisible ?? true; - const expandsOnScroll = resolvedIOSOptions?.prefersScrollingExpandsWhenScrolledToEdge ?? false; - const edgeAttachedCompact = resolvedIOSOptions?.prefersEdgeAttachedInCompactHeight ?? false; - const cornerRadius = resolvedIOSOptions?.preferredCornerRadius ?? 20; - const transparentOnIOS26 = resolvedIOSOptions?.transparentBackgroundOnIOS26 ?? true; - - const getiOSPresentationStyle = () => { - return resolvedIOSOptions?.presentationStyle ?? UIModalPresentationStyle.PageSheet; - }; - - const configureIOSModalSheet = () => { - if (!__IOS__) { - return; - } - - const vc = modalPage?.ios || modalPage?.viewController; - if (!vc) { - return; - } - - const detents = detentNames - .map((name) => { - if (name === 'large') { - return UISheetPresentationControllerDetent.largeDetent(); - } - - return UISheetPresentationControllerDetent.mediumDetent(); - }) - .filter(Boolean); - - vc.modalPresentationStyle = getiOSPresentationStyle(); - - const sheet = vc.sheetPresentationController || vc.parentViewController?.sheetPresentationController; - if (!sheet) { - return; - } - - if (detents.length) { - sheet.detents = Utils.ios.collections.jsArrayToNSArray(detents); - } - - sheet.selectedDetentIdentifier = selectedDetent === 'large' ? UISheetPresentationControllerDetentIdentifierLarge : UISheetPresentationControllerDetentIdentifierMedium; - sheet.prefersScrollingExpandsWhenScrolledToEdge = expandsOnScroll; - sheet.prefersEdgeAttachedInCompactHeight = edgeAttachedCompact; - sheet.prefersGrabberVisible = showGrabber; - sheet.preferredCornerRadius = cornerRadius; - - // iOS 26+ allows transparent backgrounds so system material can show through. - if (transparentOnIOS26 && Utils.SDK_VERSION >= 26) { - modalPage.backgroundColor = new Color('transparent'); - if (vc.view) { - vc.view.backgroundColor = UIColor.clearColor; - } - } - }; - - const showOptions: ShowModalOptions = { - context: modalContext, - animated: resolvedModalOptions?.animated ?? props.animated ?? true, - fullscreen: resolvedModalOptions?.fullscreen ?? __ANDROID__, - closeCallback: () => { - if (activeModalPage === modalPage) { - activeModalPage = undefined; - activeModalPath = null; - } - syncRouterOnNativeModalClose(); - }, - }; - - if (__IOS__) { - showOptions.ios = { - presentationStyle: getiOSPresentationStyle(), - }; - } - - const attemptShowModal = (hostPage: any) => { - try { - log('[NSRouter] showModal attempt:', 'path=', modalPath, 'hostLoaded=', !!hostPage?.isLoaded, 'frameLoaded=', !!hostPage?.frame?.isLoaded); - - hostPage.showModal(modalPage, showOptions as any); - activeModalPage = modalPage; - activeModalPath = modalPath; - } catch (err) { - activeModalPage = undefined; - activeModalPath = null; - console.error('[NSRouter] Failed to show modal for path:', modalPath, err); - syncRouterOnNativeModalClose(); - } - }; - - if (__ANDROID__) { - // Android modal dialogs rely on a ready host Page/Fragment manager. - // Opening before the host is loaded can no-op without visual presentation. - if (!currentPage?.isLoaded) { - log('[NSRouter] deferring Android modal until host page is loaded:', modalPath); - - const onHostLoaded = () => { - currentPage.removeEventListener?.('loaded', onHostLoaded); - - if (requestId !== modalRequestId) { - return; - } - - const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!latestModalPath || latestModalPath !== modalPath || activeModalPath) { - return; - } - - setTimeout(() => attemptShowModal(currentPage), 0); - }; - - currentPage.addEventListener?.('loaded', onHostLoaded); - } else { - setTimeout(() => attemptShowModal(currentPage), 0); - } - } else { - attemptShowModal(currentPage); - setTimeout(() => { - try { - configureIOSModalSheet(); - } catch (err) { - console.error('[NSRouter] Failed to configure iOS modal sheet:', err); - } - }, 0); - } - }; - - const runNativeBackSync = () => { - if (!router.history.canGoBack()) { - queuedNativeBackCount = 0; - return; - } - - nativeBackSyncInFlight = true; - nativeBackSyncFromPath = router.state.location.pathname; - // Native UI has already popped the page. Reflect it in router history - // without issuing a second Frame.goBack from the router effect. - skipNextFrameBackNavigation = true; - acquireGuard('native_back_callback'); - log('[NSRouter] native back pop -> router.history.back()'); - router.history.back(); - }; - - const reconcileRouterToVisiblePath = (visiblePath: string) => { - const activePath = router.state.location.pathname; - if (visiblePath === activePath) { - // Native visibility has aligned with router path, so any in-flight native - // back sync can be deterministically completed from this event. - if ( - shouldCompleteNativeBackSyncOnVisiblePath({ - inFlight: nativeBackSyncInFlight, - visiblePath, - activePath, - }) - ) { - nativeBackSyncInFlight = false; - nativeBackSyncFromPath = null; - if (guard.lockReason === 'native_back_callback') { - log('[NSRouter] native back sync completed on visible-path alignment'); - releaseGuard(); - } - setTimeout(tryDrainQueuedNativeBack, 0); - } - return; - } - - log('[NSRouter] reconciling router to visible native page:', 'visible=', visiblePath, 'active=', activePath); - - nativeBackSyncInFlight = false; - nativeBackSyncFromPath = null; - queuedNativeBackCount = 0; - skipNextFrameBackNavigation = false; - - acquireGuard('native_visible_path_reconcile'); - router.navigate({ - to: visiblePath, - replace: true, - } as any); - - const settlePromise = router.load?.(); - - if (settlePromise && typeof settlePromise.then === 'function') { - settlePromise - .then(() => { - log('[NSRouter] visible-path reconcile settled:', 'status=', router.state.status, 'path=', router.state.location.pathname); - }) - .catch((err: any) => { - console.error('[NSRouter] visible-path reconcile load rejected:', err); - }) - .finally(() => { - if (guard.lockReason === 'native_visible_path_reconcile') { - releaseGuard(); - } - setTimeout(tryDrainQueuedNativeBack, 0); - }); - return; - } - - if (guard.lockReason === 'native_visible_path_reconcile') { - releaseGuard(); - } - setTimeout(tryDrainQueuedNativeBack, 0); - }; - - const tryDrainQueuedNativeBack = () => { - if (queuedNativeBackCount <= 0) { - return; - } - - if (nativeBackSyncInFlight || guard.isNavigating) { - return; - } - - if (!router.history.canGoBack()) { - queuedNativeBackCount = 0; - return; - } - - queuedNativeBackCount -= 1; - log('[NSRouter] draining queued native back sync. remaining:', queuedNativeBackCount); - runNativeBackSync(); - }; - - // ── Mount lifecycle (mirrors Transitioner.onMount) ── - onMount(() => { - // Subscribe to history changes and trigger router.load(). The - // Transitioner-equivalent reactive effect above handles status transitions - // (pendingβ†’idle) and signal updates once isLoading + hasPending settle, so - // we no longer need to poke `router.stores.status` after each load. - const unsub = router.history.subscribe(() => { - log('[NSRouter] history.subscribe fired, pathname:', router.state.location.pathname); - const loadPromise = router.load(); - if (loadPromise && typeof loadPromise.then === 'function') { - loadPromise.catch((err: any) => { - log('[NSRouter] history load error:', err?.message || err); - }); - } - }); - - log('[NSRouter] onMount: calling router.load()'); - log('[NSRouter] latestLocation:', JSON.stringify(router.latestLocation?.pathname)); - log('[NSRouter] routeTree:', !!router.routeTree); - log('[NSRouter] routesById keys:', Object.keys((router as any).routesById || {})); - - // Set up back button handling - const cleanupBack = setupBackHandler(router, () => frameRef, guard); - - // ── Solid HMR remount subscription ── - // After solid-refresh's inline `patchRegistry` has swapped the proxy's - // underlying signal to point at each newly-evaluated component, the - // proxy's memo correctly re-evaluates, but in this universal-renderer + - // nested-context configuration the page-level renderEffect doesn't - // re-fire so the visible Page tree never updates. The NS HMR client - // emits a `__ns_solid_hmr_subscribe` completion event after the solid - // case finishes; we react by re-mounting the Solid tree of every Page - // currently held by the Frame (currentPage + backStack). Re-mounting a - // Page disposes its existing render and then runs `render()` again with - // the fresh route component pulled from `router.routesById`, so the - // user sees the edit without losing their place in the navigation - // history. - const cleanupHmr = subscribeSolidHmrRemount({ - router, - getFrame: () => frameRef, - getActiveModalPage: () => activeModalPage, - getActiveModalPath: () => activeModalPath, - log, - }); - - onCleanup(() => { - closeModalFromRouterState(); - unsub(); - cleanupBack(); - cleanupHmr(); - unsubLoad(); - unsubBeforeLoad(); - }); - }); - - // Initial load β€” trigger immediately. The Transitioner-equivalent effect - // above flips status to 'idle' and updates the signal when the load settles. - { - const tryLoad = async () => { - try { - await router.load(); - log('[NSRouter] load resolved. status:', router.state.status, 'matches:', router.state.matches.length); - } catch (err: any) { - console.error('[NSRouter] load rejected:', err); - } - }; - tryLoad(); - } - - // React to match changes and navigate the Frame - createEffect(() => { - // Read reactive dependency - const _navigationSignal = navigationSignal(); - - log('[NSRouter] effect fired, navigationSignal:', _navigationSignal, 'frameRef:', !!frameRef); - - untrack(() => { - if (!frameRef) { - log('[NSRouter] no frameRef'); - return; - } - const state = router.state; - const matches = state.matches; - log('[NSRouter] matches:', matches.length, 'status:', state.status); - if (!matches.length) return; - - // Release native-back sync lock only after router settles out of pending. - if (nativeBackSyncInFlight && (state.status !== 'pending' || (nativeBackSyncFromPath != null && state.location.pathname !== nativeBackSyncFromPath))) { - nativeBackSyncInFlight = false; - nativeBackSyncFromPath = null; - if (guard.lockReason === 'native_back_callback') { - log('[NSRouter] native back callback releasing guard'); - releaseGuard(); - } - } - - // Drain queued native-back requests one-by-one when router is stable. - if (queuedNativeBackCount > 0) { - tryDrainQueuedNativeBack(); - } - - if (nativeBackSyncInFlight || guard.isNavigating) { - return; - } - - const curIndex = getHistoryIndex(router.history.location.state as any); - const curTransition = getNativeScriptNavigationTransition(router.history.location.state); - const curPathname = state.location.pathname; - const curModalPath = getSingleModalPathFromSearch(state.location.search); - const hasPathChanged = !shouldSkipPathNavigation(curPathname, prevPathname, prevIndex); - - if (curModalPath !== prevModalPath) { - if (!curModalPath) { - closeModalFromRouterState(); - prevModalPath = curModalPath; - } else if (!activeModalPath) { - // Defer opening modal until the base path is settled on the active page. - if (hasPathChanged && prevPathname) { - log('[NSRouter] deferring modal open until pathname settles:', curModalPath); - } else { - void openModalFromRouterState(curModalPath); - prevModalPath = curModalPath; - } - } else if (activeModalPath !== curModalPath) { - closeModalFromRouterState(); - void openModalFromRouterState(curModalPath); - prevModalPath = curModalPath; - } - } - - if (guard.isNavigating) { - log('[NSRouter] guard active; syncing prev tracking only. reason:', guard.lockReason); - prevIndex = curIndex; - prevPathname = curPathname; - return; - } - - log('[NSRouter] curPathname:', curPathname, 'prevPathname:', prevPathname, 'curIndex:', curIndex, 'prevIndex:', prevIndex); - - // Skip if the pathname hasn't changed (e.g., only search params changed) - if (!hasPathChanged) { - prevIndex = curIndex; - return; - } - - const navigationKind = getNavigationKind(prevIndex, curIndex); - const isBack = navigationKind === 'back'; - const isReplace = navigationKind === 'replace'; - - if (isBack) { - if (skipNextFrameBackNavigation) { - skipNextFrameBackNavigation = false; - log('[NSRouter] skipping Frame.goBack for native-originated back sync'); - prevIndex = curIndex; - prevPathname = curPathname; - return; - } - - acquireGuard('router_state_back'); - if (frameRef.canGoBack()) { - // Router-initiated goBack causes a native navigatingFrom(back) event. - // Suppress exactly one sync callback for this controlled pop. - suppressedNativeBackCallbacks += 1; - frameRef.goBack(); - } - prevIndex = curIndex; - prevPathname = curPathname; - setTimeout(releaseGuard, 0); - return; - } - - // Forward or replace navigation - let leafMatch = matches[matches.length - 1]; - - // If the leaf match's routeId doesn't match the current pathname, the matches - // may be stale (common for child route swaps within a layout, or parameterized - // routes like /posts/$postId where the leaf shows /posts but pathname is /posts/2). - // Find the correct route by searching all routes for one that matches the pathname. - if (!doesRouteIdMatchPathname(leafMatch.routeId, curPathname)) { - const routesById = (router as any).routesById || {}; - let resolvedRouteId: string | null = null; - - // Search all routes for one whose ID pattern matches the current pathname - for (const routeId of Object.keys(routesById)) { - if (routeId === '__root__') continue; - if (doesRouteIdMatchPathname(routeId, curPathname)) { - // Prefer the most specific match (longest routeId) - if (!resolvedRouteId || routeId.length > resolvedRouteId.length) { - resolvedRouteId = routeId; - } - } - } - - if (resolvedRouteId) { - log('[NSRouter] match/path mismatch resolved:', leafMatch.routeId, '->', resolvedRouteId, 'for pathname:', curPathname); - leafMatch = { ...leafMatch, routeId: resolvedRouteId }; - // Schedule a delayed signal update so the match stores settle and - // useParams/useMatch can read correct data when the component renders. - setTimeout(() => updateSignal(), 16); - } else { - log('[NSRouter] deferring Frame navigation due to pending match/path mismatch:', 'routeId=', leafMatch.routeId, 'pathname=', curPathname, 'status=', state.status); - // Schedule retry β€” stores may settle on next tick - setTimeout(() => updateSignal(), 16); - return; - } - } - - const route = (router as any).routesById[leafMatch.routeId]; - const rawComponent = route?.options?.component; - const Component = normalizeRenderableComponent(rawComponent); - - log('[NSRouter] leafMatch:', leafMatch.routeId, 'Component:', !!Component); - - if (!Component) { - console.error('[NSRouter] Invalid route component for route:', leafMatch.routeId, 'shape:', describeComponentShape(rawComponent), 'value:', rawComponent); - prevIndex = curIndex; - prevPathname = curPathname; - return; - } - - acquireGuard('router_state_forward_or_replace'); - - // Build the per-page chrome thunk (e.g. ) for this route, if the - // consumer supplied an `actionBar` render fn. Passed into renderPage so it renders - // inside the page's own reactive scope and slots into page.actionBar. - const pageChrome = props.actionBar - ? () => - props.actionBar!({ - path: curPathname, - routeId: leafMatch.routeId, - route, - staticData: route?.options?.staticData ?? {}, - }) - : undefined; - - log('[NSRouter] navigating Frame to', curPathname); - frameRef.navigate({ - create: () => - renderPage( - router, - Component, - curPathname, - (sourcePath) => { - if (suppressedNativeBackCallbacks > 0) { - suppressedNativeBackCallbacks -= 1; - log('[NSRouter] native back callback suppressed (router-initiated goBack)'); - return; - } - - // A stale source path still indicates a real native pop event. - // This happens when multiple native pops occur while router state is - // still settling. Queue the sync instead of dropping it. - if (sourcePath !== router.state.location.pathname) { - queuedNativeBackCount += 1; - log('[NSRouter] queued native back sync (stale source path):', 'source=', sourcePath, 'active=', router.state.location.pathname, 'count=', queuedNativeBackCount); - setTimeout(tryDrainQueuedNativeBack, 0); - return; - } - - if (nativeBackSyncInFlight) { - queuedNativeBackCount += 1; - log('[NSRouter] queued native back sync while router is busy. count=', queuedNativeBackCount, 'status=', router.state.status); - setTimeout(tryDrainQueuedNativeBack, 0); - return; - } - - log('[NSRouter] native back callback. guard:', guard.isNavigating, 'path:', router.state.location.pathname); - const decision = getNativeBackCallbackDecision({ - guardActive: guard.isNavigating, - canGoBack: router.history.canGoBack(), - }); - if (decision === 'ignore_guard_active') { - queuedNativeBackCount += 1; - log('[NSRouter] queued native back sync (guard active). count=', queuedNativeBackCount); - setTimeout(tryDrainQueuedNativeBack, 0); - return; - } - - if (decision === 'ignore_cannot_go_back') { - log('[NSRouter] native back callback ignored (cannot go back)'); - queuedNativeBackCount = 0; - return; - } - - runNativeBackSync(); - }, - reconcileRouterToVisiblePath, - props.debug, - pageChrome, - ), - animated: prevIndex >= 0 ? (props.animated ?? true) : false, - transition: curTransition ?? props.transition, - backstackVisible: !isReplace, - clearHistory: false, - }); - - prevIndex = curIndex; - prevPathname = curPathname; - - // If a modal path is present on a path transition, open it after the - // new page has a chance to become current. - if (curModalPath && !activeModalPath) { - setTimeout(() => { - const latestModalPath = getSingleModalPathFromSearch(router.state.location.search); - if (!latestModalPath || latestModalPath !== curModalPath || activeModalPath) { - return; - } - - void openModalFromRouterState(latestModalPath); - prevModalPath = latestModalPath; - }, 0); - } - - releaseGuard(); - }); - }); - - const frameEl = document.createElement('frame') as any; - frameRef = frameEl; - frameEl.setAttribute('actionBarVisibility', props.actionBarVisibility || 'never'); - return frameEl; -} diff --git a/packages/tanstack-router/src/PageRenderer.ts b/packages/tanstack-router/src/PageRenderer.ts new file mode 100644 index 0000000..dac31e0 --- /dev/null +++ b/packages/tanstack-router/src/PageRenderer.ts @@ -0,0 +1,248 @@ +import { Errored, createComponent, createRoot, flush, runWithOwner, untrack } from 'solid-js'; +import { insert } from '@nativescript-community/solid-js'; +import { RouterContextProvider, type AnyRouter } from '@tanstack/solid-router'; +import type { Component } from 'solid-js'; +import { resetNativeBackSyncScheduled, shouldScheduleNativeBackSync } from './native-back-sync'; +import { createDebugLogger } from './debug-log'; +import { describeComponentShape, normalizeRenderableComponent } from './component-shape'; +import { shouldUnmountPageOnNavigatingFrom } from './page-lifecycle'; +import { NavigatedData } from '@nativescript/core'; + +function getErrorMessage(err: unknown): string { + if (err instanceof Error) { + return err.message; + } + + return String(err); +} + +// Unlike the renderer's `render()`, disposing this root leaves the views attached, +// so a Page popped by native back keeps its content through the pop animation +// while its reactivity is already torn down. +function mountTree(parent: any, code: () => unknown): () => void { + let dispose!: () => void; + runWithOwner(null, () => + createRoot((d) => { + dispose = d; + const tree = code(); + insert(parent, () => tree); + }), + ); + flush(); + return dispose; +} + +function isExpectedBackstackError(message: string): boolean { + return message.includes('Cannot read properties of undefined') || message.includes('Could not find an active match'); +} + +export function renderPage( + router: AnyRouter, + RouteComponent: Component, + routePath: string, + onNativeBack?: (sourcePath: string) => void, + onVisiblePathChange?: (visiblePath: string) => void, + debug?: boolean, + // Optional per-page chrome thunk (e.g. an ). Called inside the page's + // render scope so it participates in the same reactive lifecycle/disposal as the + // route content. Whatever it returns is inserted as a child of the Page alongside + // the route component β€” dominative's Page slots an ActionBar child into + // `page.actionBar` and the route's root view into `page.content`. See + // `NativeScriptRouterProvider`'s `actionBar` prop. + chrome?: () => any, +): any { + const page = document.createElement('Page') as any; + const log = createDebugLogger(debug); + + let resetErrorBoundary: (() => void) | undefined; + const loggedUnexpectedErrors = new Set(); + let dispose: (() => void) | undefined; + let hasMounted = false; + let nativeBackSyncScheduled = false; + // Track the current route component reference. HMR remount swaps this so a + // freshly-imported route module's exported component takes effect on + // subsequent mounts without the consumer needing to re-call renderPage. + let currentRouteComponent: Component = RouteComponent; + + const getPagePath = () => (page as any).__nsRouterPath || routePath; + + // Reset error boundary when Page comes back from backstack + page.on('loaded', () => { + if (resetErrorBoundary) { + resetErrorBoundary(); + resetErrorBoundary = undefined; + } + }); + + // Keep a stable path tag on the page for native navigation reconciliation. + (page as any).__nsRouterPath = routePath; + + const mount = () => { + if (dispose) return; + + if (typeof RouterContextProvider !== 'function') { + console.error('[NSRouter] Invalid RouterContextProvider export:', describeComponentShape(RouterContextProvider)); + return; + } + + if (typeof Errored !== 'function') { + console.error('[NSRouter] Invalid Errored export:', describeComponentShape(Errored)); + return; + } + + const SafeRouteView = () => { + const Comp = normalizeRenderableComponent(currentRouteComponent); + if (!Comp) { + console.error('[NSRouter] Invalid render component for route path:', routePath, 'shape:', describeComponentShape(currentRouteComponent)); + return null as any; + } + + try { + return createComponent(Comp as any, {}); + } catch (err) { + console.error('[NSRouter] Route component invocation failed for path:', routePath, 'shape:', describeComponentShape(currentRouteComponent), err); + return null as any; + } + }; + + if (hasMounted) { + clearPageChildren(); + } + hasMounted = true; + + dispose = mountTree(page, () => + createComponent(RouterContextProvider, { + router, + children: () => [ + // Per-page chrome (e.g. ) rendered as a sibling of the route + // content; dominative routes it to `page.actionBar`. null when no chrome. + chrome ? chrome() : null, + createComponent(Errored, { + fallback: (err: () => unknown, reset: () => void) => { + const error = untrack(err); + const message = getErrorMessage(error); + + // Backstack pages can briefly evaluate stale route hooks while hidden. + // This is expected and intentionally swallowed by rendering nothing. + if (!isExpectedBackstackError(message) && !loggedUnexpectedErrors.has(message)) { + loggedUnexpectedErrors.add(message); + console.error('[NSRouter] Errored caught:', error); + } + + resetErrorBoundary = reset; + return null; + }, + // A getter defers creation into the boundary so render errors are caught. + get children() { + return createComponent(SafeRouteView, {}); + }, + }), + ], + }), + ); + + log('[NSRouter] page mount:', (page as any).__nsRouterPath || routePath); + }; + + const unmount = () => { + if (dispose) { + dispose(); + dispose = undefined; + log('[NSRouter] page unmount:', (page as any).__nsRouterPath || routePath); + } + }; + + // Detach the views left behind by a disposed tree (see mountTree). A Page shows + // one content view, so a fresh tree appended beside stale views never appears. + const clearPageChildren = () => { + try { + let child: any = (page as any).firstChild; + while (child) { + const next = child.nextSibling; + try { + (page as any).removeChild?.(child); + } catch (err) { + log('[NSRouter] removeChild failed during remount clear:', err); + } + child = next; + } + // dominative's Page has no __dominative_onRemoveChild, so removing the + // nodes leaves NS Core's `actionBar` / `content` slots pointing at the old + // views. Null them so the next mount always takes the first-set path. + try { + (page as any).actionBar = null; + } catch {} + try { + (page as any).content = null; + } catch {} + } catch (err) { + log('[NSRouter] clearPageChildren failed:', err); + } + }; + + // HMR entry point (see solid-hmr-remount.ts): swaps the route component in + // place instead of `frame.navigate()`, which would push a history entry and + // lose the user's place. + (page as any).__ns_remount = (nextComponent?: Component) => { + if (typeof nextComponent === 'function') { + currentRouteComponent = nextComponent; + } + unmount(); + mount(); + log('[NSRouter] page remount:', (page as any).__nsRouterPath || routePath); + }; + + // Mount immediately for the page being navigated to. + mount(); + + // Re-mount when this page becomes visible again after back navigation. + page.on('navigatedTo', () => { + nativeBackSyncScheduled = resetNativeBackSyncScheduled(); + onVisiblePathChange?.(getPagePath()); + // Deterministic lifecycle handling: once a Page is visible, it must have + // an active view tree regardless of router pending/transient state. + mount(); + log('[NSRouter] page navigatedTo:', getPagePath()); + }); + + // Sync router when this page is popped by native UI back controls + // (iOS ActionBar/UINavigationController back, swipe-back, Android native pop). + page.on('navigatingFrom', (args: NavigatedData) => { + const isBack = !!args?.isBackNavigation; + + // Tear down hidden page trees on both forward/back transitions. + // When a page becomes visible again, `navigatedTo` re-mounts it. + if (shouldUnmountPageOnNavigatingFrom(args)) { + unmount(); + } + + // For native back pops, sync router history after unmount and on next tick + // to avoid re-entrant updates in the native transition teardown stack. + if ( + shouldScheduleNativeBackSync({ + isBackNavigation: isBack, + alreadyScheduled: nativeBackSyncScheduled, + }) + ) { + nativeBackSyncScheduled = true; + log('[NSRouter] schedule native back sync from:', getPagePath()); + setTimeout(() => { + const sourcePath = getPagePath(); + log('[NSRouter] run native back sync from:', sourcePath); + onNativeBack?.(sourcePath); + }, 0); + } else if (isBack) { + log('[NSRouter] native back sync already scheduled for:', getPagePath()); + } + + log('[NSRouter] page navigatingFrom:', getPagePath(), 'isBack:', isBack); + }); + + // Clean up SolidJS tree when native Page is destroyed + page.on('disposeNativeView', () => { + nativeBackSyncScheduled = resetNativeBackSyncScheduled(); + unmount(); + }); + + return page; +} diff --git a/packages/tanstack-router/src/PageRenderer.tsx b/packages/tanstack-router/src/PageRenderer.tsx deleted file mode 100644 index 0dbb7d9..0000000 --- a/packages/tanstack-router/src/PageRenderer.tsx +++ /dev/null @@ -1,317 +0,0 @@ -import { ErrorBoundary, createComponent } from 'solid-js' -import { render } from '@nativescript-community/solid-js' -import { RouterContextProvider, type AnyRouter } from '@tanstack/solid-router' -import type { Component } from 'solid-js' -import { - resetNativeBackSyncScheduled, - shouldScheduleNativeBackSync, -} from './native-back-sync' -import { createDebugLogger } from './debug-log' -import { describeComponentShape, normalizeRenderableComponent } from './component-shape' -import { shouldUnmountPageOnNavigatingFrom } from './page-lifecycle' -import { NavigatedData } from '@nativescript/core' - -function getErrorMessage(err: unknown): string { - if (err instanceof Error) { - return err.message - } - - return String(err) -} - -function isExpectedBackstackError(message: string): boolean { - return ( - message.includes("Cannot read properties of undefined") || - message.includes('Could not find an active match') - ) -} - -// Unwrap a solid-refresh proxy chain to the underlying user component -// function. See `solid-hmr-remount.ts` for full reasoning β€” the short -// version is that mounting with the proxy creates a HMRComp createMemo -// subscribed to the M_initial signal, which in our universal-renderer + -// nested context provider configuration is the source of "every other -// save applies". Mounting with the underlying function is a clean, -// single-pass render with no signal-based reactivity for solid-refresh -// to interfere with. -function unwrapSolidRefreshProxyInline(value: any): any { - if (typeof value !== 'function') return value - let current: any = value - let hops = 0 - while (typeof current?.__$ns_resolveSource === 'function' && hops < 8) { - try { - const next = current.__$ns_resolveSource() - if (typeof next !== 'function' || next === current) break - current = next - hops++ - } catch { - break - } - } - return current -} - -export function renderPage( - router: AnyRouter, - RouteComponent: Component, - routePath: string, - onNativeBack?: (sourcePath: string) => void, - onVisiblePathChange?: (visiblePath: string) => void, - debug?: boolean, - // Optional per-page chrome thunk (e.g. an ). Called inside the page's - // render scope so it participates in the same reactive lifecycle/disposal as the - // route content. Whatever it returns is inserted as a child of the Page alongside - // the route component β€” dominative's Page slots an ActionBar child into - // `page.actionBar` and the route's root view into `page.content`. See - // `NativeScriptRouterProvider`'s `actionBar` prop. - chrome?: () => any, -): any { - const page = document.createElement('Page') as any - const log = createDebugLogger(debug) - - let resetErrorBoundary: (() => void) | undefined - const loggedUnexpectedErrors = new Set() - let dispose: (() => void) | undefined - let nativeBackSyncScheduled = false - // Track the current route component reference. HMR remount swaps this so a - // freshly-imported route module's exported component takes effect on - // subsequent mounts without the consumer needing to re-call renderPage. - let currentRouteComponent: Component = RouteComponent - - const getPagePath = () => (page as any).__nsRouterPath || routePath - - // Reset error boundary when Page comes back from backstack - page.on('loaded', () => { - if (resetErrorBoundary) { - resetErrorBoundary() - resetErrorBoundary = undefined - } - }) - - // Keep a stable path tag on the page for native navigation reconciliation. - ;(page as any).__nsRouterPath = routePath - - const mount = () => { - if (dispose) return - - if (typeof RouterContextProvider !== 'function') { - console.error('[NSRouter] Invalid RouterContextProvider export:', describeComponentShape(RouterContextProvider)) - return - } - - if (typeof ErrorBoundary !== 'function') { - console.error('[NSRouter] Invalid ErrorBoundary export:', describeComponentShape(ErrorBoundary)) - return - } - - const SafeRouteView = () => { - // Unwrap solid-refresh proxies (M_save_X.proxy β†’ M_initial.proxy β†’ fn) - // ALSO at boot (not just HMR remount). If we mount with the proxy, its - // HMRComp body creates a createMemo subscribed to M_initial.source. - // That subscription survives subsequent unmounts in subtle ways - // (cleanNode unsubscribes, but the cached value held by the renderEffect - // closure still references the previous JSX), and the next HMR cycle's - // patchRegistry causes the previous mount's leftover memo to re-evaluate - // BEFORE our remount fires β€” producing the visible "every other save - // applies / always one save behind" symptom. By unwrapping here we - // ensure devComponent calls the underlying user function directly with - // no proxy chain at any mount, boot or HMR. - const raw = normalizeRenderableComponent(currentRouteComponent) - const Comp = unwrapSolidRefreshProxyInline(raw) - if (!Comp) { - console.error( - '[NSRouter] Invalid render component for route path:', - routePath, - 'shape:', - describeComponentShape(currentRouteComponent), - ) - return null as any - } - - // Diagnostic: surface the proxy/component identity SafeRouteView is - // about to render. Pairs with the inline patchRegistry diagnostics in - // `@solid-refresh` ($$refreshESM) β€” together they make the - // "did patchRegistry actually swap the signal AND did mount actually - // render that swapped proxy?" question answerable from the device - // console without instrumenting solid-js itself. - try { - const compName = (Comp as any).name || 'anonymous' - const compTag = (Comp as any).location || '' - log('[NSRouter] SafeRouteView render β€” component name=', compName, 'location=', compTag) - } catch {} - - try { - return createComponent(Comp as any, {}) - } catch (err) { - console.error( - '[NSRouter] Route component invocation failed for path:', - routePath, - 'shape:', - describeComponentShape(currentRouteComponent), - err, - ) - return null as any - } - } - - dispose = render( - () => ( - - {() => [ - // Per-page chrome (e.g. ) rendered as a sibling of the route - // content; dominative routes it to `page.actionBar`. null when no chrome. - chrome ? chrome() : null, - void) => { - const message = getErrorMessage(err) - - // Backstack pages can briefly evaluate stale route hooks while hidden. - // This is expected and intentionally swallowed by rendering nothing. - if (!isExpectedBackstackError(message) && !loggedUnexpectedErrors.has(message)) { - loggedUnexpectedErrors.add(message) - console.error('[NSRouter] ErrorBoundary caught:', err) - } - - resetErrorBoundary = reset - return null as any - }} - > - - , - ]} - - ), - page, - ) - - log('[NSRouter] page mount:', (page as any).__nsRouterPath || routePath) - } - - const unmount = () => { - if (dispose) { - dispose() - dispose = undefined - log('[NSRouter] page unmount:', (page as any).__nsRouterPath || routePath) - } - } - - // Detach every child currently attached to the Page. Solid's `dispose()` - // tears down reactive computations but does NOT remove DOM nodes β€” so a - // naive unmount + mount leaves the old subtree attached and the new one - // gets appended alongside it. NativeScript Pages can only display one - // root content view at a time, so without this clear the new tree never - // becomes visible (the user keeps seeing the stale render). Used only on - // explicit remount paths (HMR), never during routine navigation. - const clearPageChildren = () => { - try { - let child: any = (page as any).firstChild - while (child) { - const next = child.nextSibling - try { - ;(page as any).removeChild?.(child) - } catch (err) { - log('[NSRouter] removeChild failed during remount clear:', err) - } - child = next - } - // dominative's Page wrapper has no __dominative_onRemoveChild β€” undom - // clears `page.childNodes` but NS Core's `Page._actionBar` and - // `Page._content` references stay pointing at the previous mount's - // elements. The next mount inserts NEW elements which trigger the - // setters' identity check (different => replace), so this is usually - // a no-op safety. But under HMR remount we've observed cases where the - // NS view tree retains stale visible content even though the new - // dominative tree was correctly built. Explicitly null out the slots - // before the mount inserts fresh elements so the setters always take - // the "first set" path (no comparison against a stale reference). - try { - ;(page as any).actionBar = null - } catch {} - try { - ;(page as any).content = null - } catch {} - } catch (err) { - log('[NSRouter] clearPageChildren failed:', err) - } - } - - // Expose a remount API so HMR-aware code (e.g. - // `NativeScriptRouterProvider`'s solid-hmr subscriber) can swap in a - // freshly-imported route component without going through - // `frame.navigate()` (which would push a new history entry and lose the - // user's place). When `nextComponent` is provided the page picks up that - // reference on the next mount; otherwise it re-mounts with whatever - // reference is currently held (useful when the proxy itself was patched - // in place, e.g. solid-refresh). - ;(page as any).__ns_remount = (nextComponent?: Component) => { - if (typeof nextComponent === 'function') { - // Diagnostic: surface whether nextComponent identity changes from - // call to call. If the same proxy instance is passed across saves - // AND solid-refresh's patchRegistry is functioning, the proxy's - // internal signal source should still produce the latest body. - try { - const sameAsBefore = currentRouteComponent === nextComponent - log('[NSRouter] __ns_remount component identity sameAsBefore=', sameAsBefore, 'name=', (nextComponent as any).name || 'anonymous') - } catch {} - currentRouteComponent = nextComponent - } - unmount() - clearPageChildren() - mount() - log('[NSRouter] page remount:', (page as any).__nsRouterPath || routePath) - } - - // Mount immediately for the page being navigated to. - mount() - - // Re-mount when this page becomes visible again after back navigation. - page.on('navigatedTo', () => { - nativeBackSyncScheduled = resetNativeBackSyncScheduled() - onVisiblePathChange?.(getPagePath()) - // Deterministic lifecycle handling: once a Page is visible, it must have - // an active view tree regardless of router pending/transient state. - mount() - log('[NSRouter] page navigatedTo:', getPagePath()) - }) - - // Sync router when this page is popped by native UI back controls - // (iOS ActionBar/UINavigationController back, swipe-back, Android native pop). - page.on('navigatingFrom', (args: NavigatedData) => { - const isBack = !!args?.isBackNavigation - - // Tear down hidden page trees on both forward/back transitions. - // When a page becomes visible again, `navigatedTo` re-mounts it. - if (shouldUnmountPageOnNavigatingFrom(args)) { - unmount() - } - - // For native back pops, sync router history after unmount and on next tick - // to avoid re-entrant updates in the native transition teardown stack. - if ( - shouldScheduleNativeBackSync({ - isBackNavigation: isBack, - alreadyScheduled: nativeBackSyncScheduled, - }) - ) { - nativeBackSyncScheduled = true - log('[NSRouter] schedule native back sync from:', getPagePath()) - setTimeout(() => { - const sourcePath = getPagePath() - log('[NSRouter] run native back sync from:', sourcePath) - onNativeBack?.(sourcePath) - }, 0) - } else if (isBack) { - log('[NSRouter] native back sync already scheduled for:', getPagePath()) - } - - log('[NSRouter] page navigatingFrom:', getPagePath(), 'isBack:', isBack) - }) - - // Clean up SolidJS tree when native Page is destroyed - page.on('disposeNativeView', () => { - nativeBackSyncScheduled = resetNativeBackSyncScheduled() - unmount() - }) - - return page -} diff --git a/packages/tanstack-router/src/router.ts b/packages/tanstack-router/src/router.ts index ca9308e..b54800f 100644 --- a/packages/tanstack-router/src/router.ts +++ b/packages/tanstack-router/src/router.ts @@ -7,6 +7,11 @@ import { createNativeScriptHistory } from './history'; if (typeof self === 'undefined') { (globalThis as any).self = globalThis; } +// router-core resets window scroll after every render; NativeScript pages own +// their scroll state, so the global is a no-op. +if (typeof (globalThis as any).scrollTo !== 'function') { + (globalThis as any).scrollTo = () => {}; +} if (typeof AbortController === 'undefined') { (globalThis as any).AbortController = NativeScriptAbortController; (globalThis as any).AbortSignal = NativeScriptAbortSignal; @@ -14,16 +19,21 @@ if (typeof AbortController === 'undefined') { type RouterOptions = Parameters>[0]; -export function createNativeScriptRouter( - opts: Omit, 'history'> & { - initialPath?: string; - }, -) { +type NativeScriptRouterOptions = Omit, 'history'> & { + initialPath?: string; +}; + +/** Creates a router without registering it as the app router (used for modal stacks). */ +export function createDetachedNativeScriptRouter(opts: NativeScriptRouterOptions) { const { initialPath, ...routerOpts } = opts; - const router = createRouter({ + return createRouter({ ...(routerOpts as RouterOptions), history: createNativeScriptHistory({ initialPath }), }); +} + +export function createNativeScriptRouter(opts: NativeScriptRouterOptions) { + const router = createDetachedNativeScriptRouter(opts); // Dev-only: expose router for HMR client to patch route loaders // when non-component utility modules change (standard pattern: // React uses __REACT_DEVTOOLS_GLOBAL_HOOK__, Vue uses __VUE_HMR_RUNTIME__). diff --git a/packages/tanstack-router/src/solid-hmr-remount.ts b/packages/tanstack-router/src/solid-hmr-remount.ts index 70a95e1..caa4d87 100644 --- a/packages/tanstack-router/src/solid-hmr-remount.ts +++ b/packages/tanstack-router/src/solid-hmr-remount.ts @@ -54,61 +54,10 @@ function findRouteByFullPath(router: any, fullPath: string): any | null { return rootMatch; } -// Resolve a solid-refresh proxy chain down to the underlying user component -// function. solid-refresh wraps every component in a `createProxy`-returned -// Proxy whose `HMRComp` body returns `createMemo(() => source()(props))`. -// On HMR, `patchComponent` rewrites M_save_X.signal.value = M_initial.proxy -// and M_initial.signal.value = newHomeFn, so calling M_save_X.proxy(props) -// goes M_save_X.proxy β†’ OUTER memo β†’ M_initial.proxy β†’ INNER memo β†’ newHomeFn. -// -// The nested memo chain is the source of "every other save applies": each -// remount's INNER memo subscribes to M_initial.source, and on patch the -// previous mount's INNER memos (still subscribed because the disposal -// behavior under universal-renderer + nested context provider isn't fully -// torn down before the next patch) re-evaluate, producing zombie renders -// that fight the fresh mount's renderEffect. -// -// By unwrapping the proxy chain HERE β€” before passing to `__ns_remount` β€” -// we hand the page the freshly-evaluated user function directly. The page's -// `createComponent(fn, {})` then runs `fn({})` without any HMRComp memos. -// Each save's mount is a clean, single-pass render with no signal-based -// reactivity to share with previous mounts. solid-refresh's patchRegistry -// still updates the registry (so other consumers that hold the proxy -// reference also see fresh behavior), but our page mount is decoupled. -// -// Each call to source() returns either another solid-refresh proxy -// (recurse) or the underlying user function (terminate). -function unwrapSolidRefreshProxy(value: any, log: (...a: any[]) => void): any { - if (typeof value !== 'function') return value; - let current: any = value; - let hops = 0; - // The escape hatch is `__$ns_resolveSource` (NOT `__$$ns_resolveSource`): - // Vite's plugin patches solid-refresh via String.prototype.replace, where - // `$$` in the replacement is a literal `$`. We use a single `$` to avoid - // that footgun. - while (typeof current?.__$ns_resolveSource === 'function' && hops < 8) { - try { - const next = current.__$ns_resolveSource(); - if (typeof next !== 'function' || next === current) break; - current = next; - hops++; - } catch (err) { - log('[NSRouter][hmr] unwrapSolidRefreshProxy error at hop', hops, err); - break; - } - } - log('[NSRouter][hmr] unwrap', 'name=', (value as any)?.name, 'hops=', hops, 'finalName=', (current as any)?.name); - return current; -} - -// Ask a Page (rendered by `PageRenderer.renderPage`) to dispose its current -// Solid tree and remount with `nextComponent` as the route component. When -// `nextComponent` is undefined, the page reuses its existing component -// reference β€” which for solid-refresh is the proxy, whose internal signal -// has already been swapped by `patchRegistry` so a fresh render emits the -// updated body. Pages render through the same RouterContextProvider / -// ErrorBoundary chain, so a remount picks up the freshest behavior without -// a Frame.navigate (no backstack churn, no native page transition). +// Ask a Page (rendered by `PageRenderer.renderPage`) to dispose its Solid tree +// and remount, with `nextComponent` as the route component when given. Done in +// place rather than through Frame.navigate (no backstack churn, no native page +// transition). function remountPage(page: any, nextComponent: any, log: (...a: any[]) => void): boolean { if (!page || typeof page.__ns_remount !== 'function') { return false; @@ -148,30 +97,15 @@ function collectFramePages(frame: any): any[] { return pages; } -// Subscribe to the NS HMR client's Solid completion event and trigger a -// page-level remount whenever a Solid HMR cycle finishes. Returns a cleanup -// function that unsubscribes from the HMR event stream. -// -// Strategy: when ANY .tsx file changes (route OR component), every Page held -// by the Frame is remounted. We don't try to map "which file changed" to -// "which page depends on it" β€” `solid-refresh` already swapped the proxy -// signals globally, so a fresh render of any page automatically picks up the -// latest component bodies. Remounting unaffected pages is a few-millisecond -// no-op cost, and avoiding the dependency analysis means HMR Just Works for -// edits to shared components, hooks, utilities, etc., not just route files. -// -// For route-file edits we do prefer to pass the freshly-patched component -// reference explicitly (rather than reusing the existing proxy ref) so that -// any deep-equality checks downstream see a different identity. +// The NS HMR client (@nativescript/vite) re-imports changed route files, patches +// `route.options.component` with the fresh export, then emits a Solid completion +// event. Every Page held by the Frame (and any open modal) is remounted on that +// event; mapping changed files to dependent pages is not worth the analysis, and +// remounting an unaffected page is cheap. Without the HMR client (production, +// tests) this is a no-op. // -// If the NS HMR client is not present (production builds, tests, or older -// runtimes that don't expose `__ns_solid_hmr_subscribe`), this is a no-op -// and returns a no-op cleanup. -// Resolve (or lazily create) the shared globalThis-stored listener Set used -// by the NS HMR client. By using the same Set the HMR client iterates at -// emit time, we sidestep module-instance / realm mismatches that can occur -// in NativeScript when the HMR client and user-app modules load via -// different paths (HTTP loader vs bundled vendor realm). +// The listener Set lives on globalThis because the HMR client and app modules +// can load as separate module instances (HTTP loader vs vendor realm). function resolveSharedListenerSet(): Set<(ev: NsSolidHmrEvent) => void> { const g = globalThis as any; let set = g.__ns_solid_hmr_listener_set as Set<(ev: NsSolidHmrEvent) => void> | undefined; @@ -205,11 +139,7 @@ export function subscribeSolidHmrRemount(opts: SolidHmrRemountOptions): NsSolidH const fullPath = boundaryToFullPath(bid); if (!fullPath) continue; const route = findRouteByFullPath(router, fullPath); - const rawComp = normalizeRenderableComponent(route?.options?.component); - // Unwrap the solid-refresh proxy chain so the page mount calls the - // freshly-loaded user function directly. See unwrapSolidRefreshProxy - // for full reasoning β€” this is the fix for "every other save applies". - const Comp = unwrapSolidRefreshProxy(rawComp, log); + const Comp = normalizeRenderableComponent(route?.options?.component); if (Comp) routePathToComponent.set(fullPath, Comp); } diff --git a/packages/tanstack-router/src/solid-web-shim.js b/packages/tanstack-router/src/solid-web-shim.js deleted file mode 100644 index 2435408..0000000 --- a/packages/tanstack-router/src/solid-web-shim.js +++ /dev/null @@ -1,98 +0,0 @@ -// Shim for solid-js/web in NativeScript -// Re-exports everything from core solid-js (which the NativeScript community plugin aliases) -// plus web-specific exports that @tanstack/solid-router dependencies need -export * from 'solid-js'; - -// NativeScript is never server-side -export const isServer = false; - -// Web-specific rendering functions used by @tanstack/solid-router -// These are no-ops or simple pass-throughs in NativeScript -export function Dynamic(props) { - const comp = typeof props.component === 'function' ? props.component : null; - if (comp) return comp(props); - return null; -} - -export function delegateEvents() {} -export function clearDelegatedEvents() {} -export function spread() {} -export function assign() {} -export function setAttribute() {} -export function setProperty() {} -export function insert() {} -export function effect() {} -export function style() {} -export function classList() {} -export function memo(fn) { - return fn; -} -export function template() { - return function () {}; -} -export function getNextElement() {} -export function getNextMarker() {} -export function getNextMatch() {} -export function escape(s) { - return s; -} -export function ssrElement() { - return ''; -} -export function ssrAttribute() { - return ''; -} -export function ssrHydrationKey() { - return ''; -} -export function ssr() { - return ''; -} -export function ssrSpread() { - return ''; -} -export function resolveSSRNode() { - return ''; -} -export function generateHydrationScript() { - return ''; -} -export function HydrationScript() { - return ''; -} -export function Hydration() { - return ''; -} -export function NoHydration() { - return ''; -} -export function getHydrationKey() {} -export function hydrate() {} -export function renderToString() { - return ''; -} -export function renderToStringAsync() { - return Promise.resolve(''); -} -export function renderToStream() { - return {}; -} -export function Assets() { - return null; -} -export function useAssets(fn) {} -export function pipeToNodeWritable() {} -export function pipeToWritable() {} -export function addEventListener() {} -export function removeEventListener() {} -export function dynamicProperty() {} -export function setAttributeNS() {} -export const Aliases = {}; -export function getPropAlias(prop) { - return prop; -} -export const Properties = new Set(); -export const ChildProperties = new Set(); -export const DelegatedEvents = new Set(); -export const SVGElements = new Set(); -export const SVGNamespace = {}; diff --git a/packages/tanstack-router/src/start-transition.ts b/packages/tanstack-router/src/start-transition.ts new file mode 100644 index 0000000..f531794 --- /dev/null +++ b/packages/tanstack-router/src/start-transition.ts @@ -0,0 +1,23 @@ +import { flush, runWithOwner } from 'solid-js'; +import type { AnyRouter } from '@tanstack/solid-router'; + +/** + * Stand-in for the transition hook solid-router's `` installs. + * NativeScript renders Pages through Frame.navigate() instead of a `` + * tree, so `` is never mounted. router-core still moves `status` + * to idle, sets `resolvedLocation` and emits onResolved/onRendered once the + * returned promise settles. + */ +export function installNativeScriptStartTransition(router: AnyRouter): void { + router.startTransition = (fn: () => void) => { + // Store writes are forbidden inside owned scopes; flushing right away lets + // listeners see the committed matches before the router reports them rendered. + runWithOwner(null, fn); + try { + flush(); + } catch { + // As in : an effect error must not abort the router's commit. + } + return Promise.resolve(true); + }; +} diff --git a/packages/tanstack-router/test/full-deployed-flow.test.ts b/packages/tanstack-router/test/full-deployed-flow.test.ts index 106596c..6f96ee3 100644 --- a/packages/tanstack-router/test/full-deployed-flow.test.ts +++ b/packages/tanstack-router/test/full-deployed-flow.test.ts @@ -1,170 +1,156 @@ // @vitest-environment jsdom // -// Closest possible reproduction of the deployed bundle's render flow: -// - universal renderer (just like @nativescript-community/solid-js) -// - the published `solid-js-jsx-runtime-shim.js`'s `jsx` function (via dynamic import) -// - the published `renderPage` shape: render(() => jsx(RouterContextProvider, {router, children: () => jsx(ErrorBoundary, {fallback, children: jsx(SafeRouteView, {})})}), page) -// - SafeRouteView -> Home -> returns ARRAY [actionbar, scrollview-tree] - -import { describe, it, expect, beforeAll, vi } from 'vitest'; -import { createRenderer } from 'solid-js/universal'; -import { ErrorBoundary, createComponent } from 'solid-js'; -import { RouterContextProvider, createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi } from '@tanstack/solid-router'; -// Load the actual published shim's jsx (same file that ships in the package) -import { jsx } from '../solid-js-jsx-runtime-shim.js'; - -vi.mock('solid-js/web', async () => { +// Runs the shipped `renderPage` against a real router, with only the NativeScript +// layer faked: `@nativescript-community/solid-js` is a FakeNode-backed universal +// renderer and `document.createElement('Page')` returns a FakeNode page that +// fills NativeScript's `actionBar` / `content` slots. + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi } from '@tanstack/solid-router'; +import { FakeNode, collectTags } from './support/fake-native-renderer'; + +vi.mock('@nativescript-community/solid-js', async () => { + const { createFakeCommunitySolid } = await import('./support/fake-native-renderer'); + return createFakeCommunitySolid(); +}); + +vi.mock('@solidjs/web', async () => { return await import('../solid-web-shim.js'); }); +vi.mock('@nativescript/core', () => ({})); + +const community = await import('@nativescript-community/solid-js'); +const { renderPage } = await import('../src/PageRenderer'); + +const originalCreateElement = document.createElement; + beforeAll(() => { - process.env.NODE_ENV = 'development'; + (document as any).createElement = (tag: string) => new FakeNode(tag.toLowerCase()); +}); + +afterAll(() => { + (document as any).createElement = originalCreateElement; }); -type FakeNode = { - tag: string; - text?: string; - attrs: Record; - children: Array; - parent?: FakeNode; - // dominative-Page-style content + actionBar slots - actionBar?: FakeNode; - content?: FakeNode; - isPage?: boolean; - isActionBar?: boolean; -}; - -function makeNode(tag: string): FakeNode { - const node: FakeNode = { tag, attrs: {}, children: [] }; - if (tag === 'page' || tag === 'Page') node.isPage = true; - if (tag === 'actionbar') node.isActionBar = true; - return node; +const settle = () => new Promise((r) => setTimeout(r, 30)); + +function createLabel(text: string) { + const label = community.createElement('label'); + community.setProp(label, 'text', text); + return label; } -const universal = createRenderer({ - createElement(tag) { - return makeNode(tag); - }, - createTextNode(value) { - const n = makeNode('#text'); - n.text = value; - return n; - }, - isTextNode(node) { - return node.tag === '#text'; - }, - replaceText(node, value) { - node.text = value; - }, - setProperty(node, name, value) { - node.attrs[name] = value; - }, - insertNode(parent, node, anchor) { - if (anchor) { - const idx = parent.children.indexOf(anchor); - parent.children.splice(idx, 0, node); - } else { - parent.children.push(node); - } - node.parent = parent; - // Mimic dominative Page child handling - if (parent.isPage) { - if (node.isActionBar) parent.actionBar = node; - else parent.content = node; - } - }, - removeNode(parent, node) { - const idx = parent.children.indexOf(node); - if (idx >= 0) parent.children.splice(idx, 1); - if (parent.actionBar === node) parent.actionBar = undefined; - if (parent.content === node) parent.content = undefined; - node.parent = undefined; - }, - getParentNode(node) { - return node.parent as FakeNode; - }, - getFirstChild(node) { - return node.children[0] as FakeNode; - }, - getNextSibling(node) { - if (!node.parent) return undefined as unknown as FakeNode; - const idx = node.parent.children.indexOf(node); - return node.parent.children[idx + 1] as FakeNode; - }, -}); +async function createLoadedRouter(component: () => any) { + const rootRoute = createRootRoute(); + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => ({ greeting: 'hi' }), + component, + }); + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }); + await router.load(); + expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); + return router; +} -describe('Full deployed render flow', () => { - it('inserts actionbar + scrollview into Page when Home returns a fragment array', async () => { - const rootRoute = createRootRoute(); - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: () => ({ greeting: 'hi' }), - component: () => { - // Mimic what babel-preset-solid emits for Home() - const route = getRouteApi('/'); - const data = route.useLoaderData(); - void data(); - const ab = universal.createElement('actionbar'); - universal.setProp(ab, 'title', 'TanStack Router', undefined); - const sv = universal.createElement('scrollview'); - const sl = universal.createElement('stacklayout'); - const lbl = universal.createElement('label'); - universal.setProp(lbl, 'text', 'Native SolidJS News', undefined); - universal.insertNode(sl, lbl); - universal.insertNode(sv, sl); - return [ab, sv] as any; - }, +describe('renderPage (deployed render flow)', () => { + it('slots a fragment-returning route component into the Page actionBar and content', async () => { + const router = await createLoadedRouter(() => { + const data = getRouteApi('/').useLoaderData(); + const actionBar = community.createElement('actionbar'); + community.setProp(actionBar, 'title', 'TanStack Router'); + const scroll = community.createElement('scrollview'); + const stack = community.createElement('stacklayout'); + community.insert(stack, () => createLabel(`greeting:${(data() as any).greeting}`)); + community.insertNode(scroll, stack); + return [actionBar, scroll]; }); - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }); + const Home = (router as any).routesById['/'].options.component; + const page = renderPage(router as any, Home, '/') as FakeNode; + await settle(); - await router.load(); - expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); - - const page = makeNode('page'); - let caught: any; - - const Comp = (indexRoute as any).options.component; - const SafeRouteView = () => createComponent(Comp, {}); - - const dispose = universal.render( - (() => - jsx(RouterContextProvider, { - router, - children: () => - jsx(ErrorBoundary, { - fallback: (err: any) => { - caught = err; - return null; - }, - children: jsx(SafeRouteView, {}), - }), - })) as any, - page, - ); - - await new Promise((r) => setTimeout(r, 50)); - - // Diagnose - if (page.children.length === 0) { - console.error('Page is EMPTY β€” repro!'); - console.error( - 'Page snapshot:', - JSON.stringify(page, (k, v) => (k === 'parent' ? undefined : v), 2), - ); - } - - expect(caught, `ErrorBoundary should not have caught anything but got: ${caught?.message ?? caught}`).toBeUndefined(); - expect(page.children.length, 'page should have inserted children').toBeGreaterThan(0); expect(page.actionBar?.tag).toBe('actionbar'); expect(page.actionBar?.attrs.title).toBe('TanStack Router'); expect(page.content?.tag).toBe('scrollview'); + expect(collectTags(page)).toEqual(['actionbar', 'scrollview', 'stacklayout', 'label']); + const label = page.content!.children[0].children[0]; + expect(label.attrs.text).toBe('greeting:hi'); + }); + + it('renders per-page chrome beside the route content', async () => { + const router = await createLoadedRouter(() => community.createElement('stacklayout')); + const Home = (router as any).routesById['/'].options.component; + + const page = renderPage(router as any, Home, '/', undefined, undefined, false, () => { + const actionBar = community.createElement('actionbar'); + community.setProp(actionBar, 'title', 'Chrome'); + return actionBar; + }) as FakeNode; + await settle(); + + expect(page.actionBar?.attrs.title).toBe('Chrome'); + expect(page.content?.tag).toBe('stacklayout'); + }); + + it('swallows reactive route errors and resets the boundary when the page loads again', async () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); + let shouldThrow = true; + const router = await createLoadedRouter(() => { + const stack = community.createElement('stacklayout'); + community.insert(stack, () => { + if (shouldThrow) throw new Error('boom'); + return createLabel('recovered'); + }); + return stack; + }); + const Home = (router as any).routesById['/'].options.component; + + const page = renderPage(router as any, Home, '/') as FakeNode; + await settle(); + + expect(collectTags(page)).toEqual([]); + expect(errorSpy).toHaveBeenCalledWith('[NSRouter] Errored caught:', expect.objectContaining({ message: 'boom' })); + + shouldThrow = false; + page.emit('loaded'); + await settle(); + + expect(collectTags(page)).toEqual(['stacklayout', 'label']); + errorSpy.mockRestore(); + }); + + it('keeps the views of a page popped by native back, and remounts cleanly afterwards', async () => { + const router = await createLoadedRouter(() => createLabel('first')); + const Home = (router as any).routesById['/'].options.component; + const page = renderPage(router as any, Home, '/') as FakeNode; + await settle(); + + page.emit('navigatingFrom', { isBackNavigation: true }); + expect(page.content?.attrs.text, 'views stay attached for the pop animation').toBe('first'); + + page.emit('navigatedTo'); + await settle(); + expect(page.children.filter((c) => c.tag !== '#text')).toHaveLength(1); + expect(page.content?.attrs.text).toBe('first'); + }); + + it('__ns_remount swaps the route component in place', async () => { + const router = await createLoadedRouter(() => createLabel('before')); + const Home = (router as any).routesById['/'].options.component; + const page = renderPage(router as any, Home, '/') as any; + await settle(); + expect(page.content?.attrs.text).toBe('before'); + + page.__ns_remount(() => createLabel('after')); + await settle(); - dispose(); + expect(page.children.filter((c: FakeNode) => c.tag !== '#text')).toHaveLength(1); + expect(page.content?.attrs.text).toBe('after'); }); }); diff --git a/packages/tanstack-router/test/ns-render-via-shim.test.ts b/packages/tanstack-router/test/ns-render-via-shim.test.ts index 14a6748..a565d0f 100644 --- a/packages/tanstack-router/test/ns-render-via-shim.test.ts +++ b/packages/tanstack-router/test/ns-render-via-shim.test.ts @@ -1,86 +1,51 @@ // @vitest-environment jsdom // -// Reproduces the NativeScript rendering pipeline using the universal Solid -// renderer plus our `solid-web-shim.js`, mirroring how the @nativescript/vite -// `solid` config aliases `solid-js/web` for app builds. This catches the kind -// of cross-package reactivity bugs that show up as "blank screen" in NS at -// runtime β€” for instance, the 1.168+ regression where `useMatch` couldn't -// resolve the active match and `` ended up rendering -// nothing because our shim's `memo()` wasn't actually memoizing. - -import { describe, it, expect, beforeAll, vi } from 'vitest'; -import { createRenderer } from 'solid-js/universal'; -import { createComponent, ErrorBoundary } from 'solid-js'; -import { createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi, RouterContextProvider } from '@tanstack/solid-router'; - -// Provide a `solid-js/web` alias backed by the actual shim file shipped in -// the package so the imports from @tanstack/solid-router resolve through it. -vi.mock('solid-js/web', async () => { - return await import('../solid-web-shim.js'); +// Drives @tanstack/solid-router's own components (RouterContextProvider, Outlet β†’ +// Match, Dynamic, memo) through the shipped `solid-web-shim.js`, with the +// NativeScript renderer swapped for a FakeNode-backed universal renderer. This is +// the wiring an app gets once nativescript.vite.mjs aliases `@solidjs/web`. + +import { describe, it, expect, vi } from 'vitest'; +import { Errored, createComponent, flush, untrack } from 'solid-js'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi, Match, Outlet, RouterContextProvider } from '@tanstack/solid-router'; +import { FakeNode, collectTags } from './support/fake-native-renderer'; + +vi.mock('@nativescript-community/solid-js', async () => { + const { createFakeCommunitySolid } = await import('./support/fake-native-renderer'); + return createFakeCommunitySolid(); }); -beforeAll(() => { - process.env.NODE_ENV = 'development'; +vi.mock('@solidjs/web', async () => { + return await import('../solid-web-shim.js'); }); -// Minimal "NativeScript-like" element backing β€” just a tiny tagged tree we -// can introspect to verify children were inserted. -type FakeNode = { - tag: string; - text?: string; - children: Array; - parent?: FakeNode; - attrs: Record; -}; - -function makeNode(tag: string): FakeNode { - return { tag, children: [], attrs: {} }; +const community = await import('@nativescript-community/solid-js'); +const shim: any = await import('../solid-web-shim.js'); + +function renderIntoPage(router: any, view: () => any) { + const page = new FakeNode('page'); + let caught: unknown; + const dispose = community.render( + () => + createComponent(RouterContextProvider as any, { + router, + children: () => + createComponent(Errored, { + fallback: (err: () => unknown) => { + caught = untrack(err); + return null; + }, + get children() { + return view(); + }, + }), + }), + page, + ); + return { page, dispose, caught: () => caught }; } -const universal = createRenderer({ - createElement(tag) { - return makeNode(tag); - }, - createTextNode(value) { - const n = makeNode('#text'); - n.text = value; - return n; - }, - isTextNode(node) { - return node.tag === '#text'; - }, - replaceText(node, value) { - node.text = value; - }, - setProperty(node, name, value) { - node.attrs[name] = value; - }, - insertNode(parent, node, anchor) { - if (anchor) { - const idx = parent.children.indexOf(anchor); - parent.children.splice(idx, 0, node); - } else { - parent.children.push(node); - } - node.parent = parent; - }, - removeNode(parent, node) { - const idx = parent.children.indexOf(node); - if (idx >= 0) parent.children.splice(idx, 1); - node.parent = undefined; - }, - getParentNode(node) { - return node.parent as FakeNode; - }, - getFirstChild(node) { - return node.children[0] as FakeNode; - }, - getNextSibling(node) { - if (!node.parent) return undefined as unknown as FakeNode; - const idx = node.parent.children.indexOf(node); - return node.parent.children[idx + 1] as FakeNode; - }, -}); +const settle = () => new Promise((r) => setTimeout(r, 30)); describe('NativeScript rendering pipeline (universal renderer + solid-web-shim)', () => { it('renders the leaf route component with reactive loaderData via getRouteApi', async () => { @@ -91,16 +56,11 @@ describe('NativeScript rendering pipeline (universal renderer + solid-web-shim)' const HomeComponent: any = () => { homeInvocations++; - const route = getRouteApi('/'); - const loaderData = route.useLoaderData(); - lastLoaderData = loaderData(); - // Build a small NS-style tree so we can verify it was inserted into the page - const label = makeNode('label'); - label.attrs.text = `loaded:${(loaderData() as any)?.greeting ?? 'NONE'}`; - const stack = makeNode('stacklayout'); - stack.children = [label]; - label.parent = stack; - return stack; + const loaderData = getRouteApi('/').useLoaderData(); + lastLoaderData = untrack(loaderData); + const label = community.createElement('label'); + community.insert(label, () => `loaded:${(loaderData() as any)?.greeting ?? 'NONE'}`); + return label; }; const indexRoute = createRoute({ @@ -116,37 +76,96 @@ describe('NativeScript rendering pipeline (universal renderer + solid-web-shim)' }); await router.load(); - expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); - const page = makeNode('page'); - let caught: any; - const dispose = universal.render( - (() => - createComponent(RouterContextProvider as any, { - router, - children: () => - createComponent(ErrorBoundary, { - fallback: (err: any) => { - caught = err; - return null as any; - }, - get children() { - return createComponent(HomeComponent, {}); - }, - }), - })) as any, - page, - ); - - // Allow Solid effects to flush - await new Promise((r) => setTimeout(r, 50)); + const { page, dispose, caught } = renderIntoPage(router, () => createComponent(HomeComponent, {})); + await settle(); expect(homeInvocations, 'Home should have rendered exactly once').toBe(1); expect(lastLoaderData).toEqual({ greeting: 'hello' }); - expect(caught, `ErrorBoundary should not have caught anything but got: ${caught?.message ?? caught}`).toBeUndefined(); - expect(page.children.length, 'page should have an inserted view subtree').toBeGreaterThan(0); + expect(caught()).toBeUndefined(); + expect(page.content?.tag).toBe('label'); + expect(page.content?.children[0]?.text).toBe('loaded:hello'); dispose(); }); + + it("renders nested matches through the router's own / (Dynamic, memo, mergeProps from the shim)", async () => { + const rootRoute = createRootRoute(); + + const layoutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/virtual', + component: () => { + const stack = community.createElement('stacklayout'); + community.insert(stack, () => createComponent(Outlet, {})); + return stack; + }, + }); + + const inspectorRoute = createRoute({ + getParentRoute: () => layoutRoute, + path: '/inspector', + loader: () => ({ title: 'Inspector' }), + component: () => { + const data = getRouteApi('/virtual/inspector').useLoaderData(); + const label = community.createElement('label'); + community.insert(label, () => (data() as any).title); + return label; + }, + }); + + const router = createRouter({ + routeTree: rootRoute.addChildren([layoutRoute.addChildren([inspectorRoute])]), + history: createMemoryHistory({ initialEntries: ['/virtual/inspector'] }), + }); + + await router.load(); + + const { page, dispose, caught } = renderIntoPage(router, () => createComponent(Match, { routeId: layoutRoute.id })); + await settle(); + + expect(caught()).toBeUndefined(); + expect(collectTags(page)).toEqual(['stacklayout', 'label']); + const label = page.content!.children.find((c) => c.tag === 'label'); + expect(label?.children[0]?.text).toBe('Inspector'); + + dispose(); + }); +}); + +describe('solid-web-shim', () => { + it('Dynamic creates intrinsic elements through the NativeScript renderer', () => { + const host = new FakeNode('page'); + const dispose = community.render(() => createComponent(shim.Dynamic, { component: 'label', text: 'hi' }), host); + flush(); + + expect(host.content?.tag).toBe('label'); + expect(host.content?.attrs.text).toBe('hi'); + dispose(); + }); + + it('Dynamic renders function components and nothing for an unset component', () => { + const host = new FakeNode('page'); + const Comp = (props: { text: string }) => { + const node = community.createElement('button'); + community.setProp(node, 'text', props.text); + return node; + }; + const dispose = community.render(() => [createComponent(shim.Dynamic, { component: Comp, text: 'tap' }), createComponent(shim.Dynamic, { component: undefined })], host); + flush(); + + expect(collectTags(host)).toEqual(['button']); + expect(host.content?.attrs.text).toBe('tap'); + dispose(); + }); + + it('DOM templates fail loudly when instantiated instead of yielding an undefined node', () => { + const create = shim.template('

Not Found'); + expect(() => create()).toThrow(/

DOM fallback cannot render in NativeScript/); + }); + + it('reports a client environment', () => { + expect(shim.isServer).toBe(false); + }); }); diff --git a/packages/tanstack-router/test/page-renderer.test.ts b/packages/tanstack-router/test/page-renderer.test.ts index 835beda..0e0eaa8 100644 --- a/packages/tanstack-router/test/page-renderer.test.ts +++ b/packages/tanstack-router/test/page-renderer.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -const renderSpy = vi.fn<(fn: () => unknown, target: unknown) => () => void>(); +const insertSpy = vi.fn<(parent: unknown, accessor: unknown) => void>(); vi.mock('@nativescript-community/solid-js', () => ({ - render: (...args: unknown[]) => renderSpy(...(args as [() => unknown, unknown])), + insert: (...args: unknown[]) => insertSpy(...(args as [unknown, unknown])), })); vi.mock('@tanstack/solid-router', () => ({ @@ -31,7 +31,7 @@ class FakePage { describe('renderPage', () => { beforeEach(() => { - renderSpy.mockReset(); + insertSpy.mockReset(); vi.useFakeTimers(); (globalThis as any).document = { @@ -40,9 +40,6 @@ describe('renderPage', () => { }); it('re-mounts on navigatedTo even when router path is stale/pending after native back', () => { - const disposeSpy = vi.fn(); - renderSpy.mockReturnValue(disposeSpy); - const onNativeBack = vi.fn(); const onVisiblePathChange = vi.fn(); @@ -57,10 +54,9 @@ describe('renderPage', () => { const page = renderPage(router, (() => null) as any, '/', onNativeBack, onVisiblePathChange, true) as FakePage; - expect(renderSpy).toHaveBeenCalledTimes(1); + expect(insertSpy).toHaveBeenCalledTimes(1); page.emit('navigatingFrom', { isBackNavigation: true }); - expect(disposeSpy).toHaveBeenCalledTimes(1); vi.runAllTimers(); expect(onNativeBack).toHaveBeenCalledWith('/'); @@ -70,6 +66,16 @@ describe('renderPage', () => { page.emit('navigatedTo'); expect(onVisiblePathChange).toHaveBeenCalledWith('/'); - expect(renderSpy).toHaveBeenCalledTimes(2); + expect(insertSpy).toHaveBeenCalledTimes(2); + }); + + it('keeps the mounted tree when a page returns from the backstack after a forward push', () => { + const page = renderPage({ state: { location: { pathname: '/' } } } as any, (() => null) as any, '/') as FakePage; + expect(insertSpy).toHaveBeenCalledTimes(1); + + page.emit('navigatingFrom', { isBackNavigation: false }); + page.emit('navigatedTo'); + + expect(insertSpy).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/tanstack-router/test/render-eager-children-bug.test.ts b/packages/tanstack-router/test/render-eager-children-bug.test.ts deleted file mode 100644 index 70c0937..0000000 --- a/packages/tanstack-router/test/render-eager-children-bug.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -// @vitest-environment jsdom -// -// In the eager case, `jsx(Inner, {})` is evaluated when the props object -// literal is constructed β€” BEFORE the Provider sets its context. Components -// rendered inside `Inner` therefore can't find the context, so `useRouter()` -// returns null, `useMatch` throws, and the page goes blank. -// - -import { describe, it, expect, beforeAll } from 'vitest'; -import { createComponent, ErrorBoundary } from 'solid-js'; -import { render } from 'solid-js/web'; -import { createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi, RouterContextProvider, useRouter } from '@tanstack/solid-router'; - -// Mimic the shim's jsx exactly (the one shipped in solid-js-jsx-runtime-shim.js -// and @nativescript/vite/shims/solid-jsx-runtime.js). The published -// `solid/index.mjs` ultimately resolves `import { jsx } from 'solid-js/jsx-runtime'` -// to one of these shims at consumer-build time. -function shimJsx(type: any, props?: any): any { - if (typeof type === 'function') { - return createComponent(type, props || {}); - } - return { type, props: props || {} }; -} - -beforeAll(() => { - process.env.NODE_ENV = 'development'; -}); - -describe('PageRenderer JSX β†’ router context propagation', () => { - it('finds the active match when shimJsx eagerly evaluates nested children', async () => { - const rootRoute = createRootRoute(); - - let homeRendered = false; - let lastLoaderData: unknown = 'NOT_READ'; - let routerInsideHome: unknown; - - const Home = () => { - homeRendered = true; - // Snapshot the resolved router so we can assert context wiring - routerInsideHome = useRouter(); - const route = getRouteApi('/'); - const data = route.useLoaderData(); - lastLoaderData = data(); - return document.createElement('div'); - }; - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: () => ({ greeting: 'hi' }), - component: Home, - }); - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }); - - await router.load(); - expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); - - const host = document.createElement('div'); - let caught: any; - - // Mirror exactly what the bundled `renderPage` produces: - // jsx(RouterContextProvider, { - // router, - // children: () => jsx(ErrorBoundary, { - // fallback: ..., - // children: jsx(SafeRouteView, {}) // ← eager, NO getter - // }) - // }) - const SafeRouteView = () => createComponent(Home, {}); - const dispose = render( - () => - shimJsx(RouterContextProvider, { - router, - children: () => - shimJsx(ErrorBoundary, { - fallback: (err: any) => { - caught = err; - return null; - }, - children: shimJsx(SafeRouteView, {}), - }), - }), - host, - ); - - await new Promise((r) => setTimeout(r, 50)); - - expect(caught, `ErrorBoundary should not have caught anything but got: ${caught?.message ?? caught}`).toBeUndefined(); - expect(homeRendered, 'Home should have been invoked').toBe(true); - expect(routerInsideHome, 'useRouter() inside Home should resolve to the provided router').toBe(router); - expect(lastLoaderData).toEqual({ greeting: 'hi' }); - - dispose(); - }); -}); diff --git a/packages/tanstack-router/test/route-returns-array.test.ts b/packages/tanstack-router/test/route-returns-array.test.ts deleted file mode 100644 index e08462f..0000000 --- a/packages/tanstack-router/test/route-returns-array.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -// @vitest-environment jsdom - -import { describe, it, expect, beforeAll, vi } from 'vitest'; -import { createRenderer } from 'solid-js/universal'; -import { ErrorBoundary, createComponent } from 'solid-js'; -import { RouterContextProvider, createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi } from '@tanstack/solid-router'; - -vi.mock('solid-js/web', async () => { - return await import('../solid-web-shim.js'); -}); - -beforeAll(() => { - process.env.NODE_ENV = 'development'; -}); - -type FakeNode = { - tag: string; - text?: string; - attrs: Record; - children: Array; - parent?: FakeNode; -}; - -function makeNode(tag: string): FakeNode { - return { tag, attrs: {}, children: [] }; -} - -const universal = createRenderer({ - createElement(tag) { - return makeNode(tag); - }, - createTextNode(value) { - const n = makeNode('#text'); - n.text = value; - return n; - }, - isTextNode(node) { - return node.tag === '#text'; - }, - replaceText(node, value) { - node.text = value; - }, - setProperty(node, name, value) { - node.attrs[name] = value; - }, - insertNode(parent, node, anchor) { - if (anchor) { - const idx = parent.children.indexOf(anchor); - parent.children.splice(idx, 0, node); - } else { - parent.children.push(node); - } - node.parent = parent; - }, - removeNode(parent, node) { - const idx = parent.children.indexOf(node); - if (idx >= 0) parent.children.splice(idx, 1); - node.parent = undefined; - }, - getParentNode(node) { - return node.parent as FakeNode; - }, - getFirstChild(node) { - return node.children[0] as FakeNode; - }, - getNextSibling(node) { - if (!node.parent) return undefined as unknown as FakeNode; - const idx = node.parent.children.indexOf(node); - return node.parent.children[idx + 1] as FakeNode; - }, -}); - -// Mimic exactly what tsup's auto-jsx-runtime emits for our PageRenderer.tsx -function shimJsx(type: any, props?: any): any { - if (typeof type === 'function') { - return createComponent(type, props || {}); - } - return { type, props: props || {} }; -} - -describe('Page subtree where the route component returns a fragment (array)', () => { - it('inserts both fragment children into the page', async () => { - const rootRoute = createRootRoute(); - - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: () => ({ greeting: 'hi' }), - // Mimic babel-preset-solid output for `<>`: - // returns an array of two universal nodes. - component: () => { - const route = getRouteApi('/'); - const data = route.useLoaderData(); - // touch loaderData so useMatch wires up - void data(); - const ab = universal.createElement('actionbar'); - universal.setProp(ab, 'title', 'TanStack Router', undefined); - const sv = universal.createElement('scrollview'); - return [ab, sv] as any; - }, - }); - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }); - - await router.load(); - expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); - - const page = makeNode('page'); - let caught: any; - - const Comp = (indexRoute as any).options.component; - const SafeRouteView = () => createComponent(Comp, {}); - - // Mirror PageRenderer.tsx's exact JSX shape (eager children via shimJsx) - const dispose = universal.render( - (() => - shimJsx(RouterContextProvider, { - router, - children: () => - shimJsx(ErrorBoundary, { - fallback: (err: any) => { - caught = err; - return null; - }, - children: shimJsx(SafeRouteView, {}), - }), - })) as any, - page, - ); - - await new Promise((r) => setTimeout(r, 50)); - - expect(caught, `ErrorBoundary should not have caught anything but got: ${caught?.message ?? caught}`).toBeUndefined(); - expect(page.children.length, 'page must have inserted children').toBeGreaterThan(0); - // The page should contain both of Home's fragment children - const tags = collectTagsRecursively(page); - expect(tags).toContain('actionbar'); - expect(tags).toContain('scrollview'); - - dispose(); - }); -}); - -function collectTagsRecursively(node: FakeNode, out: Array = []): Array { - for (const child of node.children) { - out.push(child.tag); - collectTagsRecursively(child, out); - } - return out; -} diff --git a/packages/tanstack-router/test/router-provider.test.ts b/packages/tanstack-router/test/router-provider.test.ts new file mode 100644 index 0000000..619cb7e --- /dev/null +++ b/packages/tanstack-router/test/router-provider.test.ts @@ -0,0 +1,137 @@ +// @vitest-environment jsdom +// +// Mounts NativeScriptRouterProvider against a fake Frame to check the Solid +// lifecycle end to end: initial load after settle, router-driven Frame pushes +// and pops, and teardown. + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { createComponent } from 'solid-js'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter } from '@tanstack/solid-router'; +import { FakeNode } from './support/fake-native-renderer'; + +vi.mock('@nativescript-community/solid-js', async () => { + const { createFakeCommunitySolid } = await import('./support/fake-native-renderer'); + return createFakeCommunitySolid(); +}); + +vi.mock('@solidjs/web', async () => { + return await import('../solid-web-shim.js'); +}); + +vi.mock('@nativescript/core', () => ({ + Application: { android: undefined }, + isAndroid: false, + Color: class {}, + Utils: {}, +})); + +vi.mock('@nativescript/core/abortcontroller', () => ({ + AbortController: globalThis.AbortController, + AbortSignal: globalThis.AbortSignal, +})); + +const community = await import('@nativescript-community/solid-js'); +const { NativeScriptRouterProvider } = await import('../src/NativeScriptRouterProvider'); + +class FakeFrame extends FakeNode { + currentPage?: FakeNode; + backStack: FakeNode[] = []; + navigations: Array<{ animated?: boolean; backstackVisible?: boolean }> = []; + + navigate(entry: { create: () => FakeNode; animated?: boolean; backstackVisible?: boolean }) { + this.navigations.push({ animated: entry.animated, backstackVisible: entry.backstackVisible }); + const page = entry.create(); + if (this.currentPage && entry.backstackVisible !== false) this.backStack.push(this.currentPage); + this.currentPage = page; + page.emit('navigatedTo', { isBackNavigation: false }); + } + + canGoBack() { + return this.backStack.length > 0; + } + + goBack() { + const page = this.backStack.pop(); + if (!page) return; + this.currentPage?.emit('navigatingFrom', { isBackNavigation: true }); + this.currentPage = page; + page.emit('navigatedTo', { isBackNavigation: true }); + } +} + +const originalCreateElement = document.createElement; + +beforeAll(() => { + (document as any).createElement = (tag: string) => (tag.toLowerCase() === 'frame' ? new FakeFrame('frame') : new FakeNode(tag.toLowerCase())); +}); + +afterAll(() => { + (document as any).createElement = originalCreateElement; +}); + +const settle = () => new Promise((r) => setTimeout(r, 30)); + +function label(text: string) { + return () => { + const node = community.createElement('label'); + community.setProp(node, 'text', text); + return node; + }; +} + +function createTestRouter() { + const rootRoute = createRootRoute(); + const routeTree = rootRoute.addChildren([createRoute({ getParentRoute: () => rootRoute, path: '/', component: label('home') }), createRoute({ getParentRoute: () => rootRoute, path: '/about', component: label('about') })]); + return createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/'] }), + }); +} + +describe('NativeScriptRouterProvider', () => { + it('loads the initial route and pushes / pops Frame pages as the router navigates', async () => { + const router = createTestRouter(); + const host = new FakeNode('page'); + const dispose = community.render(() => createComponent(NativeScriptRouterProvider, { router }), host); + + const frame = host.content as unknown as FakeFrame; + expect(frame).toBeInstanceOf(FakeFrame); + expect(frame.attrs.actionBarVisibility).toBe('never'); + + await settle(); + expect(router.state.status).toBe('idle'); + expect(frame.navigations).toHaveLength(1); + expect(frame.navigations[0].animated).toBe(false); + expect(frame.currentPage?.content?.attrs.text).toBe('home'); + + await router.navigate({ to: '/about' }); + await settle(); + expect(frame.navigations).toHaveLength(2); + expect(frame.navigations[1]).toEqual({ animated: true, backstackVisible: true }); + expect(frame.currentPage?.content?.attrs.text).toBe('about'); + expect(frame.backStack).toHaveLength(1); + + router.history.back(); + await settle(); + expect(router.state.location.pathname).toBe('/'); + expect(frame.backStack).toHaveLength(0); + expect(frame.currentPage?.content?.attrs.text).toBe('home'); + + dispose(); + }); + + it('stops reacting to router navigation once disposed', async () => { + const router = createTestRouter(); + const host = new FakeNode('page'); + const dispose = community.render(() => createComponent(NativeScriptRouterProvider, { router }), host); + const frame = host.content as unknown as FakeFrame; + await settle(); + expect(frame.navigations).toHaveLength(1); + + dispose(); + router.history.push('/about'); + await settle(); + + expect(frame.navigations).toHaveLength(1); + }); +}); diff --git a/packages/tanstack-router/test/router-render.test.ts b/packages/tanstack-router/test/router-render.test.ts index 2459cd5..a482135 100644 --- a/packages/tanstack-router/test/router-render.test.ts +++ b/packages/tanstack-router/test/router-render.test.ts @@ -1,13 +1,12 @@ // @vitest-environment jsdom import { describe, it, expect, beforeAll } from 'vitest'; import { createMemoryHistory, createRootRoute, createRoute, createRouter, getRouteApi, RouterContextProvider } from '@tanstack/solid-router'; -import { createComponent, createRoot, ErrorBoundary } from 'solid-js'; -import { render } from 'solid-js/web'; +import { createComponent, Errored, untrack } from 'solid-js'; +import { render } from '@solidjs/web'; -// Reproduces white-screen scenario: -// 1. createRouter + load() (matches reach `success`, status stays `pending`) -// 2. Render a page subtree containing a route component that calls `useLoaderData` -// 3. useMatch's `createEffect` should find the match and NOT throw "Could not find an active match" +// Baseline on the stock DOM renderer: a route component calling `useLoaderData` +// inside a RouterContextProvider subtree must find its match after router.load() +// (no "Could not find an active match"). describe('TanStack Router render path', () => { beforeAll(() => { @@ -29,7 +28,7 @@ describe('TanStack Router render path', () => { homeRendered = true; const route = getRouteApi('/'); const data = route.useLoaderData(); - homeLoaderDataAtRender = data(); + homeLoaderDataAtRender = untrack(data); // Return a real DOM node so render() doesn't bail return document.createElement('div'); }, @@ -50,40 +49,35 @@ describe('TanStack Router render path', () => { expect(indexMatch, 'index match present after load').toBeTruthy(); expect(indexMatch!.status).toBe('success'); - // Render exactly the way the NS PageRenderer does + // Same tree shape as the NS PageRenderer const host = document.createElement('div'); let caughtError: any; - const dispose = createRoot((dispose) => { - const root = render( - () => - createComponent(RouterContextProvider as any, { - router, - children: () => - createComponent(ErrorBoundary, { - fallback: (err: any) => { - caughtError = err; - return null as any; - }, - get children() { - const Comp = (indexRoute as any).options.component; - return createComponent(Comp, {}); - }, - }), - }), - host, - ); - return () => { - root(); - dispose(); - }; - }); + const dispose = render( + () => + createComponent(RouterContextProvider as any, { + router, + children: () => + createComponent(Errored, { + fallback: (err: () => unknown) => { + caughtError = untrack(err); + return null; + }, + get children() { + const Comp = (indexRoute as any).options.component; + return createComponent(Comp, {}); + }, + }), + }), + host, + ); // Allow Solid effects to flush await new Promise((r) => setTimeout(r, 50)); expect(homeRendered, 'Home component should have been invoked').toBe(true); expect(homeLoaderDataAtRender).toEqual({ greeting: 'hello' }); - expect(caughtError, `ErrorBoundary should not have caught anything but got: ${caughtError?.message ?? caughtError}`).toBeUndefined(); + expect(caughtError, `Errored should not have caught anything but got: ${caughtError?.message ?? caughtError}`).toBeUndefined(); + expect(host.children.length).toBe(1); dispose(); }); diff --git a/packages/tanstack-router/test/router.test.ts b/packages/tanstack-router/test/router.test.ts new file mode 100644 index 0000000..ac0c238 --- /dev/null +++ b/packages/tanstack-router/test/router.test.ts @@ -0,0 +1,32 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createRootRoute, createRoute } from '@tanstack/solid-router'; +import { createDetachedNativeScriptRouter, createNativeScriptRouter } from '../src/router'; + +vi.mock('@nativescript/core/abortcontroller', () => ({ + AbortController: globalThis.AbortController, + AbortSignal: globalThis.AbortSignal, +})); + +function routeTree() { + const rootRoute = createRootRoute(); + return rootRoute.addChildren([createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => null })]); +} + +describe('createNativeScriptRouter', () => { + afterEach(() => { + delete (globalThis as any).__ns_router; + }); + + it('registers the app router for HMR', () => { + const router = createNativeScriptRouter({ routeTree: routeTree() }); + expect((globalThis as any).__ns_router).toBe(router); + }); + + it('keeps the app router registered when a detached (modal) router is created', () => { + const app = createNativeScriptRouter({ routeTree: routeTree() }); + const modal = createDetachedNativeScriptRouter({ routeTree: routeTree(), initialPath: '/' }); + expect(modal).not.toBe(app); + expect((globalThis as any).__ns_router).toBe(app); + }); +}); diff --git a/packages/tanstack-router/test/solid-hmr-remount.test.ts b/packages/tanstack-router/test/solid-hmr-remount.test.ts index fa4cb77..36befe9 100644 --- a/packages/tanstack-router/test/solid-hmr-remount.test.ts +++ b/packages/tanstack-router/test/solid-hmr-remount.test.ts @@ -125,14 +125,10 @@ describe('subscribeSolidHmrRemount', () => { it('passes the freshly-patched component when a component file change propagates to a route file boundary', () => { // Mirrors the production HMR pipeline: editing - // `/src/components/home.tsx` triggers the HMR client's BFS pass-2, - // which discovers `/src/routes/index.tsx` (the route file that - // imports home.tsx) as a boundary. The HMR client re-imports the - // route file and patches `route.options.component` to the freshly- - // imported reference. The listener then reads that fresh reference - // and passes it through to the page remount β€” keeping the visible - // tree in sync with the edited source even when solid-refresh's - // proxy patch does not propagate to the page-level renderEffect. + // `/src/components/home.tsx` makes the HMR client discover + // `/src/routes/index.tsx` (the route file that imports home.tsx) as a + // boundary, re-import it and patch `route.options.component` with the + // fresh export. The listener passes that reference to the page remount. const home = new FakePage('/'); const frame = new FakeFrame(); frame.currentPage = home; diff --git a/packages/tanstack-router/test/start-transition.test.ts b/packages/tanstack-router/test/start-transition.test.ts new file mode 100644 index 0000000..b004f20 --- /dev/null +++ b/packages/tanstack-router/test/start-transition.test.ts @@ -0,0 +1,65 @@ +// @vitest-environment jsdom +// +// NativeScript never mounts solid-router's , so the provider +// installs its own transition hook. With it, a load must still settle the router +// the way does on the web: matches committed, status back to +// idle, resolvedLocation set, onResolved / onRendered emitted. + +import { describe, it, expect } from 'vitest'; +import { createMemoryHistory, createRootRoute, createRoute, createRouter } from '@tanstack/solid-router'; +import { installNativeScriptStartTransition } from '../src/start-transition'; + +function createTestRouter() { + const rootRoute = createRootRoute(); + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: async () => { + await new Promise((r) => setTimeout(r, 5)); + return { ok: true }; + }, + component: () => null, + }); + const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', + component: () => null, + }); + const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }); + installNativeScriptStartTransition(router); + return router; +} + +describe('installNativeScriptStartTransition', () => { + it('settles the initial load: idle status, resolved location, onResolved + onRendered', async () => { + const router = createTestRouter(); + const events: string[] = []; + router.subscribe('onResolved', () => events.push('onResolved')); + router.subscribe('onRendered', () => events.push('onRendered')); + + expect(router.state.status).toBe('idle'); + + await router.load(); + + expect(router.state.status).toBe('idle'); + expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); + expect(router.state.resolvedLocation?.pathname).toBe('/'); + expect(events).toEqual(['onResolved', 'onRendered']); + }); + + it('commits a follow-up navigation', async () => { + const router = createTestRouter(); + await router.load(); + + await router.navigate({ to: '/about' }); + await router.load(); + + expect(router.state.location.pathname).toBe('/about'); + expect(router.state.matches.at(-1)?.routeId).toBe('/about'); + expect(router.state.status).toBe('idle'); + expect(router.state.resolvedLocation?.pathname).toBe('/about'); + }); +}); diff --git a/packages/tanstack-router/test/support/fake-native-renderer.ts b/packages/tanstack-router/test/support/fake-native-renderer.ts new file mode 100644 index 0000000..63480b4 --- /dev/null +++ b/packages/tanstack-router/test/support/fake-native-renderer.ts @@ -0,0 +1,122 @@ +import { createRenderer } from '@solidjs/universal'; +import { Errored, For, Loading, Match, Repeat, Reveal, Show, Switch } from 'solid-js'; + +type Listener = (args?: any) => void; + +/** + * Minimal stand-in for a DOMiNATIVE element: enough DOM-ish surface for the + * universal renderer and PageRenderer, plus NativeScript Page's + * `actionBar` / `content` slots. + */ +export class FakeNode { + children: FakeNode[] = []; + parent?: FakeNode; + attrs: Record = {}; + text?: string; + actionBar?: FakeNode | null; + content?: FakeNode | null; + private listeners = new Map(); + + constructor(public tag: string) {} + + get firstChild(): FakeNode | undefined { + return this.children[0]; + } + + get nextSibling(): FakeNode | undefined { + if (!this.parent) return undefined; + return this.parent.children[this.parent.children.indexOf(this) + 1]; + } + + insertBefore(node: FakeNode, anchor?: FakeNode | null) { + node.parent?.removeChild(node); + const idx = anchor ? this.children.indexOf(anchor) : -1; + if (idx >= 0) this.children.splice(idx, 0, node); + else this.children.push(node); + node.parent = this; + if (this.tag === 'page' && node.tag !== '#text') { + if (node.tag === 'actionbar') this.actionBar = node; + else this.content = node; + } + } + + removeChild(node: FakeNode) { + const idx = this.children.indexOf(node); + if (idx >= 0) this.children.splice(idx, 1); + node.parent = undefined; + } + + setAttribute(name: string, value: unknown) { + this.attrs[name] = value; + } + + removeAttribute(name: string) { + delete this.attrs[name]; + } + + on(event: string, fn: Listener) { + this.listeners.set(event, [...(this.listeners.get(event) ?? []), fn]); + } + + addEventListener(event: string, fn: Listener) { + this.on(event, fn); + } + + removeEventListener(event: string, fn: Listener) { + this.listeners.set( + event, + (this.listeners.get(event) ?? []).filter((l) => l !== fn), + ); + } + + emit(event: string, args?: any) { + for (const fn of this.listeners.get(event) ?? []) fn(args); + } +} + +export function collectTags(node: FakeNode, out: string[] = []): string[] { + for (const child of node.children) { + if (child.tag !== '#text') out.push(child.tag); + collectTags(child, out); + } + return out; +} + +export function createFakeNativeRenderer() { + return createRenderer({ + createElement: (tag) => new FakeNode(tag), + createTextNode(value) { + const node = new FakeNode('#text'); + node.text = value; + return node; + }, + isTextNode: (node) => node.tag === '#text', + replaceText(node, value) { + node.text = value; + }, + setProperty(node, name, value) { + node.attrs[name] = value; + }, + insertNode: (parent, node, anchor) => parent.insertBefore(node, anchor), + removeNode: (parent, node) => parent.removeChild(node), + getParentNode: (node) => node.parent as FakeNode, + getFirstChild: (node) => node.firstChild as FakeNode, + getNextSibling: (node) => node.nextSibling as FakeNode, + }); +} + +/** Module shape of `@nativescript-community/solid-js`, backed by FakeNode. */ +export function createFakeCommunitySolid() { + const renderer = createFakeNativeRenderer(); + return { + ...renderer, + For, + Repeat, + Show, + Switch, + Match, + Loading, + Reveal, + Errored, + }; +} diff --git a/packages/tanstack-router/test/transitioner-equivalent.test.ts b/packages/tanstack-router/test/transitioner-equivalent.test.ts deleted file mode 100644 index 0e685dd..0000000 --- a/packages/tanstack-router/test/transitioner-equivalent.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -// @vitest-environment jsdom -// -// Verifies that the @tanstack/solid-router 1.168+ signal-based router state -// (`router.stores.{isLoading,hasPending,status,resolvedLocation}`) settles -// correctly under the same accumulator-style createEffect we use in -// `NativeScriptRouterProvider` (modeled after solid-router's internal -// ``). This is a stand-in for the real provider β€” we can't -// mount the full NS Frame in a node test β€” but it covers the failure mode we -// hit shipping 0.1.0: the manual `.set('idle')` hack against the new signal -// store left the router stuck at `status === 'pending'` after `router.load()`. - -import { describe, it, expect, beforeAll, vi } from 'vitest'; -import { batch, createEffect, createMemo, createRoot } from 'solid-js'; -import { createMemoryHistory, createRootRoute, createRoute, createRouter } from '@tanstack/solid-router'; - -vi.mock('solid-js/web', async () => { - return await import('../solid-web-shim.js'); -}); - -beforeAll(() => { - process.env.NODE_ENV = 'development'; -}); - -describe('Transitioner-equivalent reactive effect', () => { - it('flips status from pending β†’ idle when isLoading + hasPending settle after router.load()', async () => { - const rootRoute = createRootRoute(); - const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - loader: async () => { - // Force a microtask boundary so isLoading is observably true at some point - await new Promise((r) => setTimeout(r, 5)); - return { ok: true }; - }, - component: () => null as any, - }); - - const router = createRouter({ - routeTree: rootRoute.addChildren([indexRoute]), - history: createMemoryHistory({ initialEntries: ['/'] }), - }); - - // Same as `NativeScriptRouterProvider`: synchronous startTransition because - // we don't render in NS. - router.startTransition = (fn: () => void) => fn(); - - let observedSettlements = 0; - const cleanup = createRoot((dispose) => { - const isAnyPending = createMemo(() => { - const stores = (router as any).stores; - if (!stores) return false; - return Boolean(stores.isLoading?.get?.() ?? false) || Boolean(stores.hasPending?.get?.() ?? false); - }); - - createEffect((prev: boolean = false) => { - const cur = isAnyPending(); - if (prev && !cur) { - observedSettlements++; - const stores = (router as any).stores; - batch(() => { - stores.status?.set?.('idle'); - if (stores.resolvedLocation && stores.location) { - stores.resolvedLocation.set(stores.location.get()); - } - }); - } - return cur; - }); - - return dispose; - }); - - // Sanity: before load, status starts at 'idle' (router default initial - // state) and there's nothing pending. - expect(router.state.status).toBe('idle'); - - await router.load(); - // Allow the createEffect to flush after the load resolves - await new Promise((r) => setTimeout(r, 30)); - - expect(observedSettlements, 'effect should observe exactly one pendingβ†’idle transition for the initial load').toBe(1); - expect(router.state.status).toBe('idle'); - expect(router.state.matches.length).toBeGreaterThan(0); - expect(router.state.matches.find((m) => m.routeId === '/')?.status).toBe('success'); - expect(router.state.resolvedLocation?.pathname).toBe('/'); - - cleanup(); - }); -}); diff --git a/packages/tanstack-router/tsconfig.json b/packages/tanstack-router/tsconfig.json index 11da63f..f90e38e 100644 --- a/packages/tanstack-router/tsconfig.json +++ b/packages/tanstack-router/tsconfig.json @@ -7,7 +7,6 @@ "moduleResolution": "bundler", "lib": ["ESNext", "DOM"], "jsx": "preserve", - "jsxImportSource": "solid-js", "allowJs": true, "types": ["node", "@nativescript/core"], "allowSyntheticDefaultImports": true, diff --git a/packages/tanstack-router/tsup.config.ts b/packages/tanstack-router/tsup.config.ts index dbc761f..6b1656f 100644 --- a/packages/tanstack-router/tsup.config.ts +++ b/packages/tanstack-router/tsup.config.ts @@ -13,11 +13,7 @@ export default defineConfig({ clean: false, target: 'es2018', outDir: 'dist/packages/tanstack-router', - external: ['@tanstack/solid-router', '@tanstack/react-router', '@tanstack/history', '@nativescript/core', '@nativescript/core/abortcontroller', '@nativescript-community/solid-js', '@nativescript-community/react', 'solid-js', 'solid-js/web', 'solid-js/jsx-runtime', 'react', 'react-dom', 'react/jsx-runtime', 'react-reconciler'], - esbuildOptions(options) { - options.jsx = 'automatic'; - options.jsxImportSource = 'solid-js'; - }, + external: ['@tanstack/solid-router', '@tanstack/react-router', '@tanstack/history', '@nativescript/core', '@nativescript/core/abortcontroller', '@nativescript-community/solid-js', '@nativescript-community/react', 'solid-js', 'react', 'react-dom', 'react/jsx-runtime', 'react-reconciler'], outExtension({ format }) { return { js: format === 'esm' ? '.mjs' : '.cjs', diff --git a/packages/tanstack-router/vitest.config.ts b/packages/tanstack-router/vitest.config.ts index bf00e47..ecebc25 100644 --- a/packages/tanstack-router/vitest.config.ts +++ b/packages/tanstack-router/vitest.config.ts @@ -2,24 +2,17 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ root: __dirname, - esbuild: { - jsx: 'automatic', - jsxImportSource: 'solid-js', - }, resolve: { - // Force solid-js / solid-router to resolve to their browser/dev builds - // rather than their SSR builds when running tests, even though some specs - // run under the `node` environment. Tests that exercise actual rendering - // also opt into `// @vitest-environment jsdom` per-file. + // Solid 2 packages map the `node` condition to their SSR builds, which render + // once and never update. Resolve the browser builds even for `node` specs; + // rendering specs also opt into `// @vitest-environment jsdom`. conditions: ['development', 'browser', 'import', 'default'], }, ssr: { - // Vitest evaluates test files via Vite's SSR pipeline, which uses SSR - // resolve conditions and pulls solid-js/web's `server.js` build. That - // build throws "Client-only API called on the server side" when - // @tanstack/solid-router internals (CatchBoundary etc.) load. Force - // these packages through Vite's web (non-SSR) transformer instead. - noExternal: ['solid-js', '@tanstack/solid-router', '@tanstack/router-core'], + // Vitest evaluates specs through Vite's SSR pipeline, whose externalized deps + // resolve with Node conditions. Inline the Solid runtime and the router so + // they go through the browser resolution above. + noExternal: ['solid-js', '@solidjs/signals', '@solidjs/web', '@solidjs/universal', '@tanstack/solid-router', '@tanstack/router-core'], }, test: { environment: 'node',