akanjs 3.2.0-rc.9 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (641) hide show
  1. package/ARCHITECTURE.md +41 -38
  2. package/CHANGELOG.md +0 -680
  3. package/CONTRIBUTING.md +3 -0
  4. package/base/base.ts +2 -1
  5. package/client/clientRuntime.ts +1 -0
  6. package/client/cn.ts +2 -2
  7. package/client/csrTypes.ts +2 -0
  8. package/client/frameConfig.ts +1 -0
  9. package/client/index.ts +249 -26
  10. package/client/locale.ts +1 -0
  11. package/client/makePageProto.tsx +12 -85
  12. package/client/nativeThemeColor.ts +51 -0
  13. package/client/route/PageDefinition.ts +11 -3
  14. package/client/route/RouteDefinition.ts +24 -7
  15. package/client/route/RouteGuards.ts +2 -1
  16. package/client/route/RouteHead.ts +4 -1
  17. package/client/route/routeArgs.ts +8 -0
  18. package/client/router.ts +17 -2
  19. package/client/rscNavigation.ts +1 -0
  20. package/client/viewportMeta.ts +86 -6
  21. package/common/CodeTranscript.ts +1 -1
  22. package/common/Logger.ts +4 -2
  23. package/common/PipelinePlanSchema.ts +2 -2
  24. package/common/clientAddress.ts +14 -0
  25. package/common/err.ts +122 -0
  26. package/common/eventStream.ts +71 -19
  27. package/common/facetBarrel.ts +38 -0
  28. package/common/index.ts +7 -0
  29. package/common/isGuardRefusal.ts +14 -0
  30. package/common/loggedFailure.ts +11 -0
  31. package/common/mcpExposure.ts +17 -4
  32. package/common/pipelinePlan.ts +1 -1
  33. package/common/routeConvention.ts +3 -1
  34. package/common/types.ts +18 -1
  35. package/constant/constantRegistry.ts +4 -8
  36. package/constant/crystalize.ts +1 -2
  37. package/constant/getDefault.ts +1 -1
  38. package/constant/immerify.ts +1 -1
  39. package/constant/index.ts +78 -21
  40. package/constant/purify.ts +4 -9
  41. package/constant/serialize.ts +4 -2
  42. package/constant/types.ts +1 -0
  43. package/constant/via.ts +1 -2
  44. package/dictionary/agent.dictionary.ts +12 -0
  45. package/dictionary/base.dictionary.ts +11 -0
  46. package/dictionary/locale.ts +1 -1
  47. package/dictionary/trans.ts +14 -97
  48. package/document/dataLoader.ts +39 -19
  49. package/document/databaseRegistry.ts +2 -1
  50. package/document/documentSchema.ts +1 -0
  51. package/document/filterMeta.ts +4 -1
  52. package/document/into.ts +2 -1
  53. package/document/loaderInfo.ts +2 -1
  54. package/document/noDocumentError.ts +4 -1
  55. package/document/queryEvaluator.ts +1 -1
  56. package/document/types.ts +1 -1
  57. package/fetch/client/fetchClient.ts +83 -269
  58. package/fetch/client/fetchClientTypes.ts +49 -0
  59. package/fetch/client/httpClient.ts +3 -2
  60. package/fetch/client/remoteError.ts +4 -20
  61. package/fetch/client/requestScope.ts +41 -0
  62. package/fetch/client/signalCatalog.ts +131 -0
  63. package/fetch/client/wsClient.ts +82 -6
  64. package/fetch/requestStorage.ts +1 -0
  65. package/package.json +1 -1
  66. package/server/agentHooks.ts +16 -0
  67. package/server/akanApp.ts +110 -1272
  68. package/server/akanOption.ts +30 -3
  69. package/server/akanServer.ts +179 -674
  70. package/server/artifact/builderRpc.ts +14 -6
  71. package/server/artifact/routeSeedIndexStore.ts +4 -2
  72. package/server/assetHeaders.ts +6 -0
  73. package/server/console.ts +6 -4
  74. package/server/decorators.ts +2 -2
  75. package/server/di/diLifecycle.ts +24 -35
  76. package/server/di/predefinedAdaptor.ts +24 -1
  77. package/server/di/resolveHierarchy.ts +19 -6
  78. package/server/di/stageFailedError.ts +10 -0
  79. package/server/di/utils.ts +8 -3
  80. package/server/ed25519Key.ts +31 -15
  81. package/server/flightRowReader.ts +106 -20
  82. package/server/gateway/childSupervisor.ts +328 -0
  83. package/server/gateway/devHostChannel.ts +47 -0
  84. package/server/gateway/gatewayChildren.ts +161 -0
  85. package/server/gateway/gatewayConfig.ts +182 -0
  86. package/server/gateway/gatewayHttpProxy.ts +231 -0
  87. package/server/gateway/gatewayLogging.ts +111 -0
  88. package/server/gateway/gatewayRooms.ts +141 -0
  89. package/server/gateway/gatewayStatus.ts +122 -0
  90. package/server/gateway/gatewayStatusPage.ts +54 -0
  91. package/server/gateway/gatewayWebSocketRelay.ts +149 -0
  92. package/server/gateway/listeningPort.ts +13 -0
  93. package/server/hmr/devHmrController.ts +10 -1
  94. package/server/htmlResultCache.ts +234 -0
  95. package/server/imageOptimizer.ts +4 -1
  96. package/server/index.ts +281 -17
  97. package/server/lifecycle/parentChannel.ts +79 -0
  98. package/server/lifecycle/shutdownManager.ts +6 -3
  99. package/server/lifecycle/startGuard.ts +90 -0
  100. package/server/logging/hubFileSink.ts +1 -0
  101. package/server/logging/logControlSocket.ts +42 -3
  102. package/server/logging/logHub.ts +0 -0
  103. package/server/logging/logStdoutWriter.ts +3 -1
  104. package/server/logging/logStreamRoute.ts +28 -11
  105. package/server/logging/serverLogging.ts +74 -0
  106. package/server/machine/machineToken.ts +10 -3
  107. package/server/mcp/AgentTools.ts +149 -0
  108. package/server/mcp/AgentToolsAccount.ts +26 -0
  109. package/server/mcp/McpApps.ts +32 -2
  110. package/server/mcp/McpDispatcher.ts +44 -30
  111. package/server/mcp/McpPages.ts +34 -12
  112. package/server/mcp/McpRateLimiter.ts +14 -0
  113. package/server/mcp/McpRouter.ts +4 -2
  114. package/server/mcp/McpUiSession.ts +2 -1
  115. package/server/mcp/index.ts +1 -0
  116. package/server/migration/migrationCommand.ts +31 -2
  117. package/server/migration/migrationRunner.ts +36 -1
  118. package/server/nativeFile.ts +39 -12
  119. package/server/nativeSecret.ts +12 -3
  120. package/server/oauth/OAuthClientIdMetadata.ts +2 -2
  121. package/server/ops/migrateJobs.ts +2 -2
  122. package/server/ops/opsCommand.ts +1 -1
  123. package/server/ops/opsRoute.ts +5 -1
  124. package/server/ops/opsToken.ts +3 -1
  125. package/server/remote/RemoteFetch.ts +161 -0
  126. package/server/remote/RemoteMcp.ts +242 -0
  127. package/server/remote/RemoteOAuth.ts +270 -0
  128. package/server/remote/RemoteSource.ts +214 -0
  129. package/server/remote/index.ts +17 -0
  130. package/server/remote/remoteError.ts +19 -0
  131. package/server/resolver/CascadeRunner.ts +20 -8
  132. package/server/resolver/database.resolver.ts +10 -417
  133. package/server/resolver/databaseModelInstance.ts +209 -0
  134. package/server/resolver/invalidSignal.ts +7 -0
  135. package/server/resolver/livePause.ts +34 -0
  136. package/server/resolver/modelFacade.ts +136 -0
  137. package/server/resolver/modelLoaders.ts +84 -0
  138. package/server/resolver/modelSchema.ts +52 -0
  139. package/server/resolver/roomAdmission.ts +68 -0
  140. package/server/resolver/signal.resolver.ts +45 -111
  141. package/server/resolver/sliceCrud.ts +63 -0
  142. package/server/resolver/timedQuery.ts +16 -0
  143. package/server/resolver/websocketOf.ts +2 -1
  144. package/server/routeElementComposer.tsx +45 -6
  145. package/server/routeTreeBuilder.ts +23 -9
  146. package/server/routing/apiRouter.ts +53 -28
  147. package/server/routing/builtinRoutes.ts +194 -0
  148. package/server/routing/localRooms.ts +34 -0
  149. package/server/routing/roomReplay.ts +2 -2
  150. package/server/routing/serverLimits.ts +4 -1
  151. package/server/routing/serverListener.ts +194 -0
  152. package/server/rscClient.tsx +121 -204
  153. package/server/rscClientCache.ts +165 -0
  154. package/server/rscClientChunks.ts +126 -8
  155. package/server/rscClientFetch.ts +3 -1
  156. package/server/rscClientPatch.ts +78 -15
  157. package/server/rscDocumentHead.tsx +177 -0
  158. package/server/rscFlightRenderer.ts +83 -0
  159. package/server/rscFlightStream.ts +259 -0
  160. package/server/rscHostReloads.ts +238 -0
  161. package/server/rscHostRenderStream.ts +297 -0
  162. package/server/rscHostRequests.ts +158 -0
  163. package/server/rscHttp.ts +18 -6
  164. package/server/rscNavigationState.ts +24 -1
  165. package/server/rscPagePrompts.ts +65 -14
  166. package/server/rscPrefetchCache.ts +5 -1
  167. package/server/rscRenderControl.ts +33 -0
  168. package/server/rscRenderFallbacks.ts +299 -0
  169. package/server/rscRenderHandler.ts +439 -0
  170. package/server/rscRenderStats.ts +49 -0
  171. package/server/rscResultCaches.ts +74 -0
  172. package/server/rscRouteDocument.tsx +316 -0
  173. package/server/rscSegmentOutletReference.ts +5 -1
  174. package/server/rscStaticApp.tsx +73 -0
  175. package/server/rscWorker.tsx +112 -1341
  176. package/server/rscWorkerHost.ts +175 -803
  177. package/server/rscWorkerProcess.ts +155 -0
  178. package/server/rscWorkerRecycler.ts +128 -0
  179. package/server/serverConfig.ts +128 -0
  180. package/server/serverMetrics.ts +52 -0
  181. package/server/sitemap.ts +1 -0
  182. package/server/ssrFromRscRenderer.tsx +20 -20
  183. package/server/ssrStaticApp.tsx +243 -0
  184. package/server/webArtifact.ts +86 -0
  185. package/server/webAssetRoutes.ts +84 -0
  186. package/server/webCsrSurface.ts +172 -0
  187. package/server/webDocumentRoute.ts +180 -0
  188. package/server/webRouteContext.ts +232 -0
  189. package/server/webRouter.ts +129 -1165
  190. package/server/webRscRoute.ts +155 -0
  191. package/server/webSiteFiles.ts +139 -0
  192. package/server/webStaticApp.ts +62 -0
  193. package/server/wellKnownRoutes.ts +73 -0
  194. package/service/agent.service.ts +14 -2
  195. package/service/agentAccounts.ts +19 -0
  196. package/service/agentLoop/agentLoop.ts +550 -0
  197. package/service/agentLoop/agentLoopTypes.ts +220 -0
  198. package/service/agentLoop/deltaStream.ts +40 -0
  199. package/service/agentLoop/loopAnswer.ts +67 -0
  200. package/service/agentLoop/loopAsk.ts +44 -0
  201. package/service/agentLoop/loopCompaction.ts +146 -0
  202. package/service/agentLoop/loopRemotes.ts +181 -0
  203. package/service/agentLoop/loopRequest.ts +120 -0
  204. package/service/agentLoop/loopStored.ts +24 -0
  205. package/service/agentLoop/loopToolOutput.ts +54 -0
  206. package/service/agentLoop/loopToolkits.ts +155 -0
  207. package/service/agentLoop/loopTranscript.ts +138 -0
  208. package/{signal → service}/agentMeter.ts +2 -1
  209. package/{signal → service}/agentRelayPolicy.ts +43 -8
  210. package/service/endpointCacheKeys.ts +14 -2
  211. package/service/index.ts +6 -0
  212. package/service/injectInfo.ts +2 -1
  213. package/service/ipcTypes.ts +8 -2
  214. package/service/liveRoomLimit.ts +68 -0
  215. package/service/liveRoomLimitError.ts +16 -0
  216. package/service/liveSyncHub.ts +24 -2
  217. package/service/predefinedAdaptor/agentTools.adaptor.ts +34 -0
  218. package/service/predefinedAdaptor/anthropicLlm.ts +33 -14
  219. package/service/predefinedAdaptor/compress.adaptor.ts +2 -2
  220. package/service/predefinedAdaptor/database.adaptor.ts +62 -19
  221. package/service/predefinedAdaptor/index.ts +1 -0
  222. package/service/predefinedAdaptor/llm.adaptor.ts +24 -1
  223. package/service/predefinedAdaptor/openaiDialect.ts +72 -23
  224. package/service/predefinedAdaptor/openaiLlm.ts +1 -1
  225. package/service/predefinedAdaptor/role.adaptor.ts +2 -0
  226. package/service/predefinedAdaptor/solidPubsub.adaptor.ts +35 -2
  227. package/service/predefinedAdaptor/solidQueue.adaptor.ts +2 -2
  228. package/service/predefinedAdaptor/solidSqlite.ts +6 -3
  229. package/service/predefinedAdaptor/sql/DocumentHydrator.ts +95 -0
  230. package/service/predefinedAdaptor/sql/DocumentRowCodec.ts +192 -0
  231. package/service/predefinedAdaptor/sql/DocumentWriter.ts +298 -0
  232. package/service/predefinedAdaptor/sql/QueryScope.ts +70 -0
  233. package/service/predefinedAdaptor/sql/QueryWriter.ts +200 -0
  234. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +127 -1069
  235. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +357 -0
  236. package/service/predefinedAdaptor/sql/StoredRows.ts +95 -0
  237. package/service/predefinedAdaptor/sql/TransactionScope.ts +14 -7
  238. package/service/predefinedAdaptor/sql/dialect/postgres.ts +1 -1
  239. package/service/predefinedAdaptor/sql/dialect/sqlite.ts +1 -1
  240. package/service/predefinedAdaptor/sql/driver/bunSqlite.ts +20 -9
  241. package/service/predefinedAdaptor/sql/driver/postgres.ts +1 -1
  242. package/service/predefinedAdaptor/sql/types.ts +28 -4
  243. package/service/predefinedAdaptor/sseData.ts +88 -0
  244. package/service/predefinedAdaptor/storage.adaptor.ts +2 -1
  245. package/service/predefinedAdaptor/websocket.adaptor.ts +74 -44
  246. package/service/serviceRegistry.ts +1 -0
  247. package/signal/SignalFailure.ts +35 -0
  248. package/signal/agent.signal.ts +15 -9
  249. package/signal/agentTurnStream.ts +23 -9
  250. package/signal/byIdRead.ts +18 -0
  251. package/signal/carriedClientIps.ts +1 -0
  252. package/signal/endpointCache.ts +61 -6
  253. package/signal/endpointErrorContract.ts +1 -1
  254. package/signal/endpointRateLimit.ts +84 -3
  255. package/signal/index.ts +322 -32
  256. package/signal/mcp/McpDocument.ts +8 -1
  257. package/signal/mcp/mcpProtocol.ts +6 -1
  258. package/signal/mcp/pagePrompt.ts +15 -0
  259. package/signal/middleware.ts +10 -3
  260. package/signal/openapi/openapi.ts +10 -1
  261. package/signal/resolveFieldContext.ts +34 -0
  262. package/signal/serializer/fetch.serializer.ts +22 -15
  263. package/signal/signalContext.ts +15 -42
  264. package/signal/slice.ts +22 -19
  265. package/signal/trace.ts +44 -5
  266. package/signal/types.ts +46 -8
  267. package/store/action.ts +32 -1057
  268. package/store/actionErrorMessage.ts +20 -0
  269. package/store/actionOption.ts +22 -0
  270. package/store/baseSt.ts +1 -0
  271. package/store/formFieldSetters.ts +229 -0
  272. package/store/index.ts +125 -17
  273. package/store/modelActionContext.ts +65 -0
  274. package/store/modelOpenActions.ts +158 -0
  275. package/store/modelWriteActions.ts +240 -0
  276. package/store/modelWriteGuard.ts +3 -12
  277. package/store/openSeq.ts +34 -0
  278. package/store/sliceListActions.ts +370 -0
  279. package/store/sliceLiveActions.ts +140 -0
  280. package/store/stateBuilder.ts +2 -0
  281. package/store/storeInstance.ts +4 -18
  282. package/store/storeRegistry.ts +1 -1
  283. package/test/conformance.ts +25 -5
  284. package/types/base/base.d.ts +2 -1
  285. package/types/client/clientRuntime.d.ts +1 -0
  286. package/types/client/cn.d.ts +2 -2
  287. package/types/client/csrTypes.d.ts +2 -0
  288. package/types/client/frameConfig.d.ts +1 -0
  289. package/types/client/index.d.ts +25 -26
  290. package/types/client/locale.d.ts +1 -0
  291. package/types/client/makePageProto.d.ts +5 -13
  292. package/types/client/nativeThemeColor.d.ts +6 -0
  293. package/types/client/route/PageDefinition.d.ts +5 -2
  294. package/types/client/route/RouteDefinition.d.ts +2 -2
  295. package/types/client/route/routeArgs.d.ts +7 -0
  296. package/types/client/router.d.ts +3 -1
  297. package/types/client/rscNavigation.d.ts +1 -0
  298. package/types/client/viewportMeta.d.ts +5 -2
  299. package/types/common/CodeTranscript.d.ts +1 -1
  300. package/types/common/clientAddress.d.ts +5 -0
  301. package/types/common/err.d.ts +48 -0
  302. package/types/common/eventStream.d.ts +5 -1
  303. package/types/common/facetBarrel.d.ts +4 -0
  304. package/types/common/index.d.ts +6 -3
  305. package/types/common/isGuardRefusal.d.ts +3 -0
  306. package/types/common/loggedFailure.d.ts +2 -0
  307. package/types/common/mcpExposure.d.ts +9 -2
  308. package/types/common/routeConvention.d.ts +2 -0
  309. package/types/common/types.d.ts +18 -1
  310. package/types/constant/constantRegistry.d.ts +3 -1
  311. package/types/constant/crystalize.d.ts +1 -1
  312. package/types/constant/getDefault.d.ts +1 -1
  313. package/types/constant/immerify.d.ts +1 -1
  314. package/types/constant/index.d.ts +21 -21
  315. package/types/constant/purify.d.ts +2 -1
  316. package/types/constant/serialize.d.ts +1 -1
  317. package/types/constant/types.d.ts +1 -0
  318. package/types/dictionary/agent.dictionary.d.ts +1 -1
  319. package/types/dictionary/base.dictionary.d.ts +1 -1
  320. package/types/dictionary/dictionary.d.ts +9 -9
  321. package/types/dictionary/locale.d.ts +1 -1
  322. package/types/dictionary/trans.d.ts +3 -26
  323. package/types/document/dataLoader.d.ts +5 -0
  324. package/types/document/databaseRegistry.d.ts +2 -1
  325. package/types/document/documentSchema.d.ts +1 -0
  326. package/types/document/filterMeta.d.ts +4 -1
  327. package/types/document/into.d.ts +1 -1
  328. package/types/document/loaderInfo.d.ts +2 -1
  329. package/types/document/noDocumentError.d.ts +8 -1
  330. package/types/document/queryEvaluator.d.ts +1 -1
  331. package/types/document/types.d.ts +1 -1
  332. package/types/fetch/client/fetchClient.d.ts +6 -36
  333. package/types/fetch/client/fetchClientTypes.d.ts +40 -0
  334. package/types/fetch/client/httpClient.d.ts +2 -0
  335. package/types/fetch/client/remoteError.d.ts +0 -4
  336. package/types/fetch/client/requestScope.d.ts +11 -0
  337. package/types/fetch/client/signalCatalog.d.ts +25 -0
  338. package/types/fetch/client/wsClient.d.ts +2 -0
  339. package/types/fetch/requestStorage.d.ts +1 -0
  340. package/types/server/agentHooks.d.ts +4 -0
  341. package/types/server/akanApp.d.ts +2 -20
  342. package/types/server/akanOption.d.ts +16 -2
  343. package/types/server/akanServer.d.ts +2 -2
  344. package/types/server/assetHeaders.d.ts +1 -0
  345. package/types/server/console.d.ts +4 -3
  346. package/types/server/di/predefinedAdaptor.d.ts +1 -0
  347. package/types/server/di/stageFailedError.d.ts +5 -0
  348. package/types/server/ed25519Key.d.ts +1 -0
  349. package/types/server/flightRowReader.d.ts +8 -2
  350. package/types/server/gateway/childSupervisor.d.ts +35 -0
  351. package/types/server/gateway/devHostChannel.d.ts +14 -0
  352. package/types/server/gateway/gatewayChildren.d.ts +50 -0
  353. package/types/server/gateway/gatewayConfig.d.ts +82 -0
  354. package/types/server/gateway/gatewayHttpProxy.d.ts +22 -0
  355. package/types/server/gateway/gatewayLogging.d.ts +16 -0
  356. package/types/server/gateway/gatewayRooms.d.ts +25 -0
  357. package/types/server/gateway/gatewayStatus.d.ts +63 -0
  358. package/types/server/gateway/gatewayStatusPage.d.ts +9 -0
  359. package/types/server/gateway/gatewayWebSocketRelay.d.ts +17 -0
  360. package/types/server/gateway/listeningPort.d.ts +5 -0
  361. package/types/server/htmlResultCache.d.ts +51 -0
  362. package/types/server/index.d.ts +19 -17
  363. package/types/server/lifecycle/parentChannel.d.ts +13 -0
  364. package/types/server/lifecycle/startGuard.d.ts +10 -0
  365. package/types/server/logging/logHub.d.ts +5 -1
  366. package/types/server/logging/logStreamRoute.d.ts +2 -0
  367. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  368. package/types/server/logging/serverLogging.d.ts +12 -0
  369. package/types/server/mcp/AgentTools.d.ts +31 -0
  370. package/types/server/mcp/AgentToolsAccount.d.ts +7 -0
  371. package/types/server/mcp/McpApps.d.ts +6 -2
  372. package/types/server/mcp/McpDispatcher.d.ts +10 -1
  373. package/types/server/mcp/McpPages.d.ts +2 -1
  374. package/types/server/mcp/McpRateLimiter.d.ts +3 -0
  375. package/types/server/mcp/index.d.ts +1 -0
  376. package/types/server/migration/migrationCommand.d.ts +1 -1
  377. package/types/server/migration/migrationRunner.d.ts +9 -1
  378. package/types/server/remote/RemoteFetch.d.ts +42 -0
  379. package/types/server/remote/RemoteMcp.d.ts +52 -0
  380. package/types/server/remote/RemoteOAuth.d.ts +58 -0
  381. package/types/server/remote/RemoteSource.d.ts +51 -0
  382. package/types/server/remote/index.d.ts +5 -0
  383. package/types/server/remote/remoteError.d.ts +12 -0
  384. package/types/server/remote.d.ts +1 -0
  385. package/types/server/resolver/CascadeRunner.d.ts +2 -2
  386. package/types/server/resolver/database.resolver.d.ts +2 -2
  387. package/types/server/resolver/databaseModelInstance.d.ts +4 -0
  388. package/types/server/resolver/invalidSignal.d.ts +2 -0
  389. package/types/server/resolver/livePause.d.ts +5 -0
  390. package/types/server/resolver/modelFacade.d.ts +5 -0
  391. package/types/server/resolver/modelLoaders.d.ts +15 -0
  392. package/types/server/resolver/modelSchema.d.ts +6 -0
  393. package/types/server/resolver/roomAdmission.d.ts +7 -0
  394. package/types/server/resolver/signal.resolver.d.ts +1 -1
  395. package/types/server/resolver/sliceCrud.d.ts +8 -0
  396. package/types/server/resolver/timedQuery.d.ts +8 -0
  397. package/types/server/routeElementComposer.d.ts +21 -5
  398. package/types/server/routing/builtinRoutes.d.ts +24 -0
  399. package/types/server/routing/localRooms.d.ts +14 -0
  400. package/types/server/routing/roomReplay.d.ts +2 -2
  401. package/types/server/routing/serverListener.d.ts +31 -0
  402. package/types/server/rscClientCache.d.ts +34 -0
  403. package/types/server/rscClientChunks.d.ts +3 -1
  404. package/types/server/rscClientPatch.d.ts +12 -1
  405. package/types/server/rscDocumentHead.d.ts +33 -0
  406. package/types/server/rscFlightRenderer.d.ts +14 -0
  407. package/types/server/rscFlightStream.d.ts +53 -0
  408. package/types/server/rscHostReloads.d.ts +54 -0
  409. package/types/server/rscHostRenderStream.d.ts +53 -0
  410. package/types/server/rscHostRequests.d.ts +29 -0
  411. package/types/server/rscHttp.d.ts +4 -2
  412. package/types/server/rscNavigationState.d.ts +5 -1
  413. package/types/server/rscPagePrompts.d.ts +13 -0
  414. package/types/server/rscRenderControl.d.ts +12 -0
  415. package/types/server/rscRenderFallbacks.d.ts +41 -0
  416. package/types/server/rscRenderHandler.d.ts +29 -0
  417. package/types/server/rscRenderStats.d.ts +32 -0
  418. package/types/server/rscResultCaches.d.ts +18 -0
  419. package/types/server/rscRouteDocument.d.ts +52 -0
  420. package/types/server/rscStaticApp.d.ts +28 -0
  421. package/types/server/rscWorker.d.ts +1 -3
  422. package/types/server/rscWorkerHost.d.ts +10 -70
  423. package/types/server/rscWorkerProcess.d.ts +31 -0
  424. package/types/server/rscWorkerRecycler.d.ts +22 -0
  425. package/types/server/serverConfig.d.ts +30 -0
  426. package/types/server/serverMetrics.d.ts +11 -0
  427. package/types/server/sitemap.d.ts +1 -0
  428. package/types/server/ssrFromRscRenderer.d.ts +2 -2
  429. package/types/server/ssrStaticApp.d.ts +20 -0
  430. package/types/server/webArtifact.d.ts +7 -0
  431. package/types/server/webAssetRoutes.d.ts +11 -0
  432. package/types/server/webCsrSurface.d.ts +18 -0
  433. package/types/server/webDocumentRoute.d.ts +19 -0
  434. package/types/server/webRouteContext.d.ts +45 -0
  435. package/types/server/webRouter.d.ts +3 -28
  436. package/types/server/webRscRoute.d.ts +24 -0
  437. package/types/server/webSiteFiles.d.ts +12 -0
  438. package/types/server/webStaticApp.d.ts +8 -0
  439. package/types/server/wellKnownRoutes.d.ts +5 -0
  440. package/types/service/agent.service.d.ts +3 -0
  441. package/types/service/agentAccounts.d.ts +8 -0
  442. package/types/service/agentLoop/agentLoop.d.ts +33 -0
  443. package/types/service/agentLoop/agentLoopTypes.d.ts +235 -0
  444. package/types/service/agentLoop/deltaStream.d.ts +3 -0
  445. package/types/service/agentLoop/loopAnswer.d.ts +13 -0
  446. package/types/service/agentLoop/loopAsk.d.ts +12 -0
  447. package/types/service/agentLoop/loopCompaction.d.ts +12 -0
  448. package/types/service/agentLoop/loopRemotes.d.ts +40 -0
  449. package/types/service/agentLoop/loopRequest.d.ts +9 -0
  450. package/types/service/agentLoop/loopStored.d.ts +6 -0
  451. package/types/service/agentLoop/loopToolOutput.d.ts +8 -0
  452. package/types/service/agentLoop/loopToolkits.d.ts +17 -0
  453. package/types/service/agentLoop/loopTranscript.d.ts +13 -0
  454. package/types/{signal → service}/agentMeter.d.ts +1 -1
  455. package/types/{signal → service}/agentRelayPolicy.d.ts +18 -3
  456. package/types/service/index.d.ts +6 -0
  457. package/types/service/injectInfo.d.ts +2 -1
  458. package/types/service/ipcTypes.d.ts +10 -0
  459. package/types/service/liveRoomLimit.d.ts +26 -0
  460. package/types/service/liveRoomLimitError.d.ts +9 -0
  461. package/types/service/predefinedAdaptor/agentTools.adaptor.d.ts +31 -0
  462. package/types/service/predefinedAdaptor/anthropicLlm.d.ts +2 -2
  463. package/types/service/predefinedAdaptor/database.adaptor.d.ts +9 -7
  464. package/types/service/predefinedAdaptor/index.d.ts +1 -0
  465. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +12 -0
  466. package/types/service/predefinedAdaptor/openaiDialect.d.ts +3 -2
  467. package/types/service/predefinedAdaptor/role.adaptor.d.ts +2 -0
  468. package/types/service/predefinedAdaptor/solidPubsub.adaptor.d.ts +3 -0
  469. package/types/service/predefinedAdaptor/solidSqlite.d.ts +1 -1
  470. package/types/service/predefinedAdaptor/sql/DocumentHydrator.d.ts +11 -0
  471. package/types/service/predefinedAdaptor/sql/DocumentRowCodec.d.ts +26 -0
  472. package/types/service/predefinedAdaptor/sql/DocumentWriter.d.ts +25 -0
  473. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +16 -0
  474. package/types/service/predefinedAdaptor/sql/QueryWriter.d.ts +20 -0
  475. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +5 -28
  476. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +22 -0
  477. package/types/service/predefinedAdaptor/sql/StoredRows.d.ts +27 -0
  478. package/types/service/predefinedAdaptor/sql/TransactionScope.d.ts +3 -1
  479. package/types/service/predefinedAdaptor/sql/driver/bunSqlite.d.ts +3 -15
  480. package/types/service/predefinedAdaptor/sql/driver/postgres.d.ts +0 -8
  481. package/types/service/predefinedAdaptor/sql/types.d.ts +27 -4
  482. package/types/service/predefinedAdaptor/sseData.d.ts +13 -0
  483. package/types/service/predefinedAdaptor/websocket.adaptor.d.ts +7 -3
  484. package/types/service/serviceRegistry.d.ts +1 -0
  485. package/types/signal/SignalFailure.d.ts +4 -0
  486. package/types/signal/agentTurnStream.d.ts +3 -0
  487. package/types/signal/byIdRead.d.ts +7 -0
  488. package/types/signal/carriedClientIps.d.ts +4 -0
  489. package/types/signal/endpointRateLimit.d.ts +12 -0
  490. package/types/signal/index.d.ts +32 -32
  491. package/types/signal/mcp/McpDocument.d.ts +2 -0
  492. package/types/signal/mcp/mcpProtocol.d.ts +5 -0
  493. package/types/signal/mcp/pagePrompt.d.ts +13 -0
  494. package/types/signal/resolveFieldContext.d.ts +15 -0
  495. package/types/signal/serializer/fetch.serializer.d.ts +3 -1
  496. package/types/signal/signalContext.d.ts +2 -14
  497. package/types/signal/slice.d.ts +15 -13
  498. package/types/signal/trace.d.ts +12 -1
  499. package/types/signal/types.d.ts +38 -7
  500. package/types/store/action.d.ts +4 -27
  501. package/types/store/actionErrorMessage.d.ts +1 -0
  502. package/types/store/actionOption.d.ts +24 -0
  503. package/types/store/baseSt.d.ts +1 -0
  504. package/types/store/formFieldSetters.d.ts +80 -0
  505. package/types/store/index.d.ts +17 -16
  506. package/types/store/modelActionContext.d.ts +189 -0
  507. package/types/store/modelOpenActions.d.ts +12 -0
  508. package/types/store/modelWriteActions.d.ts +16 -0
  509. package/types/store/modelWriteGuard.d.ts +2 -5
  510. package/types/store/openSeq.d.ts +17 -0
  511. package/types/store/sliceListActions.d.ts +295 -0
  512. package/types/store/sliceLiveActions.d.ts +6 -0
  513. package/types/store/stateBuilder.d.ts +2 -0
  514. package/types/test/conformance.d.ts +3 -1
  515. package/types/ui/Agent/Chat.d.ts +5 -2
  516. package/types/ui/Agent/ChatHeader.d.ts +13 -0
  517. package/types/ui/Agent/ChatPendingCards.d.ts +23 -0
  518. package/types/ui/Agent/ToolRow.d.ts +13 -0
  519. package/types/ui/Field/Choice.d.ts +2 -1
  520. package/types/ui/Field/index.d.ts +1 -1
  521. package/types/ui/Reference/origin.d.ts +1 -0
  522. package/types/ui/UiOverride/UiOverride.d.ts +2 -0
  523. package/types/ui/index.d.ts +2 -1
  524. package/types/ui/overlayLayer.d.ts +8 -2
  525. package/types/ui/recipe/badgeRecipe.d.ts +3 -3
  526. package/types/ui/recipe/buttonRecipe.d.ts +3 -3
  527. package/types/ui/recipe/inputRecipe.d.ts +1 -1
  528. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +4 -0
  529. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +1 -0
  530. package/types/vendor/@akanjs/native/plugins/appearance/src/index.d.ts +9 -0
  531. package/types/vendor/@akanjs/native/plugins/external-view/src/index.d.ts +22 -13
  532. package/types/vendor/@akanjs/native/plugins/single-instance/src/socket.d.ts +15 -2
  533. package/types/vendor/use-agentic/AgentClientTools.d.ts +19 -0
  534. package/types/vendor/use-agentic/Compaction.d.ts +3 -1
  535. package/types/vendor/use-agentic/SessionQuestion.d.ts +26 -0
  536. package/types/vendor/use-agentic/Transcript.d.ts +1 -1
  537. package/types/vendor/use-agentic/failureCode.d.ts +4 -0
  538. package/types/vendor/use-agentic/index.d.ts +1 -0
  539. package/types/vendor/use-agentic/types.d.ts +12 -3
  540. package/types/webkit/CsrGuards.d.ts +3 -0
  541. package/types/webkit/McpAppHost.d.ts +24 -0
  542. package/types/webkit/RouteLevelBoundary.d.ts +17 -0
  543. package/types/webkit/csrRefresh.d.ts +13 -0
  544. package/types/webkit/index.d.ts +3 -0
  545. package/types/webkit/needsBrowser.d.ts +5 -0
  546. package/types/webkit/useCamera.d.ts +1 -1
  547. package/types/webkit/useCsrKeyboard.d.ts +19 -0
  548. package/types/webkit/useCsrLocationState.d.ts +21 -0
  549. package/types/webkit/useCsrNavigation.d.ts +25 -0
  550. package/types/webkit/useCsrRefs.d.ts +33 -0
  551. package/types/webkit/useCsrRenderTrace.d.ts +13 -0
  552. package/types/webkit/useCsrStackLifecycle.d.ts +12 -0
  553. package/types/webkit/useCsrTransitions.d.ts +2 -0
  554. package/types/webkit/useGeoLocation.d.ts +1 -1
  555. package/types/webkit/useHistory.d.ts +2 -3
  556. package/types/webkit/useResolvedFrame.d.ts +38 -0
  557. package/types/webkit/useSyncNavigation.d.ts +22 -0
  558. package/ui/Agent/Bubble.tsx +4 -118
  559. package/ui/Agent/Chat.tsx +402 -235
  560. package/ui/Agent/ChatHeader.tsx +59 -0
  561. package/ui/Agent/ChatPendingCards.tsx +49 -0
  562. package/ui/Agent/ToolRow.tsx +117 -0
  563. package/ui/Agent/fetchRunner.ts +8 -1
  564. package/ui/BottomSheet.tsx +1 -1
  565. package/ui/Data/Item.tsx +2 -2
  566. package/ui/Data/ListContainer.tsx +348 -181
  567. package/ui/Data/useViewModal.ts +10 -4
  568. package/ui/Dialog/LegacyModal.tsx +1 -1
  569. package/ui/Dialog/Modal.tsx +1 -1
  570. package/ui/Field/Choice.tsx +3 -1
  571. package/ui/Load/StreamBoundary.tsx +1 -6
  572. package/ui/Load/View.tsx +2 -1
  573. package/ui/Model/EditModal.tsx +2 -1
  574. package/ui/Popconfirm.tsx +1 -1
  575. package/ui/Reference/origin.ts +1 -0
  576. package/ui/Select.tsx +43 -51
  577. package/ui/Signal/RestApi.tsx +3 -2
  578. package/ui/System/Client.tsx +4 -1
  579. package/ui/UiOverride/UiOverride.tsx +2 -0
  580. package/ui/index.ts +5 -0
  581. package/ui/overlayLayer.ts +25 -2
  582. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +31 -13
  583. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativePlugin.kt +4 -0
  584. package/vendor/@akanjs/native/native/desktop/Cargo.lock +1 -0
  585. package/vendor/@akanjs/native/native/desktop/Cargo.toml +2 -0
  586. package/vendor/@akanjs/native/native/desktop/src/external.rs +240 -114
  587. package/vendor/@akanjs/native/native/desktop/src/json.rs +14 -1
  588. package/vendor/@akanjs/native/native/desktop/src/lib.rs +12 -4
  589. package/vendor/@akanjs/native/native/desktop/src/linux/external.rs +696 -0
  590. package/vendor/@akanjs/native/native/desktop/src/linux/mod.rs +1 -0
  591. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeViewController.swift +6 -1
  592. package/vendor/@akanjs/native/packages/cli/src/lib/native-plugins.ts +5 -3
  593. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +25 -1
  594. package/vendor/@akanjs/native/packages/desktop/src/deeplinks.ts +2 -2
  595. package/vendor/@akanjs/native/packages/desktop/src/host.ts +2 -2
  596. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +8 -3
  597. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +2 -2
  598. package/vendor/@akanjs/native/plugins/appearance/android/AppearancePlugin.kt +13 -0
  599. package/vendor/@akanjs/native/plugins/appearance/ios/AppearancePlugin.swift +27 -0
  600. package/vendor/@akanjs/native/plugins/appearance/native-plugin.json +2 -2
  601. package/vendor/@akanjs/native/plugins/appearance/src/index.ts +8 -1
  602. package/vendor/@akanjs/native/plugins/autostart/src/desktop.ts +2 -1
  603. package/vendor/@akanjs/native/plugins/external-view/native-plugin.json +4 -1
  604. package/vendor/@akanjs/native/plugins/external-view/src/index.ts +22 -13
  605. package/vendor/@akanjs/native/plugins/single-instance/src/socket.ts +113 -24
  606. package/vendor/use-agentic/AgentClientTools.ts +33 -0
  607. package/vendor/use-agentic/AgentSession.ts +35 -73
  608. package/vendor/use-agentic/CHANGELOG.md +0 -43
  609. package/vendor/use-agentic/Compaction.ts +12 -2
  610. package/vendor/use-agentic/SessionQuestion.ts +99 -0
  611. package/vendor/use-agentic/ToolRunner.ts +3 -15
  612. package/vendor/use-agentic/Transcript.ts +8 -5
  613. package/vendor/use-agentic/WIRE.md +28 -9
  614. package/vendor/use-agentic/failureCode.ts +44 -0
  615. package/vendor/use-agentic/httpRunner.ts +22 -8
  616. package/vendor/use-agentic/index.ts +1 -0
  617. package/vendor/use-agentic/types.ts +13 -1
  618. package/webkit/CsrGuards.ts +11 -2
  619. package/webkit/McpAppFetchBridge.ts +3 -1
  620. package/webkit/McpAppHost.ts +122 -0
  621. package/webkit/RenderLayer.tsx +48 -14
  622. package/webkit/RouteLevelBoundary.tsx +37 -0
  623. package/webkit/csrRefresh.ts +33 -0
  624. package/webkit/index.ts +3 -0
  625. package/webkit/lazy.tsx +5 -1
  626. package/webkit/needsBrowser.ts +10 -0
  627. package/webkit/useCamera.tsx +18 -7
  628. package/webkit/useCsrKeyboard.ts +155 -0
  629. package/webkit/useCsrLocationState.ts +58 -0
  630. package/webkit/useCsrNavigation.ts +302 -0
  631. package/webkit/useCsrRefs.ts +52 -0
  632. package/webkit/useCsrRenderTrace.ts +68 -0
  633. package/webkit/useCsrStackLifecycle.ts +120 -0
  634. package/webkit/useCsrTransitions.ts +552 -0
  635. package/webkit/useCsrValues.ts +73 -1235
  636. package/webkit/useGeoLocation.tsx +1 -3
  637. package/webkit/useHistory.ts +2 -2
  638. package/webkit/useLocation.ts +3 -2
  639. package/webkit/useResolvedFrame.ts +116 -0
  640. package/webkit/useSyncNavigation.ts +109 -0
  641. package/vendor/@akanjs/native/CHANGELOG.md +0 -21
@@ -1,18 +1,10 @@
1
1
  "use client";
2
- import { useSpringValue } from "@react-spring/web";
3
- import { useDrag } from "@use-gesture/react";
4
2
  import {
5
3
  type CsrContextType,
6
- router as clientRouter,
7
4
  csrLocation,
8
- Device,
9
5
  debugFrame,
10
- defaultPageState,
11
- getAuthToken,
12
- getPathInfo,
13
6
  Href,
14
7
  type Location,
15
- type LocationState,
16
8
  type NavigationIntent,
17
9
  type PageState,
18
10
  type PageTransition,
@@ -22,1069 +14,36 @@ import {
22
14
  type RouterInstance,
23
15
  type RouteState,
24
16
  type TransitionType,
25
- type UseCsrTransition,
26
17
  } from "akanjs/client";
27
18
  import { isNativeApp, openExternalUrl } from "akanjs/client/native";
28
- import { clamp, parseAkanI18nEnv, parseBasePaths } from "akanjs/common";
29
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
30
- import { CsrStack } from "./CsrStack";
31
- import { CsrFrameDump } from "./csrFrameDump";
32
- import { type NativeBackProgress, NativeNavigation } from "./nativeNavigation";
33
- import { NativeUpdates } from "./nativeUpdates";
34
- import {
35
- createFrameSnapshot,
36
- createTransitionPlan,
37
- FRAME_Z_INDEX,
38
- getFramePlatformProfile,
39
- getFrameSlotsForSnapshot,
40
- hasBottomAnchoredKeyboardSlot,
41
- hasKeyboardStickySlot,
42
- isPendingFrameReady,
43
- PENDING_FRAME_READY_TIMEOUT_MS,
44
- prepareForFrameTransition,
45
- resolveFramePageStateMap,
46
- resolveKeyboardAccessoryHeight,
47
- resolveKeyboardLayout,
48
- resolveLocationWithFrameState,
49
- resolvePathRoutesWithFrameState,
50
- useFrameRuntimeResync,
51
- useFrameSlots,
52
- useFrameViewport,
53
- useKeyboardFrame,
54
- } from "./useFrameRuntime";
55
- import { useHistory } from "./useHistory";
56
- import { useLocation } from "./useLocation";
57
-
58
- const linearEasing = (t: number) => t;
59
-
60
- const getBottomInsetTop = (clientHeight: number, pageState: PathRoute["pageState"]) =>
61
- clientHeight - pageState.bottomInset - pageState.bottomSafeArea;
62
-
63
- const getFrameContentOffset = (ownTop: number, prevTop: number, pageTop: number, progress: number) =>
64
- ownTop - (prevTop + (pageTop - prevTop) * progress);
65
-
66
- type GestureIntent = "pending" | "gesture" | "scroll";
67
- const GESTURE_INTENT_THRESHOLD = 8;
68
- const GESTURE_AXIS_LOCK_RATIO = 1.25;
69
- const STACK_VELOCITY_DISMISS_THRESHOLD = 0.45;
70
- const STACK_SETTLE_MIN_DURATION = 90;
71
- const STACK_SETTLE_MAX_DURATION = 260;
72
- const ANDROID_SCALE_TRANSITION_DURATION = 220;
73
- const CSR_RUNTIME_SEARCH_PARAMS = ["csr", "akanMobileTarget", "akanMobileBasePath", "akanMobileIndexPath"] as const;
74
-
75
- const getVelocityAwareDuration = (distance: number, velocity: number, fallback: number) => {
76
- const absVelocity = Math.abs(velocity);
77
- if (absVelocity <= 0.01) return fallback;
78
- return clamp(Math.round(Math.abs(distance) / absVelocity), STACK_SETTLE_MIN_DURATION, STACK_SETTLE_MAX_DURATION);
79
- };
80
-
81
- const getSyncRouteHref = (location: {
82
- pathname: string;
83
- search: string;
84
- hash: string;
85
- params?: { [key: string]: string };
19
+ import { useCallback, useMemo, useState } from "react";
20
+ import { CsrRefresh } from "./csrRefresh";
21
+ import { useCsrKeyboard } from "./useCsrKeyboard";
22
+ import { type CsrLocationState, useCsrLocationState } from "./useCsrLocationState";
23
+ import { type CsrNavigation, useCsrNavigation } from "./useCsrNavigation";
24
+ import { type CsrRefs, currentRouter, useCsrRefs } from "./useCsrRefs";
25
+ import { useCsrRenderTrace } from "./useCsrRenderTrace";
26
+ import { useCsrStackLifecycle } from "./useCsrStackLifecycle";
27
+ import { useCsrTransitions } from "./useCsrTransitions";
28
+ import { FRAME_Z_INDEX, useFrameSlots, useFrameViewport } from "./useFrameRuntime";
29
+ import { useResolvedFrame } from "./useResolvedFrame";
30
+ import { getSyncRouteHref, useSyncNavigation } from "./useSyncNavigation";
31
+
32
+ const useCsrRouter = ({
33
+ refs: { pendingNavigation, pageContentRef, waitingNavigation, onBack, latestRouter },
34
+ nav,
35
+ navigation,
36
+ }: {
37
+ refs: CsrRefs;
38
+ nav: CsrLocationState;
39
+ navigation: CsrNavigation;
86
40
  }) => {
87
- const segments = location.pathname.split("/").filter(Boolean);
88
- const lang = location.params?.lang ?? parseAkanI18nEnv().locales.find((locale) => locale === segments[0]) ?? "";
89
- const configuredBasePaths = new Set(parseBasePaths(process.env.AKAN_PUBLIC_BASE_PATHS));
90
- const runtimeSearch = new URLSearchParams(location.search ?? "");
91
- const mobileBasePath = runtimeSearch.get("akanMobileBasePath") ?? "";
92
- if (mobileBasePath) configuredBasePaths.add(mobileBasePath);
93
- const prefix = segments[1] && configuredBasePaths.has(segments[1]) ? segments[1] : "";
94
- const { path } = getPathInfo(location.pathname, lang, prefix);
95
- for (const param of CSR_RUNTIME_SEARCH_PARAMS) runtimeSearch.delete(param);
96
- const search = runtimeSearch.toString();
97
- return `${path}${search ? `?${search}` : ""}${location.hash ? `#${location.hash}` : ""}`;
98
- };
99
-
100
- type Progress = UseCsrTransition["transProgress"];
101
- type FramePageState = PathRoute["pageState"];
102
-
103
- const tween = (progress: Progress, from: number, to: number) => progress.to([0, 1], [from, to]);
104
- const fadeIn = (progress: Progress) => ({ opacity: progress.to((value) => value) });
105
- const fadeOut = (progress: Progress) => ({ opacity: progress.to((value) => 1 - value) });
106
-
107
- const pageContentStyle = ({ frameLayout }: RouteState, pageState: FramePageState) => ({
108
- paddingTop: pageState.topSafeArea + pageState.topInset,
109
- paddingBottom: Math.max(
110
- pageState.bottomSafeArea,
111
- pageState.bottomInset +
112
- pageState.bottomSafeArea -
113
- (frameLayout.keyboard.sticky ? frameLayout.keyboardAccessory.height : 0),
114
- ),
115
- height: frameLayout.contentViewport.height,
116
- "--akan-content-height": `${frameLayout.contentViewport.height}px`,
117
- });
118
-
119
- const prevPageContentStyle = (clientHeight: number, prevPageState: FramePageState) => ({
120
- paddingTop: prevPageState.topSafeArea + prevPageState.topInset,
121
- paddingBottom: prevPageState.bottomInset + prevPageState.bottomSafeArea,
122
- height: clientHeight,
123
- });
124
-
125
- const tweenedSafeAreas = (
126
- progress: Progress,
127
- clientHeight: number,
128
- pageState: FramePageState,
129
- prevPageState: FramePageState,
130
- ) => ({
131
- topSafeArea: {
132
- containerStyle: {
133
- backgroundColor: pageState.topSafeAreaColor,
134
- height: tween(progress, prevPageState.topSafeArea, pageState.topSafeArea),
135
- },
136
- },
137
- bottomSafeArea: {
138
- containerStyle: {
139
- backgroundColor: pageState.bottomSafeAreaColor,
140
- visibility:
141
- pageState.bottomInset > 0 || pageState.bottomSafeAreaColor !== defaultPageState.bottomSafeAreaColor
142
- ? ("visible" as const)
143
- : ("hidden" as const),
144
- top: tween(progress, clientHeight - prevPageState.bottomSafeArea, clientHeight - pageState.bottomSafeArea),
145
- height: tween(progress, prevPageState.bottomSafeArea, pageState.bottomSafeArea),
146
- },
147
- },
148
- });
149
-
150
- const tweenedTopInset = (progress: Progress, pageState: FramePageState, prevPageState: FramePageState) => ({
151
- top: tween(progress, prevPageState.topSafeArea, pageState.topSafeArea),
152
- height: tween(progress, prevPageState.topInset, pageState.topInset),
153
- });
154
-
155
- const tweenedBottomInset = (
156
- progress: Progress,
157
- clientHeight: number,
158
- pageState: FramePageState,
159
- prevPageState: FramePageState,
160
- ) => ({
161
- height: tween(progress, prevPageState.bottomInset, pageState.bottomInset),
162
- top: tween(progress, getBottomInsetTop(clientHeight, prevPageState), getBottomInsetTop(clientHeight, pageState)),
163
- });
164
-
165
- const useFadeSpring = () => {
166
- const transUnit = useSpringValue(1, { config: { clamp: true } });
167
- const transUnitRange = useMemo(() => [0, 1], []);
168
- return {
169
- transUnit,
170
- transUnitRange,
171
- transProgress: transUnit.to((unit) => unit),
172
- transPercent: transUnit.to([0, 1], [0, 100], "clamp"),
173
- };
174
- };
175
-
176
- const useSlideSpring = (size: number) => {
177
- const transUnit = useSpringValue(0, { config: { clamp: true } });
178
- const transUnitRange = useMemo(() => [size, 0], [size]);
179
- const transUnitReversed = transUnit.to((unit) => transUnitRange[0] - unit);
180
- const transUnitRangeReversed = useMemo(() => [0, size], [size]);
181
- return {
182
- transUnit,
183
- transUnitRange,
184
- transProgress: transUnitReversed.to(transUnitRangeReversed, [0, 1], "clamp"),
185
- transPercent: transUnitReversed.to(transUnitRangeReversed, [0, 100], "clamp"),
186
- };
187
- };
188
-
189
- const usePlayOnForward = (
190
- { transUnit, transUnitRange }: Pick<UseCsrTransition, "transUnit" | "transUnitRange">,
191
- { history, location }: RouteState,
192
- config: { duration: number; easing?: (t: number) => number },
193
- ) => {
194
- useEffect(() => {
195
- if (history.current.type === "forward") {
196
- void transUnit.start(transUnitRange[0], { immediate: true });
197
- void transUnit.start(transUnitRange[1], { config });
198
- } else void transUnit.start(transUnitRange[1], { immediate: true });
199
- }, [location.entryId ?? location.pathname]);
200
- };
201
-
202
- const useNoneTrans = (routeState: RouteState): UseCsrTransition => {
203
- const { clientHeight, location, prevLocation } = routeState;
204
- const transUnit = useSpringValue(0, { config: { clamp: true } });
205
- const transUnitRange = useMemo(() => [0, 0], []);
206
- const pageState = location.pathRoute.pageState;
207
- const prevPageState = prevLocation?.pathRoute.pageState ?? defaultPageState;
208
- return {
209
- topSafeArea: {
210
- containerStyle: {
211
- backgroundColor: pageState.topSafeAreaColor,
212
- height: pageState.topSafeArea,
213
- },
214
- },
215
- bottomSafeArea: {
216
- containerStyle: {
217
- backgroundColor: pageState.bottomSafeAreaColor,
218
- top: clientHeight - pageState.bottomSafeArea,
219
- height: pageState.bottomSafeArea,
220
- },
221
- },
222
- page: {
223
- containerStyle: {
224
- top: 0,
225
- left: 0,
226
- height: clientHeight,
227
- },
228
- contentStyle: pageContentStyle(routeState, pageState),
229
- },
230
- prevPage: {
231
- containerStyle: {
232
- paddingTop: prevPageState.topSafeArea + prevPageState.topInset,
233
- },
234
- contentStyle: { opacity: 0 },
235
- },
236
- topInset: {
237
- containerStyle: {
238
- top: pageState.topSafeArea,
239
- height: pageState.topInset,
240
- },
241
- contentStyle: { opacity: 1 },
242
- prevContentStyle: { opacity: 0 },
243
- },
244
- topLeftAction: {
245
- containerStyle: {
246
- top: pageState.topSafeArea,
247
- height: pageState.topInset,
248
- },
249
- contentStyle: { opacity: 1 },
250
- prevContentStyle: { opacity: 0 },
251
- },
252
- bottomInset: {
253
- containerStyle: {
254
- height: pageState.bottomInset,
255
- top: getBottomInsetTop(clientHeight, pageState),
256
- },
257
- contentStyle: { opacity: 1 },
258
- prevContentStyle: { opacity: 0 },
259
- },
260
- pageBind: () => ({}),
261
- pageClassName: "touch-pan-y",
262
- transDirection: "none",
263
- transUnitRange,
264
- transUnit,
265
- transProgress: transUnit.to(() => 1),
266
- transPercent: transUnit.to(() => 100),
267
- };
268
- };
269
-
270
- const useFadeTrans = (routeState: RouteState): UseCsrTransition => {
271
- const { clientHeight, location, prevLocation, onBack } = routeState;
272
- const spring = useFadeSpring();
273
- const { transUnit, transUnitRange, transProgress } = spring;
274
- const pageState = location.pathRoute.pageState;
275
- const prevPageState = prevLocation?.pathRoute.pageState ?? defaultPageState;
276
- const pageBottomInsetTop = getBottomInsetTop(clientHeight, pageState);
277
- const prevBottomInsetTop = getBottomInsetTop(clientHeight, prevPageState);
278
-
279
- useEffect(() => {
280
- onBack.current.fade = async () => {
281
- await transUnit.start(transUnitRange[0]);
282
- };
283
- }, []);
284
- usePlayOnForward(spring, routeState, { duration: 150 });
285
-
286
- return {
287
- ...tweenedSafeAreas(transProgress, clientHeight, pageState, prevPageState),
288
- page: {
289
- containerStyle: {},
290
- contentStyle: { ...pageContentStyle(routeState, pageState), opacity: transUnit },
291
- },
292
- prevPage: {
293
- containerStyle: {
294
- opacity: transProgress.to((progress) => 1 - progress),
295
- },
296
- contentStyle: prevPageContentStyle(clientHeight, prevPageState),
297
- },
298
- topInset: {
299
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
300
- contentStyle: { opacity: transProgress },
301
- prevContentStyle: fadeOut(transProgress),
302
- },
303
- topLeftAction: {
304
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
305
- contentStyle: {
306
- top: tween(transProgress, 0, -(pageState.bottomInset - prevPageState.bottomInset) * 2),
307
- ...fadeIn(transProgress),
308
- },
309
- prevContentStyle: {
310
- top: tween(transProgress, 0, -(pageState.bottomInset - prevPageState.bottomInset) * 2),
311
- ...fadeOut(transProgress),
312
- },
313
- },
314
- bottomInset: {
315
- containerStyle: tweenedBottomInset(transProgress, clientHeight, pageState, prevPageState),
316
- contentStyle: {
317
- height: pageState.bottomInset,
318
- translateY: transProgress.to((progress) =>
319
- getFrameContentOffset(pageBottomInsetTop, prevBottomInsetTop, pageBottomInsetTop, progress),
320
- ),
321
- ...fadeIn(transProgress),
322
- transformOrigin: "top",
323
- },
324
- prevContentStyle: {
325
- height: prevPageState.bottomInset,
326
- translateY: transProgress.to((progress) =>
327
- getFrameContentOffset(prevBottomInsetTop, prevBottomInsetTop, pageBottomInsetTop, progress),
328
- ),
329
- ...fadeOut(transProgress),
330
- transformOrigin: "top",
331
- },
332
- },
333
- pageBind: () => ({}),
334
- pageClassName: "",
335
- transDirection: "none",
336
- ...spring,
337
- };
338
- };
339
-
340
- const useScaleOutTrans = (routeState: RouteState): UseCsrTransition => {
341
- const { clientHeight, location, prevLocation, onBack } = routeState;
342
- const spring = useFadeSpring();
343
- const { transUnit, transUnitRange, transProgress } = spring;
344
- const pageState = location.pathRoute.pageState;
345
- const prevPageState = prevLocation?.pathRoute.pageState ?? defaultPageState;
346
-
347
- useEffect(() => {
348
- onBack.current.scaleOut = async () => {
349
- await transUnit.start(transUnitRange[0], { config: { duration: ANDROID_SCALE_TRANSITION_DURATION } });
350
- };
351
- }, []);
352
- usePlayOnForward(spring, routeState, { duration: ANDROID_SCALE_TRANSITION_DURATION });
353
-
354
- return {
355
- ...tweenedSafeAreas(transProgress, clientHeight, pageState, prevPageState),
356
- page: {
357
- containerStyle: {
358
- transform: transProgress.to((progress) => `scale(${0.92 + progress * 0.08})`),
359
- },
360
- contentStyle: { ...pageContentStyle(routeState, pageState), opacity: transProgress },
361
- },
362
- prevPage: {
363
- containerStyle: {
364
- transform: transProgress.to((progress) => `scale(${1 - progress * 0.02})`),
365
- },
366
- contentStyle: {
367
- ...prevPageContentStyle(clientHeight, prevPageState),
368
- opacity: transProgress.to((progress) => 1 - progress * 0.35),
369
- },
370
- },
371
- topInset: {
372
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
373
- contentStyle: { opacity: transProgress },
374
- prevContentStyle: fadeOut(transProgress),
375
- },
376
- topLeftAction: {
377
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
378
- contentStyle: { opacity: transProgress },
379
- prevContentStyle: fadeOut(transProgress),
380
- },
381
- bottomInset: {
382
- containerStyle: tweenedBottomInset(transProgress, clientHeight, pageState, prevPageState),
383
- contentStyle: { opacity: transProgress },
384
- prevContentStyle: fadeOut(transProgress),
385
- },
386
- pageBind: () => ({}),
387
- pageClassName: "",
388
- transDirection: "none",
389
- ...spring,
390
- };
391
- };
392
-
393
- const useStackTrans = (routeState: RouteState): UseCsrTransition => {
394
- const { clientWidth, clientHeight, location, prevLocation, onBack, pageContentRef } = routeState;
395
- const spring = useSlideSpring(clientWidth);
396
- const { transUnit, transUnitRange, transProgress } = spring;
397
- const initThreshold = useMemo(() => Math.floor(clientWidth), [clientWidth]);
398
- const threshold = useMemo(() => Math.floor(clientWidth / 3), [clientWidth]);
399
- const pageState = location.pathRoute.pageState;
400
- const prevPageState = prevLocation?.pathRoute.pageState ?? defaultPageState;
401
- const gestureIntent = useRef<GestureIntent>("pending");
402
- const scrollLockRef = useRef<{ overflowY: string; touchAction: string } | null>(null);
403
- const stackBackConfigRef = useRef<{ duration: number } | null>(null);
404
- const lockPageScroll = useCallback(() => {
405
- const pageContent = pageContentRef.current;
406
- if (!pageContent || scrollLockRef.current) return;
407
- scrollLockRef.current = {
408
- overflowY: pageContent.style.overflowY,
409
- touchAction: pageContent.style.touchAction,
410
- };
411
- pageContent.style.overflowY = "hidden";
412
- pageContent.style.touchAction = "none";
413
- }, [pageContentRef]);
414
- const unlockPageScroll = useCallback(() => {
415
- const pageContent = pageContentRef.current;
416
- const scrollLock = scrollLockRef.current;
417
- if (!pageContent || !scrollLock) return;
418
- pageContent.style.overflowY = scrollLock.overflowY;
419
- pageContent.style.touchAction = scrollLock.touchAction;
420
- scrollLockRef.current = null;
421
- }, [pageContentRef]);
422
- useEffect(() => {
423
- onBack.current.stack = async () => {
424
- const config = stackBackConfigRef.current;
425
- stackBackConfigRef.current = null;
426
- await transUnit.start(transUnitRange[0], config ? { config } : undefined);
427
- };
428
- }, [transUnitRange]);
429
- useEffect(() => unlockPageScroll, [unlockPageScroll]);
430
- usePlayOnForward(spring, routeState, { duration: 150 });
431
-
432
- const pageBind = useDrag(
433
- ({ first, last, movement: [mx, my], velocity: [vx], direction: [dx], initial: [ix], cancel }) => {
434
- if (first) {
435
- gestureIntent.current = "pending";
436
- stackBackConfigRef.current = null;
437
- unlockPageScroll();
438
- }
439
- if (ix > initThreshold) {
440
- gestureIntent.current = "scroll";
441
- cancel();
442
- return;
443
- }
444
- if (gestureIntent.current === "pending") {
445
- const absX = Math.abs(mx);
446
- const absY = Math.abs(my);
447
- if (absY >= GESTURE_INTENT_THRESHOLD && absY > absX * GESTURE_AXIS_LOCK_RATIO) {
448
- gestureIntent.current = "scroll";
449
- void transUnit.start(transUnitRange[1], { immediate: true });
450
- cancel();
451
- return;
452
- }
453
- if (absX < GESTURE_INTENT_THRESHOLD || absX <= absY * GESTURE_AXIS_LOCK_RATIO) return;
454
- gestureIntent.current = "gesture";
455
- lockPageScroll();
456
- void Device.getDevice().hideKeyboard();
457
- }
458
- if (gestureIntent.current !== "gesture") {
459
- cancel();
460
- return;
461
- }
462
- if (mx < transUnitRange[1]) void transUnit.start(transUnitRange[1], { immediate: true });
463
- else if (mx > transUnitRange[0]) void transUnit.start(transUnitRange[0], { immediate: true });
464
- else if (!last) void transUnit.start(mx, { immediate: true });
465
- if (last) {
466
- const shouldComplete = mx > threshold || (dx > 0 && vx > STACK_VELOCITY_DISMISS_THRESHOLD);
467
- const target = shouldComplete ? transUnitRange[0] : transUnitRange[1];
468
- const duration = getVelocityAwareDuration(target - mx, vx, shouldComplete ? 150 : 180);
469
- if (shouldComplete) stackBackConfigRef.current = { duration };
470
- else void transUnit.start(transUnitRange[1], { config: { duration } });
471
- unlockPageScroll();
472
- gestureIntent.current = "pending";
473
- if (!shouldComplete) return;
474
- clientRouter.back();
475
- void clientRouter.navigation().catch(() => {
476
- stackBackConfigRef.current = null;
477
- void transUnit.start(transUnitRange[1], { config: { duration } });
478
- });
479
- }
480
- },
481
- { filterTaps: true },
482
- );
483
-
484
- return {
485
- ...tweenedSafeAreas(transProgress, clientHeight, pageState, prevPageState),
486
- page: {
487
- containerStyle: {},
488
- contentStyle: { ...pageContentStyle(routeState, pageState), translateX: transUnit },
489
- },
490
- prevPage: {
491
- containerStyle: {
492
- top: 0,
493
- left: 0,
494
- height: clientHeight,
495
- translateX: transUnit.to((unit) => (unit - clientWidth) / 5),
496
- },
497
- contentStyle: {
498
- ...prevPageContentStyle(clientHeight, prevPageState),
499
- opacity: transProgress.to((progress) => 1 - progress / 2),
500
- },
501
- },
502
- topInset: {
503
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
504
- contentStyle: { ...fadeIn(transProgress), translateX: tween(transProgress, clientWidth / 5, 0) },
505
- prevContentStyle: { ...fadeOut(transProgress), translateX: tween(transProgress, 0, -clientWidth / 5) },
506
- },
507
- topLeftAction: {
508
- containerStyle: {
509
- ...tweenedTopInset(transProgress, pageState, prevPageState),
510
- minWidth: tween(transProgress, prevPageState.topInset, pageState.topInset),
511
- },
512
- contentStyle: fadeIn(transProgress),
513
- prevContentStyle: fadeOut(transProgress),
514
- },
515
- bottomInset: {
516
- containerStyle: tweenedBottomInset(transProgress, clientHeight, pageState, prevPageState),
517
- contentStyle: { height: pageState.bottomInset, translateX: transUnit, ...fadeIn(transProgress) },
518
- prevContentStyle: {
519
- height: prevPageState.bottomInset,
520
- translateX: transUnit.to((unit) => (unit - clientWidth) / 5),
521
- ...fadeOut(transProgress),
522
- },
523
- },
524
- pageBind,
525
- pageClassName: "touch-pan-y",
526
- transDirection: "horizontal",
527
- ...spring,
528
- };
529
- };
530
-
531
- const useBottomUpTrans = (routeState: RouteState): UseCsrTransition => {
532
- const { clientHeight, location, prevLocation, onBack } = routeState;
533
- const spring = useSlideSpring(clientHeight);
534
- const { transUnit, transUnitRange, transProgress } = spring;
535
- const initThreshold = useMemo(() => Math.floor(clientHeight / 3), [clientHeight]);
536
- const threshold = useMemo(() => Math.floor(clientHeight / 2), [clientHeight]);
537
- const pageState = location.pathRoute.pageState;
538
- const prevPageState = prevLocation?.pathRoute.pageState ?? defaultPageState;
539
- useEffect(() => {
540
- onBack.current.bottomUp = async () => {
541
- await transUnit.start(transUnitRange[0], { config: { duration: 220, easing: linearEasing } });
542
- };
543
- }, [transUnitRange]);
544
- usePlayOnForward(spring, routeState, { duration: 220, easing: linearEasing });
545
-
546
- const pageBind = useDrag(
547
- ({ first, last, movement: [, my], initial: [, iy], cancel }) => {
548
- if (iy > initThreshold) {
549
- cancel();
550
- return;
551
- }
552
- if (first) void Device.getDevice().hideKeyboard();
553
- if (my < transUnitRange[1]) void transUnit.start(transUnitRange[1], { immediate: true });
554
- else if (my > transUnitRange[0]) void transUnit.start(transUnitRange[0], { immediate: true });
555
- else if (!last) void transUnit.start(my, { immediate: true });
556
- else if (my < threshold) void transUnit.start(transUnitRange[1]);
557
- if (!last || my <= threshold) return;
558
- clientRouter.back();
559
- void clientRouter.navigation().catch(() => transUnit.start(transUnitRange[1]));
560
- },
561
- { axis: "y", filterTaps: true, threshold: 10 },
562
- );
563
-
564
- return {
565
- ...tweenedSafeAreas(transProgress, clientHeight, pageState, prevPageState),
566
- page: {
567
- containerStyle: {},
568
- contentStyle: { ...pageContentStyle(routeState, pageState), translateY: transUnit },
569
- },
570
- prevPage: {
571
- containerStyle: {
572
- translateY: 0,
573
- },
574
- contentStyle: {
575
- ...prevPageContentStyle(clientHeight, prevPageState),
576
- opacity: transProgress.to((progress) => 1 - progress / 2),
577
- },
578
- },
579
- topInset: {
580
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
581
- contentStyle: fadeIn(transProgress),
582
- prevContentStyle: fadeOut(transProgress),
583
- },
584
- topLeftAction: {
585
- containerStyle: tweenedTopInset(transProgress, pageState, prevPageState),
586
- contentStyle: fadeIn(transProgress),
587
- prevContentStyle: fadeOut(transProgress),
588
- },
589
- bottomInset: {
590
- containerStyle: tweenedBottomInset(transProgress, clientHeight, pageState, prevPageState),
591
- contentStyle: fadeIn(transProgress),
592
- prevContentStyle: fadeOut(transProgress),
593
- },
594
- pageBind,
595
- pageClassName: "touch-pan-x",
596
- transDirection: "vertical",
597
- ...spring,
598
- };
599
- };
600
-
601
- export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]) => {
602
- const { viewport, updateViewport } = useFrameViewport();
603
- const { frameSlots, pendingFrameSlots, registerFrameSlot, promotePendingSlots, clearPendingSlots } = useFrameSlots();
604
- const [transitionPageStateSnapshot, setTransitionPageStateSnapshot] = useState<Map<string, PageState> | null>(null);
605
- const pageStateByPathRef = useRef(new Map<string, PageState>());
606
- const navigationIntentId = useRef(0);
607
- const transitionPlanId = useRef(0);
608
- const navigationLocked = useRef(false);
609
- const pendingNavigation = useRef<NavigationIntent | null>(null);
610
- const waitingNavigation = useRef<{ kind: "push" | "replace"; href: string; scrollToTop?: boolean } | null>(null);
611
- const renderCountRef = useRef(0);
612
- const basePageStateMap = useRef(new WeakMap<PathRoute, PathRoute["pageState"]>());
613
- const topSafeAreaRef = useRef<HTMLDivElement>(null);
614
- const bottomSafeAreaRef = useRef<HTMLDivElement>(null);
615
- const pageContentRef = useRef<HTMLDivElement>(null);
616
- const prevPageContentRef = useRef<HTMLDivElement>(null);
617
- const onBack = useRef<{ [K in TransitionType]?: () => Promise<void> }>({});
618
- const frameRootRef = useRef<HTMLDivElement>(null);
619
- const lastBroadcastSyncHref = useRef<string | null>(null);
620
- const syncNavigationReset = useRef<ReturnType<typeof setTimeout> | null>(null);
621
-
622
- const { getLocation } = useLocation({ rootRouteGuide });
623
- const [initialStack] = useState(() => {
624
- const current = getLocation(csrLocation.href);
625
- return CsrStack.restore(current, getLocation) ?? { locations: [current], idx: 0 };
626
- });
627
- const {
628
- history,
629
- setHistoryForward,
630
- setHistoryBack,
631
- setHistoryJump,
632
- getNextLocation,
633
- getCurrentLocation,
634
- getPrevLocation,
635
- getScrollTop,
636
- } = useHistory(initialStack.locations, initialStack);
637
- history.current.account ??= { token: getAuthToken() ?? null, generation: 0 };
638
- const [isBackgrounded, setIsBackgrounded] = useState(() => document.visibilityState === "hidden");
639
- const [locationState, setLocationState] = useState<LocationState>({
640
- location: getCurrentLocation(),
641
- prevLocation: getPrevLocation(),
642
- pendingLocation: null,
643
- navigationIntent: null,
644
- phase: "idle",
645
- });
646
- const { location, prevLocation } = locationState;
647
- const pendingLocation = locationState.pendingLocation ?? null;
648
- const navigationIntent = locationState.navigationIntent ?? null;
649
- const phase = locationState.phase ?? "idle";
650
- const pageStateByPath = useMemo(
651
- () =>
652
- resolveFramePageStateMap({
653
- pathRoutes,
654
- frameSlots,
655
- pendingFrameSlots,
656
- pendingPath: pendingLocation?.pathRoute.path,
657
- visiblePaths: [
658
- location.pathRoute.path,
659
- ...(prevLocation ? [prevLocation.pathRoute.path] : []),
660
- ...(pendingLocation ? [pendingLocation.pathRoute.path] : []),
661
- ],
662
- basePageStateMap: basePageStateMap.current,
663
- }),
664
- [
665
- pathRoutes,
666
- frameSlots,
667
- pendingFrameSlots,
668
- pendingLocation?.pathRoute.path,
669
- location.pathRoute.path,
670
- prevLocation?.pathRoute.path,
671
- ],
672
- );
673
- useEffect(() => {
674
- if (!transitionPageStateSnapshot) pageStateByPathRef.current = pageStateByPath;
675
- }, [pageStateByPath, transitionPageStateSnapshot]);
676
- const latestPageStateByPath = useRef(pageStateByPath);
677
- const latestFrameSlots = useRef(frameSlots);
678
- const latestPendingFrameSlots = useRef(pendingFrameSlots);
679
- useEffect(() => {
680
- latestPageStateByPath.current = pageStateByPath;
681
- latestFrameSlots.current = frameSlots;
682
- latestPendingFrameSlots.current = pendingFrameSlots;
683
- }, [pageStateByPath, frameSlots, pendingFrameSlots]);
684
- if (pageStateByPathRef.current.size === 0) pageStateByPathRef.current = pageStateByPath;
685
- const effectivePageStateByPath = transitionPageStateSnapshot ?? pageStateByPath;
686
- const resolvedPathRoutes = useMemo(
687
- () => resolvePathRoutesWithFrameState(pathRoutes, effectivePageStateByPath),
688
- [pathRoutes, effectivePageStateByPath],
689
- );
690
- const resolvedPathRouteMap = useMemo(
691
- () => new Map(resolvedPathRoutes.map((pathRoute) => [pathRoute.path, pathRoute])),
692
- [resolvedPathRoutes],
693
- );
694
- const resolvedLocation = resolveLocationWithFrameState(location, resolvedPathRouteMap) ?? location;
695
- const resolvedPrevLocation = resolveLocationWithFrameState(prevLocation, resolvedPathRouteMap);
696
- const resolvedPendingLocation = resolveLocationWithFrameState(pendingLocation, resolvedPathRouteMap);
697
- const stackEntries = CsrStack.entriesOf({
698
- history: history.current,
699
- location,
700
- prevLocation,
701
- pendingLocation,
702
- phase,
703
- }).map((entry) => ({
704
- ...entry,
705
- location: resolveLocationWithFrameState(entry.location, resolvedPathRouteMap) ?? entry.location,
706
- }));
707
- const frameDumpRef = useRef({ phase, location, prevLocation, pendingLocation, stackEntries });
708
- frameDumpRef.current = { phase, location, prevLocation, pendingLocation, stackEntries };
709
- useEffect(() => {
710
- CsrFrameDump.watchFrame(() => {
711
- const frame = frameDumpRef.current;
712
- return {
713
- phase: frame.phase,
714
- location: frame.location.href,
715
- prevLocation: frame.prevLocation?.href ?? null,
716
- pendingLocation: frame.pendingLocation?.href ?? null,
717
- stack: frame.stackEntries.map(({ key, location: entry, pageType }) => ({
718
- key,
719
- path: entry.pathRoute.path,
720
- pageType,
721
- })),
722
- };
723
- });
724
- }, []);
725
- const platformProfile = getFramePlatformProfile();
726
- const accessoryHeight = resolveKeyboardAccessoryHeight(resolvedLocation.pathRoute.path, frameSlots);
727
- const shouldAnchorContentBottom = hasBottomAnchoredKeyboardSlot(resolvedLocation.pathRoute.path, frameSlots);
728
- const keyboardFrame = useKeyboardFrame({
729
- bottomSafeArea: resolvedLocation.pathRoute.pageState.bottomSafeArea,
730
- sticky: hasKeyboardStickySlot(resolvedLocation.pathRoute.path, frameSlots),
731
- viewport,
732
- platformProfile,
733
- freeze: phase === "transitioning",
734
- });
735
- const keyboardLayout = useMemo(
736
- () =>
737
- resolveKeyboardLayout({
738
- viewport,
739
- keyboard: keyboardFrame,
740
- accessoryHeight,
741
- bottomSafeArea: resolvedLocation.pathRoute.pageState.bottomSafeArea,
742
- }),
743
- [viewport, keyboardFrame, accessoryHeight, resolvedLocation.pathRoute.pageState.bottomSafeArea],
744
- );
745
- const contentBottomAnchorRef = useRef<{
746
- path: string;
747
- contentViewportHeight: number;
748
- bottomDistance: number;
749
- } | null>(null);
750
- const contentBottomAnchorRafRef = useRef<number | null>(null);
751
- useLayoutEffect(() => {
752
- const element = pageContentRef.current;
753
- const path = resolvedLocation.pathRoute.path;
754
- if (!element || !shouldAnchorContentBottom || !keyboardFrame.sticky) {
755
- contentBottomAnchorRef.current = null;
756
- if (contentBottomAnchorRafRef.current !== null) {
757
- cancelAnimationFrame(contentBottomAnchorRafRef.current);
758
- contentBottomAnchorRafRef.current = null;
759
- }
760
- return;
761
- }
762
-
763
- const previous = contentBottomAnchorRef.current;
764
- const currentBottomDistance = Math.max(0, element.scrollHeight - element.scrollTop - element.clientHeight);
765
- if (!previous || previous.path !== path) {
766
- contentBottomAnchorRef.current = {
767
- path,
768
- contentViewportHeight: keyboardLayout.contentViewport.height,
769
- bottomDistance: currentBottomDistance,
770
- };
771
- return;
772
- }
773
-
774
- const shouldRestoreBottom = previous.contentViewportHeight !== keyboardLayout.contentViewport.height;
775
- const bottomDistance = previous.bottomDistance;
776
- if (shouldRestoreBottom) {
777
- const nextScrollTop = Math.max(0, element.scrollHeight - element.clientHeight - bottomDistance);
778
- if (Math.abs(element.scrollTop - nextScrollTop) > 1) {
779
- debugFrame("keyboard.contentAnchor", {
780
- path,
781
- from: element.scrollTop,
782
- to: nextScrollTop,
783
- bottomDistance,
784
- contentViewportHeight: keyboardLayout.contentViewport.height,
785
- });
786
- element.scrollTop = nextScrollTop;
787
- }
788
- const startedAt = performance.now();
789
- const duration = (keyboardFrame.animationDuration ?? 0) + 50;
790
- const keepBottomAnchored = () => {
791
- const scrollTop = Math.max(0, element.scrollHeight - element.clientHeight - bottomDistance);
792
- if (Math.abs(element.scrollTop - scrollTop) > 1) element.scrollTop = scrollTop;
793
- if (performance.now() - startedAt < duration) {
794
- contentBottomAnchorRafRef.current = requestAnimationFrame(keepBottomAnchored);
795
- } else {
796
- contentBottomAnchorRafRef.current = null;
797
- }
798
- };
799
- if (contentBottomAnchorRafRef.current !== null) cancelAnimationFrame(contentBottomAnchorRafRef.current);
800
- contentBottomAnchorRafRef.current = requestAnimationFrame(keepBottomAnchored);
801
- }
802
-
803
- contentBottomAnchorRef.current = {
804
- path,
805
- contentViewportHeight: keyboardLayout.contentViewport.height,
806
- bottomDistance: Math.max(0, element.scrollHeight - element.scrollTop - element.clientHeight),
807
- };
808
- return () => {
809
- if (contentBottomAnchorRafRef.current !== null) {
810
- cancelAnimationFrame(contentBottomAnchorRafRef.current);
811
- contentBottomAnchorRafRef.current = null;
812
- }
813
- };
814
- }, [
815
- pageContentRef,
816
- resolvedLocation.pathRoute.path,
817
- shouldAnchorContentBottom,
818
- keyboardFrame.sticky,
819
- keyboardFrame.animationDuration,
820
- keyboardLayout.contentViewport.height,
821
- ]);
822
- useEffect(() => {
823
- const element = pageContentRef.current;
824
- const path = resolvedLocation.pathRoute.path;
825
- if (!element || !shouldAnchorContentBottom || !keyboardFrame.sticky) return;
826
- const updateBottomDistance = () => {
827
- contentBottomAnchorRef.current = {
828
- path,
829
- contentViewportHeight: keyboardLayout.contentViewport.height,
830
- bottomDistance: Math.max(0, element.scrollHeight - element.scrollTop - element.clientHeight),
831
- };
832
- };
833
- element.addEventListener("scroll", updateBottomDistance, { passive: true });
834
- return () => element.removeEventListener("scroll", updateBottomDistance);
835
- }, [
836
- pageContentRef,
837
- resolvedLocation.pathRoute.path,
838
- shouldAnchorContentBottom,
839
- keyboardFrame.sticky,
840
- keyboardLayout.contentViewport.height,
841
- ]);
842
- useFrameRuntimeResync({ updateViewport });
843
- const shouldPrepareFrameTransition = useCallback(
844
- (nextHref?: string) => {
845
- if (keyboardFrame.visible) return true;
846
- if (!nextHref) return resolvedLocation.pathRoute.pageState.transition !== "none";
847
- const nextLocation = getLocation(nextHref);
848
- return (
849
- resolvedLocation.pathRoute.pageState.transition !== "none" ||
850
- nextLocation.pathRoute.pageState.transition !== "none"
851
- );
852
- },
853
- [getLocation, keyboardFrame.visible, resolvedLocation.pathRoute.pageState.transition],
854
- );
855
- const startFrameTransition = useCallback(async () => {
856
- const snapshot = new Map(pageStateByPathRef.current);
857
- setTransitionPageStateSnapshot(snapshot);
858
- window.setTimeout(() => setTransitionPageStateSnapshot(null), 360);
859
- await prepareForFrameTransition();
860
- }, []);
861
- const settle = (prev: LocationState["prevLocation"]) =>
862
- setLocationState({
863
- location: getCurrentLocation(),
864
- prevLocation: prev,
865
- pendingLocation: null,
866
- navigationIntent: null,
867
- phase: "idle",
868
- });
869
-
870
- const cancelPendingNavigation = useCallback(() => {
871
- const pending = pendingNavigation.current;
872
- if (!pending) return null;
873
- pendingNavigation.current = null;
874
- navigationLocked.current = false;
875
- clearPendingSlots();
876
- debugFrame("navigation.cancel", { reason: "superseded", id: pending.id, to: pending.to.href });
877
- setLocationState((current) => ({ ...current, pendingLocation: null, navigationIntent: null, phase: "idle" }));
878
- return pending;
879
- }, [clearPendingSlots]);
880
- const applyingSyncNavigation = useRef(false);
881
- const broadcastSyncNavigation = useCallback((kind: "push" | "replace" | "back" | "pop", href: string) => {
882
- if (applyingSyncNavigation.current || lastBroadcastSyncHref.current === href) return;
883
- lastBroadcastSyncHref.current = href;
884
- const syncNavigation = (
885
- globalThis as typeof globalThis & {
886
- __AKAN_DEV_SYNC_NAVIGATION__?: (href: string, kind: "push" | "replace" | "back" | "pop") => void;
887
- }
888
- ).__AKAN_DEV_SYNC_NAVIGATION__;
889
- syncNavigation?.(href, kind);
890
- }, []);
891
- const runForwardNavigation = useCallback(
892
- (kind: "push" | "replace", href: string, { scrollToTop }: RouteOptions = {}) => {
893
- const fromLocation = getCurrentLocation();
894
- const target = getLocation(href);
895
-
896
- const toLocation =
897
- kind === "replace" && target.pathRoute.path === fromLocation.pathRoute.path
898
- ? { ...target, entryId: fromLocation.entryId }
899
- : target;
900
- const scrollTop = pageContentRef.current?.scrollTop ?? 0;
901
- const usePendingNavigation =
902
- CsrStack.keyOf(toLocation) !== CsrStack.keyOf(fromLocation) &&
903
- shouldPrepareFrameTransition(href) &&
904
- toLocation.pathRoute.pageState.transition !== "none";
905
-
906
- if (!usePendingNavigation) {
907
- setHistoryForward({ type: kind, location: toLocation, scrollTop, scrollToTop });
908
- settle(kind === "replace" ? prevLocation : fromLocation);
909
- if (kind === "push") csrLocation.push({ akanEntryId: toLocation.entryId }, href);
910
- else csrLocation.replace({ akanEntryId: toLocation.entryId }, href);
911
- return;
912
- }
913
-
914
- if (navigationLocked.current) {
915
-
916
- const waiting = waitingNavigation.current;
917
- waitingNavigation.current = { kind: waiting?.kind === "push" ? "push" : kind, href, scrollToTop };
918
- debugFrame("navigation.wait", { kind, from: fromLocation.href, to: href });
919
- return;
920
- }
921
- navigationLocked.current = true;
922
- const intent: NavigationIntent = {
923
- id: ++navigationIntentId.current,
924
- kind,
925
- from: fromLocation,
926
- to: toLocation,
927
- scrollTop,
928
- scrollToTop,
929
- createdAt: Date.now(),
930
- };
931
- pendingNavigation.current = intent;
932
- debugFrame("navigation.intent", { id: intent.id, kind, from: fromLocation.href, to: href });
933
- clearPendingSlots();
934
- setLocationState({
935
- location: fromLocation,
936
- prevLocation,
937
- pendingLocation: toLocation,
938
- navigationIntent: intent,
939
- phase: "preparing",
940
- });
941
-
942
- const commitNavigation = async (timedOut: boolean) => {
943
- const latestPageStates = latestPageStateByPath.current;
944
- const fromPageState = latestPageStates.get(fromLocation.pathRoute.path) ?? fromLocation.pathRoute.pageState;
945
- const toPageState = latestPageStates.get(toLocation.pathRoute.path) ?? toLocation.pathRoute.pageState;
946
- const fromFrame = createFrameSnapshot({
947
- location: fromLocation,
948
- pageState: fromPageState,
949
- viewport,
950
- frameSlots: getFrameSlotsForSnapshot(fromLocation.pathRoute.path, latestFrameSlots.current),
951
- });
952
- const toFrame = createFrameSnapshot({
953
- location: toLocation,
954
- pageState: toPageState,
955
- viewport,
956
- frameSlots: getFrameSlotsForSnapshot(toLocation.pathRoute.path, latestPendingFrameSlots.current),
957
- });
958
- const plan = createTransitionPlan({
959
- id: ++transitionPlanId.current,
960
- intent,
961
- type: toPageState.transition,
962
- direction: "forward",
963
- fromFrame,
964
- toFrame,
965
- });
966
- debugFrame(timedOut ? "navigation.frameTimeout" : "navigation.frameReady", {
967
- id: intent.id,
968
- to: href,
969
- pendingSlots: toFrame.frameSlots,
970
- });
971
- debugFrame("transition.plan", {
972
- id: plan.id,
973
- type: plan.type,
974
- duration: plan.duration,
975
- actions: plan.actions.map((action) => action.type),
976
- });
977
- await prepareForFrameTransition();
978
- if (pendingNavigation.current !== intent) return;
979
- pendingNavigation.current = null;
980
- setTransitionPageStateSnapshot(new Map(latestPageStates));
981
- setHistoryForward({ type: kind, location: toLocation, scrollTop, scrollToTop });
982
- promotePendingSlots();
983
- setLocationState({
984
- location: getCurrentLocation(),
985
- prevLocation: fromLocation,
986
- pendingLocation: null,
987
- navigationIntent: intent,
988
- phase: "transitioning",
989
- });
990
- if (kind === "push") csrLocation.push({ akanEntryId: toLocation.entryId }, href);
991
- else csrLocation.replace({ akanEntryId: toLocation.entryId }, href);
992
- debugFrame("navigation.commit", { id: intent.id, kind, to: href });
993
- window.setTimeout(
994
- () => {
995
- setTransitionPageStateSnapshot(null);
996
- setLocationState((current) => ({
997
- ...current,
998
-
999
- prevLocation: getPrevLocation(),
1000
- pendingLocation: null,
1001
- navigationIntent: null,
1002
- phase: "idle",
1003
- }));
1004
- navigationLocked.current = false;
1005
- clearPendingSlots();
1006
- debugFrame("transition.actionEnd", { id: plan.id, phase: "idle" });
1007
- const waiting = waitingNavigation.current;
1008
- waitingNavigation.current = null;
1009
- if (waiting) latestRouter.current[waiting.kind](waiting.href, { scrollToTop: waiting.scrollToTop });
1010
- },
1011
- Math.max(360, plan.duration),
1012
- );
1013
- };
1014
-
1015
- const waitUntilReady = () => {
1016
- if (pendingNavigation.current !== intent) return;
1017
- const elapsedMs = Date.now() - intent.createdAt;
1018
- const ready = isPendingFrameReady({
1019
- path: toLocation.pathRoute.path,
1020
- pendingFrameSlots: latestPendingFrameSlots.current,
1021
- elapsedMs,
1022
- });
1023
- if (ready) {
1024
- void commitNavigation(elapsedMs >= PENDING_FRAME_READY_TIMEOUT_MS);
1025
- return;
1026
- }
1027
- window.setTimeout(waitUntilReady, 16);
1028
- };
1029
- window.setTimeout(waitUntilReady, 16);
1030
- },
1031
- [
1032
- clearPendingSlots,
1033
- broadcastSyncNavigation,
1034
- getCurrentLocation,
1035
- getLocation,
1036
- getPrevLocation,
1037
- prevLocation,
1038
- promotePendingSlots,
1039
- setHistoryForward,
1040
- shouldPrepareFrameTransition,
1041
- viewport,
1042
- ],
1043
- );
1044
- renderCountRef.current += 1;
1045
- if (renderCountRef.current <= 5 || renderCountRef.current % 20 === 0) {
1046
- debugFrame("csr.render", {
1047
- count: renderCountRef.current,
1048
- path: resolvedLocation.pathRoute.path,
1049
- href: resolvedLocation.href,
1050
- viewport,
1051
- keyboardFrame,
1052
- contentViewport: keyboardLayout.contentViewport,
1053
- keyboardAccessory: keyboardLayout.keyboardAccessory,
1054
- frameSlotPaths: Object.keys(frameSlots),
1055
- });
1056
- }
1057
- useEffect(() => {
1058
- debugFrame("keyboard.layoutResolve", {
1059
- path: resolvedLocation.pathRoute.path,
1060
- keyboardHeight: keyboardFrame.height,
1061
- visualHeight: viewport.visualHeight,
1062
- visualOffsetTop: viewport.visualOffsetTop,
1063
- contentViewport: keyboardLayout.contentViewport,
1064
- accessory: keyboardLayout.keyboardAccessory,
1065
- slotHeight: accessoryHeight,
1066
- platformProfile,
1067
- frozen: keyboardFrame.frozen,
1068
- source: keyboardFrame.source,
1069
- });
1070
- }, [
1071
- resolvedLocation.pathRoute.path,
1072
- keyboardFrame.height,
1073
- keyboardFrame.offset,
1074
- keyboardFrame.frozen,
1075
- keyboardFrame.source,
1076
- viewport.visualHeight,
1077
- viewport.visualOffsetTop,
1078
- keyboardLayout,
1079
- accessoryHeight,
1080
- platformProfile,
1081
- ]);
1082
- useEffect(() => {
1083
- debugFrame("csr.mount", { path: resolvedLocation.pathRoute.path, viewport });
1084
- csrLocation.replace({ ...((csrLocation.state as object | null) ?? {}), akanEntryId: getCurrentLocation().entryId });
1085
- return () => debugFrame("csr.unmount", { lastPath: getCurrentLocation().pathRoute.path });
1086
- }, []);
41
+ const { getLocation, getCurrentLocation, getPrevLocation, getNextLocation, getScrollTop, history, location } = nav;
42
+ const { setHistoryForward, setHistoryBack, setHistoryJump } = nav;
43
+ const { cancelPendingNavigation, runForwardNavigation, broadcastSyncNavigation, settle } = navigation;
44
+ const { shouldPrepareFrameTransition, startFrameTransition } = navigation;
1087
45
  const getRouter = useCallback((): RouterInstance => {
46
+ const playBack = (transition: TransitionType) => onBack.current[transition]?.();
1088
47
  const forward =
1089
48
  (kind: "push" | "replace") =>
1090
49
  (href: string, { scrollToTop }: RouteOptions = {}) => {
@@ -1104,8 +63,8 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1104
63
  return;
1105
64
  }
1106
65
  if (pendingNavigation.current?.to.href === href) return;
1107
-
1108
- const cancelled = cancelPendingNavigation();
66
+
67
+ const cancelled: NavigationIntent | null = cancelPendingNavigation();
1109
68
  if (location.href === href) {
1110
69
  if (!pageContentRef.current) return;
1111
70
  pageContentRef.current.scrollTop = getScrollTop(location);
@@ -1117,7 +76,9 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1117
76
  push: forward("push"),
1118
77
  replace: forward("replace"),
1119
78
  refresh: () => {
1120
- csrLocation.reload();
79
+ const location = getCurrentLocation();
80
+ debugFrame("router.refresh", { href: location.href });
81
+ CsrRefresh.request(location);
1121
82
  },
1122
83
  back: async ({ scrollToTop }: RouteOptions = {}) => {
1123
84
  waitingNavigation.current = null;
@@ -1130,7 +91,7 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1130
91
 
1131
92
  broadcastSyncNavigation("back", getSyncRouteHref(targetLocation));
1132
93
  if (shouldPrepareFrameTransition()) await startFrameTransition();
1133
- await onBack.current[location.pathRoute.pageState.transition]?.();
94
+ await playBack(location.pathRoute.pageState.transition);
1134
95
  const scrollTop = pageContentRef.current?.scrollTop ?? 0;
1135
96
  setHistoryBack({ type: "back", location, scrollTop, scrollToTop });
1136
97
  settle(getPrevLocation());
@@ -1179,7 +140,7 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1179
140
  } else {
1180
141
  const location = getCurrentLocation();
1181
142
  if (shouldPrepareFrameTransition(href)) await startFrameTransition();
1182
- if (!isUaAnimated) await onBack.current[location.pathRoute.pageState.transition]?.();
143
+ if (!isUaAnimated) await playBack(location.pathRoute.pageState.transition);
1183
144
  setHistoryBack({ type: "popBack", location, scrollTop });
1184
145
  settle(getPrevLocation());
1185
146
  }
@@ -1187,67 +148,48 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1187
148
  return router;
1188
149
  }, [location, runForwardNavigation, cancelPendingNavigation, broadcastSyncNavigation, shouldPrepareFrameTransition]);
1189
150
  const liveRouter = getRouter();
1190
- const latestRouter = useRef(liveRouter);
1191
151
  latestRouter.current = liveRouter;
1192
152
 
1193
153
  const [router] = useState<RouterInstance>(() => ({
1194
- push: (href, routeOptions) => latestRouter.current.push(href, routeOptions),
1195
- replace: (href, routeOptions) => latestRouter.current.replace(href, routeOptions),
1196
- back: (routeOptions) => latestRouter.current.back(routeOptions),
1197
- refresh: () => latestRouter.current.refresh(),
154
+ push: (href, routeOptions) => currentRouter(latestRouter).push(href, routeOptions),
155
+ replace: (href, routeOptions) => currentRouter(latestRouter).replace(href, routeOptions),
156
+ back: (routeOptions) => currentRouter(latestRouter).back(routeOptions),
157
+ refresh: () => currentRouter(latestRouter).refresh(),
1198
158
  }));
1199
- useEffect(() => {
1200
- const syncHref = getSyncRouteHref(resolvedLocation);
1201
- if (
1202
- lastBroadcastSyncHref.current === null ||
1203
- applyingSyncNavigation.current ||
1204
- globalThis.__AKAN_DEV_SYNC_NAVIGATION_APPLYING__
1205
- ) {
1206
- lastBroadcastSyncHref.current = syncHref;
1207
- return;
1208
- }
1209
- broadcastSyncNavigation(
1210
- history.current.type === "back" ? "back" : history.current.type === "forward" ? "push" : "pop",
1211
- syncHref,
1212
- );
1213
- }, [
1214
- resolvedLocation.pathRoute.path,
1215
- resolvedLocation.search,
1216
- resolvedLocation.hash,
1217
- broadcastSyncNavigation,
1218
- history,
1219
- ]);
1220
- useEffect(() => {
1221
-
1222
- const resetSyncNavigation = () => {
1223
- if (syncNavigationReset.current) clearTimeout(syncNavigationReset.current);
1224
- syncNavigationReset.current = setTimeout(() => {
1225
- applyingSyncNavigation.current = false;
1226
- globalThis.__AKAN_DEV_SYNC_NAVIGATION_APPLYING__ = false;
1227
- }, 1000);
1228
- };
1229
- const handleSyncNavigation = (event: Event) => {
1230
- const { href, kind = "push" } =
1231
- (event as CustomEvent<{ href?: string; kind?: "push" | "replace" | "back" | "pop" }>).detail ?? {};
1232
- if (!href) return;
1233
- const target = new URL(href, window.location.origin);
1234
- const targetHref = `${target.pathname}${target.search}${target.hash}`;
1235
-
1236
- if (targetHref === getSyncRouteHref(getCurrentLocation()) || targetHref === lastBroadcastSyncHref.current) return;
1237
- applyingSyncNavigation.current = true;
1238
- globalThis.__AKAN_DEV_SYNC_NAVIGATION_APPLYING__ = true;
1239
- const previous = getPrevLocation();
1240
-
1241
- if (kind !== "push" && kind !== "replace" && previous && getSyncRouteHref(previous) === targetHref)
1242
- clientRouter.back({ scrollToTop: false });
1243
- else if (kind === "replace" || kind === "back" || kind === "pop")
1244
- clientRouter.replace(targetHref, { scrollToTop: false });
1245
- else clientRouter.push(targetHref, { scrollToTop: false });
1246
- resetSyncNavigation();
1247
- };
1248
- window.addEventListener("akan:sync-navigation", handleSyncNavigation);
1249
- return () => window.removeEventListener("akan:sync-navigation", handleSyncNavigation);
1250
- }, [getCurrentLocation, getPrevLocation, router]);
159
+ return router;
160
+ };
161
+
162
+ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]) => {
163
+ const { viewport, updateViewport } = useFrameViewport();
164
+ const slots = useFrameSlots();
165
+ const [transitionPageStateSnapshot, setTransitionPageStateSnapshot] = useState<Map<string, PageState> | null>(null);
166
+ const refs = useCsrRefs();
167
+ const nav = useCsrLocationState(rootRouteGuide);
168
+ const frame = useResolvedFrame({ pathRoutes, slots, transitionPageStateSnapshot, refs, nav });
169
+ const keyboard = useCsrKeyboard({
170
+ viewport,
171
+ updateViewport,
172
+ frameSlots: slots.frameSlots,
173
+ phase: nav.phase,
174
+ resolvedLocation: frame.resolvedLocation,
175
+ pageContentRef: refs.pageContentRef,
176
+ });
177
+ const navigation = useCsrNavigation({ viewport, slots, setTransitionPageStateSnapshot, refs, nav, frame, keyboard });
178
+ useCsrRenderTrace({ viewport, frameSlots: slots.frameSlots, refs, nav, frame, keyboard });
179
+ const router = useCsrRouter({ refs, nav, navigation });
180
+ useSyncNavigation({
181
+ refs,
182
+ nav,
183
+ resolvedLocation: frame.resolvedLocation,
184
+ broadcastSyncNavigation: navigation.broadcastSyncNavigation,
185
+ router,
186
+ });
187
+ const { registerFrameSlot } = slots;
188
+ const { topSafeAreaRef, bottomSafeAreaRef, prevPageContentRef, pageContentRef, frameRootRef, onBack } = refs;
189
+ const { navigationIntent, phase, isBackgrounded, history } = nav;
190
+ const { resolvedLocation, resolvedPrevLocation, resolvedPendingLocation, stackEntries } = frame;
191
+ const { resolvedPathRoutes, effectivePageStateByPath } = frame;
192
+ const { keyboardFrame, keyboardLayout, shouldAnchorContentBottom, platformProfile } = keyboard;
1251
193
  const routeState: RouteState = {
1252
194
  clientWidth: viewport.width,
1253
195
  clientHeight: viewport.height,
@@ -1279,18 +221,7 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1279
221
  pageStateByPath: effectivePageStateByPath,
1280
222
  },
1281
223
  };
1282
- const useNonTransition = useNoneTrans(routeState);
1283
- const useFadeTransition = useFadeTrans(routeState);
1284
- const useScaleOutTransition = useScaleOutTrans(routeState);
1285
- const useStackTransition = useStackTrans(routeState);
1286
- const useBottomUpTransition = useBottomUpTrans(routeState);
1287
- const useCsrTransitionMap: { [key in TransitionType]: UseCsrTransition } = {
1288
- none: useNonTransition,
1289
- fade: useFadeTransition,
1290
- stack: useStackTransition,
1291
- bottomUp: useBottomUpTransition,
1292
- scaleOut: useScaleOutTransition,
1293
- };
224
+ const useCsrTransitionMap = useCsrTransitions(routeState);
1294
225
 
1295
226
  const contentResizeStyle = useMemo(() => {
1296
227
  if (!shouldAnchorContentBottom || !keyboardFrame.sticky) return null;
@@ -1306,100 +237,7 @@ export const useCsrValues = (rootRouteGuide: RouteGuide, pathRoutes: PathRoute[]
1306
237
  contentResizeStyle && csrTransition.page
1307
238
  ? { ...csrTransition.page, contentStyle: { ...csrTransition.page.contentStyle, ...contentResizeStyle } }
1308
239
  : csrTransition.page;
1309
- const nativeNavigation = useRef<NativeNavigation | null>(null);
1310
- const nativeBackStateRef = useRef({
1311
- path: resolvedLocation.pathRoute.path,
1312
- keyboardHeight: keyboardFrame.height,
1313
- keyboardVisible: keyboardFrame.visible,
1314
- router: clientRouter,
1315
- });
1316
-
1317
- useEffect(() => {
1318
- if (pageContentRef.current) pageContentRef.current.scrollTop = getScrollTop(location);
1319
- if (prevPageContentRef.current)
1320
- prevPageContentRef.current.scrollTop = prevLocation ? getScrollTop(prevLocation) : 0;
1321
- }, [location.href]);
1322
-
1323
- useEffect(() => {
1324
- for (const shown of [location, prevLocation]) if (shown?.entryId) history.current.dormant?.delete(shown.entryId);
1325
- CsrStack.save(history.current);
1326
- }, [location, prevLocation]);
1327
-
1328
- useEffect(() => {
1329
- const sync = () => setIsBackgrounded(document.visibilityState === "hidden");
1330
- document.addEventListener("visibilitychange", sync);
1331
- return () => document.removeEventListener("visibilitychange", sync);
1332
- }, []);
1333
-
1334
- useEffect(() => {
1335
- nativeNavigation.current?.showPushesExcept(location.pathname);
1336
- }, [location.pathname]);
1337
-
1338
- useEffect(() => {
1339
- nativeBackStateRef.current = {
1340
- path: resolvedLocation.pathRoute.path,
1341
- keyboardHeight: keyboardFrame.height,
1342
- keyboardVisible: keyboardFrame.visible,
1343
- router: clientRouter,
1344
- };
1345
- nativeNavigation.current?.syncBack();
1346
- }, [keyboardFrame.height, keyboardFrame.visible, resolvedLocation.pathRoute.path]);
1347
-
1348
- const backFollow = useRef(csrTransition);
1349
- backFollow.current = csrTransition;
1350
- const followBack = useCallback(({ phase, progress }: NativeBackProgress) => {
1351
- const { transUnit, transUnitRange } = backFollow.current;
1352
- const transition = getCurrentLocation().pathRoute.pageState.transition;
1353
- if (transition === "none" || history.current.idx === 0 || nativeBackStateRef.current.keyboardVisible) return;
1354
- const [hidden, shown] = transUnitRange;
1355
- if (phase === "cancelled") {
1356
- void transUnit.start(shown);
1357
- return;
1358
- }
1359
-
1360
- const follow = transition === "stack" || transition === "bottomUp" ? progress : progress / 2;
1361
- void transUnit.start(shown + (hidden - shown) * follow, { immediate: true });
1362
- }, []);
1363
- const [, setReleased] = useState(0);
1364
- const latestStackEntries = useRef(stackEntries);
1365
- latestStackEntries.current = stackEntries;
1366
- const releaseHidden = useCallback(() => {
1367
- history.current.dormant ??= new Set();
1368
- for (const { pageType, location: hidden } of latestStackEntries.current)
1369
- if (pageType === "cached" && hidden.entryId) history.current.dormant.add(hidden.entryId);
1370
- setReleased((count) => count + 1);
1371
- }, []);
1372
- useEffect(() => {
1373
- const redraw = () => {
1374
- if (CsrStack.redrawFor(history.current, getCurrentLocation(), getAuthToken() ?? null))
1375
- setReleased((count) => count + 1);
1376
- };
1377
- redraw();
1378
- window.addEventListener("akan:auth", redraw);
1379
- return () => window.removeEventListener("akan:auth", redraw);
1380
- }, []);
1381
- useEffect(() => {
1382
- if (phase === "idle") CsrStack.leave(history.current, location);
1383
- }, [phase, location]);
1384
-
1385
- useEffect(() => {
1386
- const navigation = new NativeNavigation({
1387
- historyIdx: () => history.current.idx,
1388
- backState: () => nativeBackStateRef.current,
1389
- dismissKeyboard: prepareForFrameTransition,
1390
- onBackProgress: followBack,
1391
- onMemoryWarning: releaseHidden,
1392
- });
1393
- nativeNavigation.current = navigation;
1394
- const stop = navigation.listen();
1395
- navigation.showPushesExcept(getCurrentLocation().pathname);
1396
- const stopUpdates = new NativeUpdates().listen();
1397
- return () => {
1398
- stop();
1399
- stopUpdates();
1400
- nativeNavigation.current = null;
1401
- };
1402
- }, []);
240
+ useCsrStackLifecycle({ refs, nav, frame, keyboard, csrTransition });
1403
241
 
1404
242
  return {
1405
243
  ...routeState,