@ng-native/desktop 0.0.0 → 0.23.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 (393) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +52 -0
  3. package/app.plugin.cjs +17 -0
  4. package/bin/app-config.mjs +168 -0
  5. package/bin/autolink.mjs +224 -0
  6. package/bin/cli.mjs +158 -0
  7. package/bin/host.mjs +427 -0
  8. package/bin/ng-native-desktop.mjs +4 -0
  9. package/bin/package.mjs +971 -0
  10. package/bin/plist.mjs +68 -0
  11. package/bin/prebuilt.mjs +328 -0
  12. package/bin/toolchain.mjs +192 -0
  13. package/native/CMakeLists.txt +276 -0
  14. package/native/appkit/CMakeLists.txt +109 -0
  15. package/native/appkit/address-search.h +26 -0
  16. package/native/appkit/address-search.mm +277 -0
  17. package/native/appkit/animation-frames.h +14 -0
  18. package/native/appkit/animation-frames.mm +106 -0
  19. package/native/appkit/app-info.h +12 -0
  20. package/native/appkit/app-info.mm +98 -0
  21. package/native/appkit/app-updater.mm +128 -0
  22. package/native/appkit/app-windows.h +81 -0
  23. package/native/appkit/app-windows.mm +318 -0
  24. package/native/appkit/appkit-backend.h +73 -0
  25. package/native/appkit/appkit-backend.mm +276 -0
  26. package/native/appkit/apple-authentication.h +19 -0
  27. package/native/appkit/apple-authentication.mm +248 -0
  28. package/native/appkit/apple-button-view.h +10 -0
  29. package/native/appkit/apple-button-view.mm +37 -0
  30. package/native/appkit/apple-id-button.h +16 -0
  31. package/native/appkit/apple-id-button.mm +50 -0
  32. package/native/appkit/audio.h +16 -0
  33. package/native/appkit/audio.mm +275 -0
  34. package/native/appkit/battery.h +13 -0
  35. package/native/appkit/battery.mm +92 -0
  36. package/native/appkit/bookmarks.h +17 -0
  37. package/native/appkit/bookmarks.mm +145 -0
  38. package/native/appkit/calendar.h +25 -0
  39. package/native/appkit/calendar.mm +660 -0
  40. package/native/appkit/camera-view.h +15 -0
  41. package/native/appkit/camera-view.mm +130 -0
  42. package/native/appkit/camera.h +39 -0
  43. package/native/appkit/camera.mm +362 -0
  44. package/native/appkit/cg-canvas.h +17 -0
  45. package/native/appkit/cg-canvas.mm +518 -0
  46. package/native/appkit/component-view.h +17 -0
  47. package/native/appkit/crypto.h +19 -0
  48. package/native/appkit/crypto.mm +78 -0
  49. package/native/appkit/desktop-expo.h +29 -0
  50. package/native/appkit/desktop-expo.mm +385 -0
  51. package/native/appkit/expo-image-drawing.h +46 -0
  52. package/native/appkit/expo-image-drawing.mm +131 -0
  53. package/native/appkit/expo-image-view.h +15 -0
  54. package/native/appkit/expo-image-view.mm +182 -0
  55. package/native/appkit/expo-ui-renderer.h +68 -0
  56. package/native/appkit/expo-ui-renderer.mm +101 -0
  57. package/native/appkit/expo-ui-view.h +26 -0
  58. package/native/appkit/expo-ui-view.mm +134 -0
  59. package/native/appkit/expo-ui.swift +1284 -0
  60. package/native/appkit/file-system.h +16 -0
  61. package/native/appkit/file-system.mm +140 -0
  62. package/native/appkit/fonts.h +12 -0
  63. package/native/appkit/fonts.mm +48 -0
  64. package/native/appkit/geocoder.h +19 -0
  65. package/native/appkit/geocoder.mm +101 -0
  66. package/native/appkit/glass-effect.h +22 -0
  67. package/native/appkit/glass-effect.mm +63 -0
  68. package/native/appkit/glass-view.h +8 -0
  69. package/native/appkit/glass-view.mm +65 -0
  70. package/native/appkit/header-toolbar.h +60 -0
  71. package/native/appkit/header-toolbar.mm +629 -0
  72. package/native/appkit/host-view.h +54 -0
  73. package/native/appkit/host-view.mm +1200 -0
  74. package/native/appkit/image-manipulator.h +14 -0
  75. package/native/appkit/image-manipulator.mm +191 -0
  76. package/native/appkit/image-request.h +22 -0
  77. package/native/appkit/image-request.mm +62 -0
  78. package/native/appkit/image-view.h +8 -0
  79. package/native/appkit/image-view.mm +142 -0
  80. package/native/appkit/input-replay.h +25 -0
  81. package/native/appkit/input-replay.mm +418 -0
  82. package/native/appkit/language-model.h +14 -0
  83. package/native/appkit/language-model.mm +99 -0
  84. package/native/appkit/language-model.swift +472 -0
  85. package/native/appkit/local-authentication.h +15 -0
  86. package/native/appkit/local-authentication.mm +133 -0
  87. package/native/appkit/location.h +16 -0
  88. package/native/appkit/location.mm +214 -0
  89. package/native/appkit/main.mm +1515 -0
  90. package/native/appkit/map-view.h +15 -0
  91. package/native/appkit/map-view.mm +109 -0
  92. package/native/appkit/maps.h +35 -0
  93. package/native/appkit/maps.mm +343 -0
  94. package/native/appkit/menu-bar.h +22 -0
  95. package/native/appkit/menu-bar.mm +208 -0
  96. package/native/appkit/modal-focus.h +16 -0
  97. package/native/appkit/modal-focus.mm +26 -0
  98. package/native/appkit/modal-host-view.h +79 -0
  99. package/native/appkit/modal-host-view.mm +442 -0
  100. package/native/appkit/native-controls.h +22 -0
  101. package/native/appkit/native-controls.mm +431 -0
  102. package/native/appkit/network-state.h +12 -0
  103. package/native/appkit/network-state.mm +64 -0
  104. package/native/appkit/network.h +14 -0
  105. package/native/appkit/network.mm +396 -0
  106. package/native/appkit/notifications.h +19 -0
  107. package/native/appkit/notifications.mm +309 -0
  108. package/native/appkit/photo-library.h +33 -0
  109. package/native/appkit/photo-library.mm +548 -0
  110. package/native/appkit/pointer-buttons.h +32 -0
  111. package/native/appkit/presentation-label.h +15 -0
  112. package/native/appkit/presentation-label.mm +12 -0
  113. package/native/appkit/presented-screen.h +19 -0
  114. package/native/appkit/presented-screen.mm +181 -0
  115. package/native/appkit/printing.h +42 -0
  116. package/native/appkit/printing.mm +393 -0
  117. package/native/appkit/push.h +19 -0
  118. package/native/appkit/push.mm +81 -0
  119. package/native/appkit/red-box.h +26 -0
  120. package/native/appkit/red-box.mm +387 -0
  121. package/native/appkit/screen-capture.h +21 -0
  122. package/native/appkit/screen-capture.mm +92 -0
  123. package/native/appkit/scroll-view.h +13 -0
  124. package/native/appkit/scroll-view.mm +251 -0
  125. package/native/appkit/scrollers.h +25 -0
  126. package/native/appkit/scrollers.mm +43 -0
  127. package/native/appkit/search-field.h +34 -0
  128. package/native/appkit/search-field.mm +291 -0
  129. package/native/appkit/search-toolbar-item.h +19 -0
  130. package/native/appkit/search-toolbar-item.mm +269 -0
  131. package/native/appkit/share-picker.h +34 -0
  132. package/native/appkit/share-picker.mm +121 -0
  133. package/native/appkit/split-view.h +77 -0
  134. package/native/appkit/split-view.mm +1206 -0
  135. package/native/appkit/store-review.h +13 -0
  136. package/native/appkit/store-review.mm +28 -0
  137. package/native/appkit/surface-view.h +45 -0
  138. package/native/appkit/surface-view.mm +558 -0
  139. package/native/appkit/svg-view.h +17 -0
  140. package/native/appkit/svg-view.mm +57 -0
  141. package/native/appkit/symbol-drawing.h +24 -0
  142. package/native/appkit/symbol-drawing.mm +117 -0
  143. package/native/appkit/symbol-view.h +8 -0
  144. package/native/appkit/symbol-view.mm +33 -0
  145. package/native/appkit/system-access.h +34 -0
  146. package/native/appkit/system-access.mm +210 -0
  147. package/native/appkit/system.h +24 -0
  148. package/native/appkit/system.mm +403 -0
  149. package/native/appkit/test-launch.h +36 -0
  150. package/native/appkit/test-launch.mm +115 -0
  151. package/native/appkit/text-input-field.h +76 -0
  152. package/native/appkit/text-input-field.mm +444 -0
  153. package/native/appkit/text-layout.h +58 -0
  154. package/native/appkit/text-layout.mm +477 -0
  155. package/native/appkit/text-recognition.h +13 -0
  156. package/native/appkit/text-recognition.mm +102 -0
  157. package/native/appkit/tracking.h +13 -0
  158. package/native/appkit/tracking.mm +51 -0
  159. package/native/appkit/tray-and-dock.h +45 -0
  160. package/native/appkit/tray-and-dock.mm +130 -0
  161. package/native/appkit/undo.h +23 -0
  162. package/native/appkit/undo.mm +125 -0
  163. package/native/appkit/updates.h +17 -0
  164. package/native/appkit/updates.mm +71 -0
  165. package/native/appkit/video-view.h +10 -0
  166. package/native/appkit/video-view.mm +42 -0
  167. package/native/appkit/video.h +38 -0
  168. package/native/appkit/video.mm +404 -0
  169. package/native/appkit/web-browser.h +12 -0
  170. package/native/appkit/web-browser.mm +97 -0
  171. package/native/appkit/web-view-component.h +9 -0
  172. package/native/appkit/web-view-component.mm +56 -0
  173. package/native/appkit/web-view.h +31 -0
  174. package/native/appkit/web-view.mm +394 -0
  175. package/native/cmake/libraries/react-native-reanimated.cmake +45 -0
  176. package/native/cmake/libraries/react-native-worklets.cmake +46 -0
  177. package/native/cmake/libraries.cmake +109 -0
  178. package/native/cmake/linked-modules.cmake +112 -0
  179. package/native/cmake/react-native.cmake +175 -0
  180. package/native/cmake/runtime-dependencies.cmake +34 -0
  181. package/native/cmake/swift.cmake +43 -0
  182. package/native/cmake/third-party.cmake +74 -0
  183. package/native/core/include/ngn/absent-views.h +27 -0
  184. package/native/core/include/ngn/accessibility.h +140 -0
  185. package/native/core/include/ngn/address-search.h +69 -0
  186. package/native/core/include/ngn/animation-frames.h +39 -0
  187. package/native/core/include/ngn/app-info.h +52 -0
  188. package/native/core/include/ngn/app-menus.h +146 -0
  189. package/native/core/include/ngn/app-windows.h +181 -0
  190. package/native/core/include/ngn/apple-authentication.h +116 -0
  191. package/native/core/include/ngn/asset.h +28 -0
  192. package/native/core/include/ngn/audio.h +125 -0
  193. package/native/core/include/ngn/back-swipe.h +112 -0
  194. package/native/core/include/ngn/battery.h +48 -0
  195. package/native/core/include/ngn/bytes.h +59 -0
  196. package/native/core/include/ngn/calendar.h +180 -0
  197. package/native/core/include/ngn/camera.h +128 -0
  198. package/native/core/include/ngn/control-sizes.h +111 -0
  199. package/native/core/include/ngn/core-modules.h +105 -0
  200. package/native/core/include/ngn/crypto.h +38 -0
  201. package/native/core/include/ngn/default-menu.h +91 -0
  202. package/native/core/include/ngn/desktop-expo.h +193 -0
  203. package/native/core/include/ngn/desktop-modal.h +109 -0
  204. package/native/core/include/ngn/desktop-props.h +75 -0
  205. package/native/core/include/ngn/desktop-view-props.h +110 -0
  206. package/native/core/include/ngn/dev-server.h +33 -0
  207. package/native/core/include/ngn/download.h +24 -0
  208. package/native/core/include/ngn/expo-image.h +192 -0
  209. package/native/core/include/ngn/expo-ui.h +133 -0
  210. package/native/core/include/ngn/file-system.h +274 -0
  211. package/native/core/include/ngn/focus-order.h +63 -0
  212. package/native/core/include/ngn/fonts.h +64 -0
  213. package/native/core/include/ngn/gestures.h +305 -0
  214. package/native/core/include/ngn/glass.h +67 -0
  215. package/native/core/include/ngn/header-bar.h +112 -0
  216. package/native/core/include/ngn/host-state.h +243 -0
  217. package/native/core/include/ngn/image-manipulator.h +70 -0
  218. package/native/core/include/ngn/input-dispatcher.h +211 -0
  219. package/native/core/include/ngn/input-script.h +56 -0
  220. package/native/core/include/ngn/input.h +112 -0
  221. package/native/core/include/ngn/key-value-store.h +41 -0
  222. package/native/core/include/ngn/language-model.h +69 -0
  223. package/native/core/include/ngn/launch-frame.h +47 -0
  224. package/native/core/include/ngn/launch-settings.h +98 -0
  225. package/native/core/include/ngn/layout-animations.h +24 -0
  226. package/native/core/include/ngn/library-components.h +13 -0
  227. package/native/core/include/ngn/library-glue.h +53 -0
  228. package/native/core/include/ngn/live-regions.h +54 -0
  229. package/native/core/include/ngn/local-authentication.h +74 -0
  230. package/native/core/include/ngn/location.h +89 -0
  231. package/native/core/include/ngn/maps.h +226 -0
  232. package/native/core/include/ngn/module-registry.h +51 -0
  233. package/native/core/include/ngn/mounting-backend.h +96 -0
  234. package/native/core/include/ngn/mounting-manager.h +155 -0
  235. package/native/core/include/ngn/native-controls.h +161 -0
  236. package/native/core/include/ngn/native-module.h +109 -0
  237. package/native/core/include/ngn/network-state.h +44 -0
  238. package/native/core/include/ngn/network.h +100 -0
  239. package/native/core/include/ngn/notifications.h +185 -0
  240. package/native/core/include/ngn/photo-library.h +130 -0
  241. package/native/core/include/ngn/printing.h +69 -0
  242. package/native/core/include/ngn/processes.h +114 -0
  243. package/native/core/include/ngn/red-box.h +119 -0
  244. package/native/core/include/ngn/reload-thread.h +258 -0
  245. package/native/core/include/ngn/runtime.h +161 -0
  246. package/native/core/include/ngn/safe-areas.h +77 -0
  247. package/native/core/include/ngn/screen-capture.h +35 -0
  248. package/native/core/include/ngn/screen-presentation.h +85 -0
  249. package/native/core/include/ngn/screen-stacks.h +80 -0
  250. package/native/core/include/ngn/scrollers.h +106 -0
  251. package/native/core/include/ngn/sharing.h +39 -0
  252. package/native/core/include/ngn/spawn-rules.h +78 -0
  253. package/native/core/include/ngn/splash-screen.h +41 -0
  254. package/native/core/include/ngn/split-view.h +270 -0
  255. package/native/core/include/ngn/sqlite.h +38 -0
  256. package/native/core/include/ngn/store-review.h +26 -0
  257. package/native/core/include/ngn/surface-book.h +101 -0
  258. package/native/core/include/ngn/svg.h +393 -0
  259. package/native/core/include/ngn/symbol.h +90 -0
  260. package/native/core/include/ngn/system.h +102 -0
  261. package/native/core/include/ngn/tabs-host.h +171 -0
  262. package/native/core/include/ngn/text-input.h +125 -0
  263. package/native/core/include/ngn/text-measurer.h +38 -0
  264. package/native/core/include/ngn/text-recognition.h +55 -0
  265. package/native/core/include/ngn/tracking.h +34 -0
  266. package/native/core/include/ngn/tray-and-dock.h +107 -0
  267. package/native/core/include/ngn/undo.h +37 -0
  268. package/native/core/include/ngn/updates.h +253 -0
  269. package/native/core/include/ngn/video.h +126 -0
  270. package/native/core/include/ngn/view-box.h +126 -0
  271. package/native/core/include/ngn/view-transform.h +26 -0
  272. package/native/core/include/ngn/view-tree.h +85 -0
  273. package/native/core/include/ngn/web-browser.h +45 -0
  274. package/native/core/include/ngn/web-view.h +133 -0
  275. package/native/core/include/ngn/worklet-host.h +98 -0
  276. package/native/core/src/absent-views.cpp +41 -0
  277. package/native/core/src/accessibility.cpp +374 -0
  278. package/native/core/src/animation-frames.cpp +49 -0
  279. package/native/core/src/app-menus.cpp +352 -0
  280. package/native/core/src/app-windows.cpp +444 -0
  281. package/native/core/src/back-swipe.cpp +91 -0
  282. package/native/core/src/bytes.cpp +158 -0
  283. package/native/core/src/control-sizes.cpp +232 -0
  284. package/native/core/src/default-menu.cpp +96 -0
  285. package/native/core/src/desktop-modal.cpp +162 -0
  286. package/native/core/src/desktop-view-props.cpp +80 -0
  287. package/native/core/src/dev-server-helper.cpp +152 -0
  288. package/native/core/src/dev-server.cpp +103 -0
  289. package/native/core/src/download.cpp +53 -0
  290. package/native/core/src/expo-image.cpp +548 -0
  291. package/native/core/src/expo-ui.cpp +203 -0
  292. package/native/core/src/focus-order.cpp +441 -0
  293. package/native/core/src/gestures.cpp +1806 -0
  294. package/native/core/src/glass.cpp +49 -0
  295. package/native/core/src/header-bar.cpp +104 -0
  296. package/native/core/src/host-services.cpp +50 -0
  297. package/native/core/src/host-state.cpp +61 -0
  298. package/native/core/src/input-dispatcher.cpp +727 -0
  299. package/native/core/src/input-script.cpp +123 -0
  300. package/native/core/src/key-value-store.cpp +169 -0
  301. package/native/core/src/launch-settings.cpp +148 -0
  302. package/native/core/src/layout-animations.cpp +62 -0
  303. package/native/core/src/libraries/RNCWebViewSpec.cpp +80 -0
  304. package/native/core/src/libraries/react-native-reanimated.cpp +216 -0
  305. package/native/core/src/libraries/react-native-worklets.cpp +192 -0
  306. package/native/core/src/libraries/rnscreens.cpp +125 -0
  307. package/native/core/src/libraries/rnsvg.cpp +345 -0
  308. package/native/core/src/libraries/safeareacontext.cpp +70 -0
  309. package/native/core/src/libraries/worklets-idle-frames.js +70 -0
  310. package/native/core/src/library-glue.cpp +35 -0
  311. package/native/core/src/live-regions.cpp +122 -0
  312. package/native/core/src/module-registry.cpp +50 -0
  313. package/native/core/src/modules/accessibility-manager.cpp +98 -0
  314. package/native/core/src/modules/address-search.cpp +219 -0
  315. package/native/core/src/modules/alert-manager.cpp +140 -0
  316. package/native/core/src/modules/app-info.cpp +74 -0
  317. package/native/core/src/modules/app-modules.cpp +405 -0
  318. package/native/core/src/modules/apple-authentication.cpp +188 -0
  319. package/native/core/src/modules/asset.cpp +111 -0
  320. package/native/core/src/modules/async-storage.cpp +192 -0
  321. package/native/core/src/modules/audio.cpp +541 -0
  322. package/native/core/src/modules/battery.cpp +88 -0
  323. package/native/core/src/modules/calendar.cpp +457 -0
  324. package/native/core/src/modules/camera.cpp +221 -0
  325. package/native/core/src/modules/core-modules.cpp +62 -0
  326. package/native/core/src/modules/crypto.cpp +117 -0
  327. package/native/core/src/modules/desktop-expo.cpp +527 -0
  328. package/native/core/src/modules/file-system.cpp +941 -0
  329. package/native/core/src/modules/fonts.cpp +163 -0
  330. package/native/core/src/modules/image-loader.cpp +105 -0
  331. package/native/core/src/modules/image-manipulator.cpp +305 -0
  332. package/native/core/src/modules/language-model.cpp +195 -0
  333. package/native/core/src/modules/local-authentication.cpp +140 -0
  334. package/native/core/src/modules/location.cpp +186 -0
  335. package/native/core/src/modules/maps.cpp +500 -0
  336. package/native/core/src/modules/network-state.cpp +72 -0
  337. package/native/core/src/modules/networking.cpp +387 -0
  338. package/native/core/src/modules/notifications.cpp +549 -0
  339. package/native/core/src/modules/photo-library.cpp +371 -0
  340. package/native/core/src/modules/printing.cpp +201 -0
  341. package/native/core/src/modules/screen-capture.cpp +71 -0
  342. package/native/core/src/modules/sharing.cpp +59 -0
  343. package/native/core/src/modules/splash-screen.cpp +70 -0
  344. package/native/core/src/modules/sqlite.cpp +421 -0
  345. package/native/core/src/modules/store-review.cpp +23 -0
  346. package/native/core/src/modules/text-recognition.cpp +107 -0
  347. package/native/core/src/modules/tracking.cpp +46 -0
  348. package/native/core/src/modules/undo.cpp +59 -0
  349. package/native/core/src/modules/video.cpp +366 -0
  350. package/native/core/src/modules/web-browser.cpp +100 -0
  351. package/native/core/src/modules/web-socket.cpp +266 -0
  352. package/native/core/src/mounting-manager.cpp +380 -0
  353. package/native/core/src/native-controls.cpp +129 -0
  354. package/native/core/src/native-module.cpp +250 -0
  355. package/native/core/src/network.cpp +219 -0
  356. package/native/core/src/posix-launcher.cpp +366 -0
  357. package/native/core/src/processes.cpp +324 -0
  358. package/native/core/src/red-box-errors.js +83 -0
  359. package/native/core/src/red-box.cpp +306 -0
  360. package/native/core/src/runtime.cpp +422 -0
  361. package/native/core/src/safe-areas.cpp +130 -0
  362. package/native/core/src/screen-presentation.cpp +61 -0
  363. package/native/core/src/screen-stacks.cpp +254 -0
  364. package/native/core/src/scrollers.cpp +181 -0
  365. package/native/core/src/spawn-rules.cpp +292 -0
  366. package/native/core/src/split-view.cpp +343 -0
  367. package/native/core/src/svg.cpp +1883 -0
  368. package/native/core/src/symbol.cpp +94 -0
  369. package/native/core/src/tabs-host.cpp +234 -0
  370. package/native/core/src/text-input.cpp +126 -0
  371. package/native/core/src/text-layout-manager.cpp +63 -0
  372. package/native/core/src/tray-and-dock.cpp +154 -0
  373. package/native/core/src/updates.cpp +965 -0
  374. package/native/core/src/view-box.cpp +788 -0
  375. package/native/core/src/view-transform.cpp +45 -0
  376. package/native/core/src/view-tree.cpp +234 -0
  377. package/native/core/src/web-view.cpp +143 -0
  378. package/native/core/src/worklet-host.cpp +10 -0
  379. package/native/scripts/build-hermes.sh +44 -0
  380. package/native/scripts/build.sh +171 -0
  381. package/native/scripts/cache-dir.sh +18 -0
  382. package/native/scripts/codegen-library.sh +193 -0
  383. package/native/scripts/compiler-launcher.sh +17 -0
  384. package/native/scripts/fetch.sh +174 -0
  385. package/native/scripts/hermes-built.sh +10 -0
  386. package/native/scripts/host-dir.sh +16 -0
  387. package/native/scripts/macos-target.sh +8 -0
  388. package/native/scripts/make-prebuilt.mjs +360 -0
  389. package/native/scripts/prebuilt-host-cache.mjs +158 -0
  390. package/native/shim/openssl/sha.h +22 -0
  391. package/native/shim/view-platform/react/renderer/components/view/HostPlatformViewTraitsInitializer.h +37 -0
  392. package/package.json +73 -1
  393. package/prebuilt.json +33 -0
@@ -0,0 +1,1284 @@
1
+ // The SwiftUI half of `@expo/ui` on macOS: a HostView's tree (ngn/expo-ui.h) drawn as the SwiftUI
2
+ // views expo/ui draws for the same names and props on iOS, in an NSHostingController's view, behind
3
+ // a C interface that expo-ui-view.mm adapts to the HostView's NGNView.
4
+ //
5
+ // The tree arrives as JSON: `{tag, name, props, children}` per view. A control keeps what the user
6
+ // set until its prop changes, as expo/ui's views keep `@State` seeded from their props, and sends
7
+ // its event at once from the binding's setter, with expo/ui's iOS event name and payload.
8
+ // `ngn_ui_host_perform` acts on a control as the user would, through the same path.
9
+ import AppKit
10
+ import Charts
11
+ import SwiftUI
12
+
13
+ // The context, the view's tag, the event's name (expo/ui's, without `on`) and its payload as JSON.
14
+ public typealias NGNUIEvent = @convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<CChar>, UnsafePointer<CChar>) -> Void
15
+ // The context and an RNHostView's tag: its NSView, unretained, or null.
16
+ public typealias NGNUIViewForTag = @convention(c) (UnsafeMutableRawPointer?, Int32) -> UnsafeMutableRawPointer?
17
+
18
+ // MARK: - The tree
19
+
20
+ final class UINode {
21
+ let tag: Int
22
+ let name: String
23
+ let props: [String: Any]
24
+ let children: [UINode]
25
+
26
+ init?(_ json: Any) {
27
+ guard let object = json as? [String: Any], let tag = object["tag"] as? Int, let name = object["name"] as? String else {
28
+ return nil
29
+ }
30
+ self.tag = tag
31
+ self.name = name
32
+ props = object["props"] as? [String: Any] ?? [:]
33
+ children = (object["children"] as? [Any] ?? []).compactMap(UINode.init)
34
+ }
35
+
36
+ func string(_ key: String) -> String? { props[key] as? String }
37
+ func number(_ key: String) -> Double? { (props[key] as? NSNumber).flatMap { uiIsBool($0) ? nil : $0.doubleValue } }
38
+ func bool(_ key: String) -> Bool? { (props[key] as? NSNumber).map(\.boolValue) }
39
+
40
+ var modifiers: [[String: Any]] { props["modifiers"] as? [[String: Any]] ?? [] }
41
+ var isSlot: Bool { name == "SlotView" }
42
+ var slotName: String? { isSlot ? string("name") : nil }
43
+
44
+ func slot(_ name: String) -> UINode? { children.first { $0.slotName == name } }
45
+ var withoutSlots: [UINode] { children.filter { !$0.isSlot } }
46
+
47
+ func find(_ tag: Int) -> UINode? {
48
+ if self.tag == tag { return self }
49
+ for child in children {
50
+ if let found = child.find(tag) { return found }
51
+ }
52
+ return nil
53
+ }
54
+
55
+ func all(_ into: inout [Int: UINode]) {
56
+ into[tag] = self
57
+ children.forEach { $0.all(&into) }
58
+ }
59
+ }
60
+
61
+ final class UIStore: ObservableObject {
62
+ @Published private(set) var root: UINode?
63
+ // What the user set on a view, by tag and prop, until the prop changes.
64
+ private var local: [Int: [String: Any]] = [:]
65
+ var emit: (Int, String, [String: Any]) -> Void = { _, _, _ in }
66
+ var viewForTag: (Int) -> NSView? = { _ in nil }
67
+
68
+ func set(_ root: UINode?) {
69
+ var before: [Int: UINode] = [:]
70
+ self.root?.all(&before)
71
+ var after: [Int: UINode] = [:]
72
+ root?.all(&after)
73
+ for (tag, values) in local {
74
+ guard let now = after[tag], let was = before[tag] else {
75
+ local[tag] = nil
76
+ continue
77
+ }
78
+ for key in values.keys where !same(was.props[key], now.props[key]) {
79
+ // A slider's value that echoes one of the user's earlier moves is an older update: the
80
+ // later moves stay. Echoes come in the order of the moves, so the oldest move with the
81
+ // value is the one echoed, even when the user came back to it later.
82
+ if key == "value", let sent = values["sent"] as? [Double], let echoed = (now.props[key] as? NSNumber)?.doubleValue,
83
+ let at = sent.firstIndex(of: echoed), at < sent.count - 1 {
84
+ local[tag]?["sent"] = Array(sent[(at + 1)...])
85
+ continue
86
+ }
87
+ local[tag]?[key] = nil
88
+ if key == "value" { local[tag]?["sent"] = nil }
89
+ }
90
+ }
91
+ self.root = root
92
+ }
93
+
94
+ private func same(_ a: Any?, _ b: Any?) -> Bool {
95
+ switch (a, b) {
96
+ case (nil, nil): return true
97
+ case let (a?, b?): return (a as AnyObject).isEqual(b)
98
+ default: return false
99
+ }
100
+ }
101
+
102
+ func value(_ node: UINode, _ key: String) -> Any? { local[node.tag]?[key] ?? node.props[key] }
103
+
104
+ // Kept for the view without being drawn or sent: what reconciling needs.
105
+ func remember(_ node: UINode, _ key: String, _ value: Any) { local[node.tag, default: [:]][key] = value }
106
+
107
+ // The user set `key`: kept, drawn and sent as `event` with `payload`.
108
+ func user(_ node: UINode, _ key: String, _ value: Any, event: String, payload: [String: Any]) {
109
+ local[node.tag, default: [:]][key] = value
110
+ objectWillChange.send()
111
+ emit(node.tag, event, payload)
112
+ }
113
+ }
114
+
115
+ // MARK: - Values
116
+
117
+ // Whether a JSON value is a boolean: Swift's `is Bool` also takes any NSNumber that is 0 or 1.
118
+ func uiIsBool(_ number: NSNumber) -> Bool { CFGetTypeID(number) == CFBooleanGetTypeID() }
119
+
120
+ func uiColor(_ value: Any?) -> Color? {
121
+ if let number = value as? NSNumber, !uiIsBool(number) {
122
+ // React Native's processed colour: 0xAARRGGBB.
123
+ let argb = number.uint32Value
124
+ return Color(.sRGB, red: Double((argb >> 16) & 0xff) / 255, green: Double((argb >> 8) & 0xff) / 255,
125
+ blue: Double(argb & 0xff) / 255, opacity: Double((argb >> 24) & 0xff) / 255)
126
+ }
127
+ guard let text = (value as? String)?.trimmingCharacters(in: .whitespaces).lowercased() else { return nil }
128
+ if text.hasPrefix("#") {
129
+ var hex = String(text.dropFirst())
130
+ if hex.count == 3 || hex.count == 4 { hex = hex.map { "\($0)\($0)" }.joined() }
131
+ guard hex.count == 6 || hex.count == 8, let raw = UInt64(hex, radix: 16) else { return nil }
132
+ let rgba = hex.count == 6 ? (raw << 8) | 0xff : raw
133
+ return Color(.sRGB, red: Double((rgba >> 24) & 0xff) / 255, green: Double((rgba >> 16) & 0xff) / 255,
134
+ blue: Double((rgba >> 8) & 0xff) / 255, opacity: Double(rgba & 0xff) / 255)
135
+ }
136
+ let named: [String: Color] = [
137
+ "red": .red, "orange": .orange, "yellow": .yellow, "green": .green, "mint": .mint, "teal": .teal, "cyan": .cyan,
138
+ "blue": .blue, "indigo": .indigo, "purple": .purple, "pink": .pink, "brown": .brown, "white": .white,
139
+ "gray": .gray, "grey": .gray, "black": .black, "clear": .clear, "transparent": .clear, "primary": .primary,
140
+ "secondary": .secondary, "accentcolor": .accentColor,
141
+ ]
142
+ return named[text]
143
+ }
144
+
145
+ func uiHex(_ color: Color) -> String {
146
+ let ns = NSColor(color).usingColorSpace(.sRGB) ?? .black
147
+ let parts = [ns.redComponent, ns.greenComponent, ns.blueComponent, ns.alphaComponent].map { Int(($0 * 255).rounded()) }
148
+ return String(format: "#%02X%02X%02X%02X", parts[0], parts[1], parts[2], parts[3])
149
+ }
150
+
151
+ func uiDate(_ value: Any?) -> Date? {
152
+ if let number = value as? NSNumber, !uiIsBool(number) { return Date(timeIntervalSince1970: number.doubleValue / 1000) }
153
+ guard let text = value as? String else { return nil }
154
+ let full = ISO8601DateFormatter()
155
+ full.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
156
+ return full.date(from: text) ?? ISO8601DateFormatter().date(from: text)
157
+ }
158
+
159
+ func uiAlignment(_ value: Any?) -> Alignment {
160
+ switch value as? String {
161
+ case "leading": return .leading
162
+ case "trailing": return .trailing
163
+ case "top": return .top
164
+ case "bottom": return .bottom
165
+ case "topLeading": return .topLeading
166
+ case "topTrailing": return .topTrailing
167
+ case "bottomLeading": return .bottomLeading
168
+ case "bottomTrailing": return .bottomTrailing
169
+ default: return .center
170
+ }
171
+ }
172
+
173
+ func uiHorizontal(_ value: Any?) -> HorizontalAlignment {
174
+ switch value as? String {
175
+ case "leading": return .leading
176
+ case "trailing": return .trailing
177
+ default: return .center
178
+ }
179
+ }
180
+
181
+ func uiVertical(_ value: Any?) -> VerticalAlignment {
182
+ switch value as? String {
183
+ case "top": return .top
184
+ case "bottom": return .bottom
185
+ case "firstTextBaseline": return .firstTextBaseline
186
+ case "lastTextBaseline": return .lastTextBaseline
187
+ default: return .center
188
+ }
189
+ }
190
+
191
+ func uiCGFloat(_ value: Any?) -> CGFloat? {
192
+ guard let number = value as? NSNumber, !uiIsBool(number) else { return nil }
193
+ return CGFloat(number.doubleValue)
194
+ }
195
+
196
+ // A frame's length: a number, with an infinite one (`Infinity` arrives as a huge number or null).
197
+ func uiLength(_ value: Any?) -> CGFloat? {
198
+ guard let length = uiCGFloat(value) else { return nil }
199
+ return length >= 1e10 ? .infinity : length
200
+ }
201
+
202
+ // A Picker's selection and its options' tags as one type: a string, or a number.
203
+ func uiTag(_ value: Any?) -> String? {
204
+ if let text = value as? String { return "s:" + text }
205
+ if let number = value as? NSNumber, !uiIsBool(number) { return "n:\(number.doubleValue)" }
206
+ return nil
207
+ }
208
+
209
+ func uiTagValue(_ tag: String) -> Any {
210
+ tag.hasPrefix("n:") ? (Double(tag.dropFirst(2)) ?? 0) as Any : String(tag.dropFirst(2)) as Any
211
+ }
212
+
213
+ // MARK: - Views
214
+
215
+ struct UIChildren: View {
216
+ let nodes: [UINode]
217
+ @ObservedObject var store: UIStore
218
+ var body: some View {
219
+ ForEach(nodes, id: \.tag) { UINodeView(node: $0, store: store) }
220
+ }
221
+ }
222
+
223
+ struct UINodeView: View {
224
+ let node: UINode
225
+ @ObservedObject var store: UIStore
226
+
227
+ var body: some View {
228
+ uiModified(uiContent(node, store), node.modifiers)
229
+ }
230
+ }
231
+
232
+ // What each name draws: the views `kExpoUIViews` lists (core/src/expo-ui.cpp).
233
+ let uiDrawn: Set<String> = [
234
+ "AlertView", "BackgroundView", "BottomSheetView", "Button", "CapsuleView", "ChartView", "CircleView",
235
+ "ColorPickerView", "ConfirmationDialogView", "ContentUnavailableView", "ContextMenu", "ControlGroupView",
236
+ "DatePickerView", "DisclosureGroupView", "DividerView", "EllipseView", "FormView", "GaugeView",
237
+ "GlassEffectContainerView", "GridView", "GridRowView", "GroupView", "HostView", "HStackView", "ImageView", "LabelView",
238
+ "LabeledContentView", "LazyHStackView", "LazyVStackView", "LinkView", "ListView", "MaskView", "MenuView",
239
+ "NavigationStackView", "OverlayView", "PickerView", "PopoverView", "ProgressView", "RectangleView", "RNHostView",
240
+ "RoundedRectangleView", "ScrollViewComponent", "SectionView", "SecureFieldView", "ShareLinkView", "SliderView",
241
+ "SlotView", "SpacerView", "StepperView", "SwipeActionsView", "TabView", "TextFieldView", "TextView", "ToggleView",
242
+ "UnevenRoundedRectangleView", "VStackView", "ZStackView",
243
+ ]
244
+
245
+ func uiContent(_ node: UINode, _ store: UIStore) -> AnyView {
246
+ let all = UIChildren(nodes: node.children, store: store)
247
+ let unslotted = UIChildren(nodes: node.withoutSlots, store: store)
248
+ func slot(_ name: String) -> UIChildren? { node.slot(name).map { UIChildren(nodes: $0.children, store: store) } }
249
+
250
+ switch node.name {
251
+ case "HostView", "SlotView", "GroupView":
252
+ return AnyView(Group { all })
253
+ case "VStackView":
254
+ return AnyView(VStack(alignment: uiHorizontal(node.props["alignment"]), spacing: uiCGFloat(node.props["spacing"])) { all })
255
+ case "HStackView":
256
+ return AnyView(HStack(alignment: uiVertical(node.props["alignment"]), spacing: uiCGFloat(node.props["spacing"])) { all })
257
+ case "ZStackView":
258
+ return AnyView(ZStack(alignment: uiAlignment(node.props["alignment"])) { all })
259
+ case "LazyVStackView":
260
+ return AnyView(LazyVStack(alignment: uiHorizontal(node.props["alignment"]), spacing: uiCGFloat(node.props["spacing"])) { all })
261
+ case "LazyHStackView":
262
+ return AnyView(LazyHStack(alignment: uiVertical(node.props["alignment"]), spacing: uiCGFloat(node.props["spacing"])) { all })
263
+ case "GridView":
264
+ return AnyView(Grid(alignment: uiAlignment(node.props["alignment"]), horizontalSpacing: uiCGFloat(node.props["horizontalSpacing"]),
265
+ verticalSpacing: uiCGFloat(node.props["verticalSpacing"])) { all })
266
+ case "GridRowView":
267
+ return AnyView(GridRow { all })
268
+ case "SpacerView":
269
+ return AnyView(Spacer(minLength: uiCGFloat(node.props["minLength"])))
270
+ case "DividerView":
271
+ return AnyView(Divider())
272
+ case "RectangleView":
273
+ return AnyView(Rectangle())
274
+ case "CircleView":
275
+ return AnyView(Circle())
276
+ case "EllipseView":
277
+ return AnyView(Ellipse())
278
+ case "CapsuleView":
279
+ return AnyView(Capsule(style: node.string("cornerStyle") == "circular" ? .circular : .continuous))
280
+ case "RoundedRectangleView":
281
+ return AnyView(RoundedRectangle(cornerRadius: uiCGFloat(node.props["cornerRadius"]) ?? 0))
282
+ case "UnevenRoundedRectangleView":
283
+ return AnyView(UnevenRoundedRectangle(
284
+ topLeadingRadius: uiCGFloat(node.props["topLeadingRadius"]) ?? 0,
285
+ bottomLeadingRadius: uiCGFloat(node.props["bottomLeadingRadius"]) ?? 0,
286
+ bottomTrailingRadius: uiCGFloat(node.props["bottomTrailingRadius"]) ?? 0,
287
+ topTrailingRadius: uiCGFloat(node.props["topTrailingRadius"]) ?? 0))
288
+ case "TextView":
289
+ return AnyView(uiText(node))
290
+ case "LabelView":
291
+ if let title = slot("title"), let icon = slot("icon") {
292
+ return AnyView(Label { title } icon: { icon })
293
+ }
294
+ if let systemImage = node.string("systemImage") {
295
+ return AnyView(Label(node.string("title") ?? "", systemImage: systemImage))
296
+ }
297
+ return AnyView(Text(node.string("title") ?? ""))
298
+ case "ImageView":
299
+ return AnyView(uiImage(node, store))
300
+ case "ButtonView", "Button":
301
+ return AnyView(uiButton(node, store, all))
302
+ case "LinkView":
303
+ let destination = node.string("destination").flatMap(URL.init(string:)) ?? URL(string: "about:blank")!
304
+ if let label = node.string("label") {
305
+ return AnyView(Link(label, destination: destination))
306
+ }
307
+ return AnyView(Link(destination: destination) { all })
308
+ case "ShareLinkView":
309
+ let item = node.string("item").flatMap(URL.init(string:)) ?? URL(string: "about:blank")!
310
+ let subject = node.string("subject").map { Text($0) }
311
+ let message = node.string("message").map { Text($0) }
312
+ if node.children.isEmpty {
313
+ return AnyView(ShareLink(item: item, subject: subject, message: message))
314
+ }
315
+ return AnyView(ShareLink(item: item, subject: subject, message: message) { all })
316
+ case "ToggleView":
317
+ return AnyView(uiToggle(node, store, all))
318
+ case "SliderView":
319
+ return AnyView(uiSlider(node, store))
320
+ case "StepperView":
321
+ return AnyView(uiStepper(node, store))
322
+ case "PickerView":
323
+ return AnyView(uiPicker(node, store))
324
+ case "DatePickerView":
325
+ return AnyView(uiDatePicker(node, store, all))
326
+ case "ColorPickerView":
327
+ return AnyView(uiColorPicker(node, store))
328
+ case "TextFieldView", "SecureFieldView":
329
+ return AnyView(uiTextField(node, store))
330
+ case "ProgressView":
331
+ return AnyView(uiProgress(node, all))
332
+ case "GaugeView":
333
+ return AnyView(uiGauge(node, slot))
334
+ case "FormView":
335
+ return AnyView(Form { all })
336
+ case "ListView":
337
+ return AnyView(uiList(node, store, all))
338
+ case "SectionView":
339
+ return AnyView(uiSection(node, store, slot, unslotted))
340
+ case "DisclosureGroupView":
341
+ return AnyView(uiDisclosure(node, store, slot, unslotted))
342
+ case "LabeledContentView":
343
+ let content: AnyView = slot("content").map { AnyView($0) } ?? AnyView(unslotted)
344
+ if let label = slot("label") {
345
+ return AnyView(LabeledContent { content } label: { label })
346
+ }
347
+ return AnyView(LabeledContent(node.string("label") ?? "") { content })
348
+ case "ControlGroupView":
349
+ if let label = slot("label") {
350
+ return AnyView(ControlGroup { unslotted } label: { label })
351
+ }
352
+ if let label = node.string("label") {
353
+ return AnyView(ControlGroup(label) { unslotted })
354
+ }
355
+ return AnyView(ControlGroup { all })
356
+ case "MenuView":
357
+ return AnyView(uiMenu(node, store, slot))
358
+ case "ContextMenu":
359
+ let trigger: AnyView = slot("trigger").map { AnyView($0) } ?? AnyView(unslotted)
360
+ let items = slot("items")
361
+ return AnyView(trigger.contextMenu { items })
362
+ case "ScrollViewComponent":
363
+ let axes: Axis.Set = switch node.string("axes") {
364
+ case "horizontal": .horizontal
365
+ case "both": [.horizontal, .vertical]
366
+ default: .vertical
367
+ }
368
+ return AnyView(ScrollView(axes, showsIndicators: node.bool("showsIndicators") ?? true) { all })
369
+ case "NavigationStackView":
370
+ return AnyView(NavigationStack { all })
371
+ case "TabView":
372
+ return AnyView(uiTabs(node, store))
373
+ case "BackgroundView", "OverlayView", "MaskView":
374
+ let base = AnyView(unslotted)
375
+ let alignment = uiAlignment(node.props["alignment"])
376
+ let content: AnyView = slot("content").map { AnyView($0) } ?? AnyView(EmptyView())
377
+ return switch node.name {
378
+ case "BackgroundView": AnyView(base.background(alignment: alignment) { content })
379
+ case "OverlayView": AnyView(base.overlay(alignment: alignment) { content })
380
+ default: AnyView(base.mask(alignment: alignment) { content })
381
+ }
382
+ case "AlertView", "ConfirmationDialogView":
383
+ return AnyView(uiDialog(node, store, slot))
384
+ case "PopoverView":
385
+ return AnyView(uiPopover(node, store, slot))
386
+ case "BottomSheetView":
387
+ return AnyView(uiSheet(node, store))
388
+ case "ContentUnavailableView":
389
+ if #available(macOS 14, *) {
390
+ return AnyView(ContentUnavailableView(node.string("title") ?? "", systemImage: node.string("systemImage") ?? "",
391
+ description: node.string("description").map { Text($0) }))
392
+ }
393
+ return AnyView(VStack(spacing: 8) {
394
+ Image(systemName: node.string("systemImage") ?? "").font(.largeTitle).foregroundStyle(.secondary)
395
+ Text(node.string("title") ?? "").font(.title2).bold()
396
+ if let description = node.string("description") { Text(description).foregroundStyle(.secondary) }
397
+ })
398
+ case "GlassEffectContainerView":
399
+ #if compiler(>=6.2)
400
+ if #available(macOS 26, *) {
401
+ return AnyView(GlassEffectContainer(spacing: uiCGFloat(node.props["spacing"])) { all })
402
+ }
403
+ #endif
404
+ return AnyView(Group { all })
405
+ case "SwipeActionsView":
406
+ return AnyView(uiSwipeActions(node, store))
407
+ case "ChartView":
408
+ return AnyView(uiChart(node))
409
+ case "RNHostView":
410
+ return AnyView(UIEmbedded(tag: node.tag, store: store))
411
+ default:
412
+ return AnyView(EmptyView())
413
+ }
414
+ }
415
+
416
+ func uiText(_ node: UINode) -> Text {
417
+ if let date = uiDate(node.props["date"]) {
418
+ switch node.string("dateStyle") {
419
+ case "time": return Text(date, style: .time)
420
+ case "relative": return Text(date, style: .relative)
421
+ case "offset": return Text(date, style: .offset)
422
+ case "timer": return Text(date, style: .timer)
423
+ default: return Text(date, style: .date)
424
+ }
425
+ }
426
+ if let interval = node.props["timerInterval"] as? [String: Any], let lower = uiDate(interval["lower"]),
427
+ let upper = uiDate(interval["upper"]), lower <= upper {
428
+ return Text(timerInterval: lower...upper, countsDown: node.bool("countsDown") ?? true)
429
+ }
430
+ let text = node.string("text") ?? ""
431
+ if node.bool("markdownEnabled") == true, let attributed = try? AttributedString(markdown: text) {
432
+ return Text(attributed)
433
+ }
434
+ return Text(verbatim: text)
435
+ }
436
+
437
+ func uiImage(_ node: UINode, _ store: UIStore) -> some View {
438
+ var image: Image
439
+ if let name = node.string("systemName") {
440
+ if let variable = node.number("variableValue") {
441
+ image = Image(systemName: name, variableValue: variable)
442
+ } else {
443
+ image = Image(systemName: name)
444
+ }
445
+ } else if let uri = node.string("uiImage"), let url = URL(string: uri), let ns = NSImage(contentsOf: url) {
446
+ image = Image(nsImage: ns)
447
+ } else if let asset = node.string("assetName") {
448
+ image = Image(asset)
449
+ } else {
450
+ image = Image(nsImage: NSImage())
451
+ }
452
+ if node.modifiers.contains(where: { $0["$type"] as? String == "resizable" }) {
453
+ image = image.resizable()
454
+ }
455
+ return image.onTapGesture {
456
+ if node.bool("useTapGesture") == true { store.emit(node.tag, "tap", [:]) }
457
+ }
458
+ }
459
+
460
+ func uiButton(_ node: UINode, _ store: UIStore, _ all: UIChildren) -> some View {
461
+ let role: ButtonRole? = switch node.string("role") {
462
+ case "destructive": .destructive
463
+ case "cancel": .cancel
464
+ default: nil
465
+ }
466
+ let press = { store.emit(node.tag, "buttonPress", [:]) }
467
+ if let label = node.string("label") {
468
+ if let systemImage = node.string("systemImage") {
469
+ return AnyView(Button(role: role, action: press) { Label(label, systemImage: systemImage) })
470
+ }
471
+ return AnyView(Button(label, role: role, action: press))
472
+ }
473
+ return AnyView(Button(role: role, action: press) { all })
474
+ }
475
+
476
+ func uiToggle(_ node: UINode, _ store: UIStore, _ all: UIChildren) -> some View {
477
+ let isOn = Binding<Bool>(
478
+ get: { (store.value(node, "isOn") as? Bool) ?? false },
479
+ set: { store.user(node, "isOn", $0, event: "isOnChange", payload: ["isOn": $0]) })
480
+ if let label = node.string("label") {
481
+ if let systemImage = node.string("systemImage") {
482
+ return AnyView(Toggle(isOn: isOn) { Label(label, systemImage: systemImage) })
483
+ }
484
+ return AnyView(Toggle(label, isOn: isOn))
485
+ }
486
+ return AnyView(Toggle(isOn: isOn) { all })
487
+ }
488
+
489
+ func uiSliderRange(_ node: UINode) -> ClosedRange<Double> {
490
+ let low = max(node.number("min") ?? 0, node.number("lowerLimit") ?? -.infinity)
491
+ let high = min(node.number("max") ?? 1, node.number("upperLimit") ?? .infinity)
492
+ return low...max(low, high)
493
+ }
494
+
495
+ func uiSlider(_ node: UINode, _ store: UIStore) -> some View {
496
+ let range = uiSliderRange(node)
497
+ let value = Binding<Double>(
498
+ get: { min(range.upperBound, max(range.lowerBound, ((store.value(node, "value") as? NSNumber)?.doubleValue) ?? 0)) },
499
+ set: { uiSlide(node, store, $0) })
500
+ let editing: (Bool) -> Void = { store.emit(node.tag, "editingChanged", ["isEditing": $0]) }
501
+ let labels = (node.slot("label"), node.slot("minimum"), node.slot("maximum"))
502
+ let label = UIChildren(nodes: labels.0?.children ?? [], store: store)
503
+ let minimum = UIChildren(nodes: labels.1?.children ?? [], store: store)
504
+ let maximum = UIChildren(nodes: labels.2?.children ?? [], store: store)
505
+ if let step = node.number("step"), step > 0 {
506
+ return AnyView(Slider(value: value, in: range, step: step, label: { label }, minimumValueLabel: { minimum },
507
+ maximumValueLabel: { maximum }, onEditingChanged: editing))
508
+ }
509
+ return AnyView(Slider(value: value, in: range, label: { label }, minimumValueLabel: { minimum },
510
+ maximumValueLabel: { maximum }, onEditingChanged: editing))
511
+ }
512
+
513
+ // The user moved the slider: expo/ui counts the events so a stale `value` prop is not applied.
514
+ func uiSlide(_ node: UINode, _ store: UIStore, _ raw: Double) {
515
+ let range = uiSliderRange(node)
516
+ let value = min(range.upperBound, max(range.lowerBound, raw))
517
+ let count = ((store.value(node, "eventCount") as? Int) ?? 0) + 1
518
+ store.remember(node, "sent", ((store.value(node, "sent") as? [Double]) ?? []) + [value])
519
+ store.user(node, "eventCount", count, event: "editingChanged", payload: ["isEditing": true])
520
+ store.user(node, "value", value, event: "valueChanged", payload: ["value": value, "eventCount": count])
521
+ }
522
+
523
+ func uiStepper(_ node: UINode, _ store: UIStore) -> some View {
524
+ let low = Int(node.number("min") ?? 0), high = Int(node.number("max") ?? 100)
525
+ let value = Binding<Int>(
526
+ get: { ((store.value(node, "value") as? NSNumber)?.intValue) ?? 0 },
527
+ set: { store.user(node, "value", $0, event: "valueChange", payload: ["value": $0]) })
528
+ return Stepper(node.string("label") ?? "", value: value, in: low...max(low, high), step: Int(node.number("step") ?? 1))
529
+ }
530
+
531
+ func uiPicker(_ node: UINode, _ store: UIStore) -> some View {
532
+ let selection = Binding<String>(
533
+ get: { uiTag(store.value(node, "selection")) ?? "" },
534
+ set: { tag in
535
+ guard tag != uiTag(store.value(node, "selection")) else { return }
536
+ store.user(node, "selection", uiTagValue(tag), event: "selectionChange", payload: ["selection": uiTagValue(tag)])
537
+ })
538
+ let content = UIChildren(nodes: node.slot("content")?.children ?? [], store: store)
539
+ if let label = node.slot("label") {
540
+ return AnyView(Picker(selection: selection) { content } label: { UIChildren(nodes: label.children, store: store) })
541
+ }
542
+ let label = node.string("label") ?? ""
543
+ if let systemImage = node.string("systemImage") {
544
+ return AnyView(Picker(selection: selection) { content } label: { Label(label, systemImage: systemImage) })
545
+ }
546
+ return AnyView(Picker(label, selection: selection) { content })
547
+ }
548
+
549
+ func uiDatePicker(_ node: UINode, _ store: UIStore, _ all: UIChildren) -> some View {
550
+ let date = Binding<Date>(
551
+ get: { uiDate(store.value(node, "selection")) ?? Date() },
552
+ set: { store.user(node, "selection", $0.timeIntervalSince1970 * 1000, event: "dateChange",
553
+ payload: ["date": $0.timeIntervalSince1970 * 1000]) })
554
+ var components: DatePickerComponents = []
555
+ for name in node.props["displayedComponents"] as? [String] ?? ["date"] {
556
+ if name == "date" { components.insert(.date) }
557
+ if name == "hourAndMinute" { components.insert(.hourAndMinute) }
558
+ }
559
+ let range = node.props["range"] as? [String: Any]
560
+ let start = uiDate(range?["start"]), end = uiDate(range?["end"])
561
+ let title = node.string("title") ?? ""
562
+ let picker: AnyView
563
+ if let start, let end, start <= end {
564
+ picker = AnyView(DatePicker(title, selection: date, in: start...end, displayedComponents: components))
565
+ } else if let start {
566
+ picker = AnyView(DatePicker(title, selection: date, in: start..., displayedComponents: components))
567
+ } else if let end {
568
+ picker = AnyView(DatePicker(title, selection: date, in: ...end, displayedComponents: components))
569
+ } else {
570
+ picker = AnyView(DatePicker(title, selection: date, displayedComponents: components))
571
+ }
572
+ return node.string("title") == nil && node.children.isEmpty ? AnyView(picker.labelsHidden()) : picker
573
+ }
574
+
575
+ func uiColorPicker(_ node: UINode, _ store: UIStore) -> some View {
576
+ let selection = Binding<Color>(
577
+ get: { uiColor(store.value(node, "selection")) ?? .clear },
578
+ set: { color in
579
+ let hex = uiHex(color)
580
+ store.user(node, "selection", hex, event: "selectionChange", payload: ["value": hex])
581
+ })
582
+ return ColorPicker(node.string("label") ?? "", selection: selection, supportsOpacity: node.bool("supportsOpacity") ?? true)
583
+ }
584
+
585
+ // What is typed into a text field, by the user or a replay: cut to its maxLength, kept and sent.
586
+ func uiType(_ node: UINode, _ store: UIStore, _ value: String) {
587
+ var typed = value
588
+ // Converted only when it cuts the text, so a limit past what an Int holds keeps all of it.
589
+ if let limit = node.number("maxLength"), limit >= 0, limit < Double(typed.count) {
590
+ typed = String(typed.prefix(Int(limit)))
591
+ }
592
+ store.user(node, "text", typed, event: "textChange", payload: ["value": typed])
593
+ }
594
+
595
+ // A text field keeps what is typed: expo/ui's `text` is an ObservableState, which macOS has no
596
+ // module for, so a `text` given as a string is taken instead.
597
+ func uiTextField(_ node: UINode, _ store: UIStore) -> some View {
598
+ let text = Binding<String>(
599
+ get: { (store.value(node, "text") as? String) ?? "" },
600
+ set: { uiType(node, store, $0) })
601
+ let placeholder = node.string("placeholder") ?? ""
602
+ if node.name == "SecureFieldView" {
603
+ return AnyView(SecureField(placeholder, text: text))
604
+ }
605
+ return AnyView(TextField(placeholder, text: text, axis: node.string("axis") == "vertical" ? .vertical : .horizontal))
606
+ }
607
+
608
+ func uiProgress(_ node: UINode, _ all: UIChildren) -> some View {
609
+ if let interval = node.props["timerInterval"] as? [String: Any], let lower = uiDate(interval["lower"]),
610
+ let upper = uiDate(interval["upper"]), lower <= upper {
611
+ return AnyView(ProgressView(timerInterval: lower...upper, countsDown: node.bool("countsDown") ?? true) { all })
612
+ }
613
+ if let value = node.number("value") {
614
+ return AnyView(ProgressView(value: min(1, max(0, value))) { all })
615
+ }
616
+ return AnyView(ProgressView { all })
617
+ }
618
+
619
+ func uiGauge(_ node: UINode, _ slot: (String) -> UIChildren?) -> some View {
620
+ let low = node.number("min") ?? 0, high = node.number("max") ?? 1
621
+ let value = min(max(node.number("value") ?? 0, low), max(low, high))
622
+ return Gauge(value: value, in: low...max(low, high)) {
623
+ slot("label")
624
+ } currentValueLabel: {
625
+ slot("currentValue")
626
+ } minimumValueLabel: {
627
+ slot("minimumValue")
628
+ } maximumValueLabel: {
629
+ slot("maximumValue")
630
+ }
631
+ }
632
+
633
+ func uiList(_ node: UINode, _ store: UIStore, _ all: UIChildren) -> some View {
634
+ guard node.props["selection"] != nil else { return AnyView(List { all }) }
635
+ let selection = Binding<Set<String>>(
636
+ get: { Set(((store.value(node, "selection") as? [Any]) ?? []).compactMap(uiTag)) },
637
+ set: { tags in
638
+ let values = tags.sorted().map(uiTagValue)
639
+ store.user(node, "selection", values, event: "selectionChange", payload: ["selection": values])
640
+ })
641
+ return AnyView(List(selection: selection) { all })
642
+ }
643
+
644
+ func uiSection(_ node: UINode, _ store: UIStore, _ slot: (String) -> UIChildren?, _ unslotted: UIChildren) -> some View {
645
+ let content: AnyView = slot("content").map { AnyView($0) } ?? AnyView(unslotted)
646
+ let header: AnyView = slot("header").map { AnyView($0) } ?? AnyView(node.string("title").map { Text($0) })
647
+ let footer: AnyView = slot("footer").map { AnyView($0) } ?? AnyView(EmptyView())
648
+ if node.props["isExpanded"] != nil, #available(macOS 14, *) {
649
+ let expanded = Binding<Bool>(
650
+ get: { (store.value(node, "isExpanded") as? Bool) ?? true },
651
+ set: { store.user(node, "isExpanded", $0, event: "isExpandedChange", payload: ["isExpanded": $0]) })
652
+ return AnyView(Section(isExpanded: expanded) { content } header: { header })
653
+ }
654
+ return AnyView(Section { content } header: { header } footer: { footer })
655
+ }
656
+
657
+ func uiDisclosure(_ node: UINode, _ store: UIStore, _ slot: (String) -> UIChildren?, _ unslotted: UIChildren) -> some View {
658
+ let expanded = Binding<Bool>(
659
+ get: { (store.value(node, "isExpanded") as? Bool) ?? true },
660
+ set: { store.user(node, "isExpanded", $0, event: "isExpandedChange", payload: ["isExpanded": $0]) })
661
+ if let label = slot("label") {
662
+ return AnyView(DisclosureGroup(isExpanded: expanded) { unslotted } label: { label })
663
+ }
664
+ return AnyView(DisclosureGroup(node.string("label") ?? "", isExpanded: expanded) { unslotted })
665
+ }
666
+
667
+ func uiMenu(_ node: UINode, _ store: UIStore, _ slot: (String) -> UIChildren?) -> some View {
668
+ let items = UIChildren(nodes: node.children.filter { $0.slotName != "label" }, store: store)
669
+ let label: AnyView
670
+ if let custom = slot("label") {
671
+ label = AnyView(custom)
672
+ } else if let systemImage = node.string("systemImage") {
673
+ label = AnyView(Label(node.string("label") ?? "", systemImage: systemImage))
674
+ } else {
675
+ label = AnyView(Text(node.string("label") ?? ""))
676
+ }
677
+ if node.bool("hasPrimaryAction") == true {
678
+ return AnyView(Menu { items } label: { label } primaryAction: { store.emit(node.tag, "primaryAction", [:]) })
679
+ }
680
+ return AnyView(Menu { items } label: { label })
681
+ }
682
+
683
+ func uiTabs(_ node: UINode, _ store: UIStore) -> some View {
684
+ let tabs = node.withoutSlots
685
+ let key: (UINode, Int) -> String = { tab, index in tab.string("value") ?? "\(index)" }
686
+ let selection = Binding<String>(
687
+ get: { (store.value(node, "selection") as? String) ?? node.string("defaultSelection") ?? tabs.first.map { key($0, 0) } ?? "" },
688
+ set: { store.user(node, "selection", $0, event: "selectionChange", payload: ["selection": $0]) })
689
+ return TabView(selection: selection) {
690
+ ForEach(Array(tabs.enumerated()), id: \.element.tag) { index, tab in
691
+ UIChildren(nodes: tab.name == "SlotView" ? tab.children : [tab], store: store)
692
+ .tabItem {
693
+ if let systemImage = tab.string("systemImage") {
694
+ Label(tab.string("label") ?? "", systemImage: systemImage)
695
+ } else {
696
+ Text(tab.string("label") ?? key(tab, index))
697
+ }
698
+ }
699
+ .tag(key(tab, index))
700
+ }
701
+ }
702
+ }
703
+
704
+ func uiPresented(_ node: UINode, _ store: UIStore) -> Binding<Bool> {
705
+ Binding<Bool>(
706
+ get: { (store.value(node, "isPresented") as? Bool) ?? false },
707
+ set: { shown in
708
+ guard shown != ((store.value(node, "isPresented") as? Bool) ?? false) else { return }
709
+ store.user(node, "isPresented", shown, event: "isPresentedChange", payload: ["isPresented": shown])
710
+ if !shown && node.name == "BottomSheetView" { store.emit(node.tag, "dismiss", [:]) }
711
+ })
712
+ }
713
+
714
+ func uiDialog(_ node: UINode, _ store: UIStore, _ slot: (String) -> UIChildren?) -> some View {
715
+ let trigger: AnyView = slot("trigger").map { AnyView($0) } ?? AnyView(EmptyView())
716
+ let actions = slot("actions")
717
+ let message = slot("message")
718
+ let title = node.string("title") ?? ""
719
+ if node.name == "AlertView" {
720
+ return AnyView(trigger.alert(title, isPresented: uiPresented(node, store)) { actions } message: { message })
721
+ }
722
+ let visibility: Visibility = switch node.string("titleVisibility") {
723
+ case "visible": .visible
724
+ case "hidden": .hidden
725
+ default: .automatic
726
+ }
727
+ return AnyView(trigger.confirmationDialog(title, isPresented: uiPresented(node, store), titleVisibility: visibility) {
728
+ actions
729
+ } message: { message })
730
+ }
731
+
732
+ func uiPopover(_ node: UINode, _ store: UIStore, _ slot: (String) -> UIChildren?) -> some View {
733
+ let trigger: AnyView = slot("trigger").map { AnyView($0) } ?? AnyView(EmptyView())
734
+ let edge: Edge = switch node.string("arrowEdge") {
735
+ case "leading": .leading
736
+ case "trailing": .trailing
737
+ case "bottom": .bottom
738
+ default: .top
739
+ }
740
+ let content = slot("popover")
741
+ return trigger.popover(isPresented: uiPresented(node, store), arrowEdge: edge) { content }
742
+ }
743
+
744
+ func uiSheet(_ node: UINode, _ store: UIStore) -> some View {
745
+ let content = UIChildren(nodes: node.withoutSlots, store: store)
746
+ let anchor: AnyView = node.slot("anchor").map { AnyView(UIChildren(nodes: $0.children, store: store)) } ?? AnyView(Color.clear.frame(width: 0, height: 0))
747
+ return anchor.sheet(isPresented: uiPresented(node, store)) { content }
748
+ }
749
+
750
+ func uiSwipeActions(_ node: UINode, _ store: UIStore) -> some View {
751
+ var row = AnyView(UIChildren(nodes: node.withoutSlots, store: store))
752
+ for actions in node.children where actions.slotName == "actions" {
753
+ let extra = actions.props["extraProps"] as? [String: Any]
754
+ let edge: HorizontalEdge = extra?["edge"] as? String == "leading" ? .leading : .trailing
755
+ let full = (extra?["allowsFullSwipe"] as? Bool) ?? true
756
+ row = AnyView(row.swipeActions(edge: edge, allowsFullSwipe: full) { UIChildren(nodes: actions.children, store: store) })
757
+ }
758
+ return row
759
+ }
760
+
761
+ struct UIChartPoint: Identifiable {
762
+ let id: Int
763
+ let x: String
764
+ let y: Double
765
+ let color: Color?
766
+ }
767
+
768
+ func uiChart(_ node: UINode) -> some View {
769
+ let points = (node.props["data"] as? [[String: Any]] ?? []).enumerated().map { index, point in
770
+ UIChartPoint(id: index, x: (point["x"] as? String) ?? (point["x"] as? NSNumber).map { "\($0)" } ?? "\(index)",
771
+ y: (point["y"] as? NSNumber)?.doubleValue ?? 0, color: uiColor(point["color"]))
772
+ }
773
+ let type = node.string("type") ?? "line"
774
+ let chart = Chart(points) { point in
775
+ switch type {
776
+ case "bar":
777
+ BarMark(x: .value("x", point.x), y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
778
+ case "area":
779
+ AreaMark(x: .value("x", point.x), y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
780
+ case "point":
781
+ PointMark(x: .value("x", point.x), y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
782
+ case "rectangle":
783
+ RectangleMark(x: .value("x", point.x), y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
784
+ case "rule":
785
+ RuleMark(y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
786
+ default:
787
+ LineMark(x: .value("x", point.x), y: .value("y", point.y)).foregroundStyle(point.color ?? .accentColor)
788
+ }
789
+ }
790
+ if type == "pie", #available(macOS 14, *) {
791
+ return AnyView(Chart(points) { point in
792
+ SectorMark(angle: .value("y", point.y), innerRadius: .ratio(0), angularInset: 2)
793
+ .foregroundStyle(point.color ?? .accentColor)
794
+ })
795
+ }
796
+ let grid = node.bool("showGrid") ?? true
797
+ return AnyView(chart.chartXAxis(grid ? .automatic : .hidden).chartYAxis(grid ? .automatic : .hidden))
798
+ }
799
+
800
+ // An RNHostView: the app's own views, which the host's view for the tag holds, inside the content.
801
+ final class UIEmbedContainer: NSView {
802
+ override var isFlipped: Bool { true }
803
+ override var intrinsicContentSize: NSSize { subviews.first?.frame.size ?? .zero }
804
+ }
805
+
806
+ struct UIEmbedded: NSViewRepresentable {
807
+ let tag: Int
808
+ let store: UIStore
809
+ func makeNSView(context: Context) -> UIEmbedContainer { UIEmbedContainer() }
810
+ func updateNSView(_ container: UIEmbedContainer, context: Context) {
811
+ guard let view = store.viewForTag(tag), view.superview !== container else { return }
812
+ container.subviews.forEach { $0.removeFromSuperview() }
813
+ view.setFrameOrigin(.zero)
814
+ container.addSubview(view)
815
+ container.invalidateIntrinsicContentSize()
816
+ }
817
+ }
818
+
819
+ // MARK: - Modifiers
820
+
821
+ func uiFont(_ m: [String: Any]) -> Font {
822
+ let weight: Font.Weight? = switch m["weight"] as? String {
823
+ case "ultraLight": .ultraLight
824
+ case "thin": .thin
825
+ case "light": .light
826
+ case "regular": .regular
827
+ case "medium": .medium
828
+ case "semibold": .semibold
829
+ case "bold": .bold
830
+ case "heavy": .heavy
831
+ case "black": .black
832
+ default: nil
833
+ }
834
+ let design: Font.Design = switch m["design"] as? String {
835
+ case "rounded": .rounded
836
+ case "serif": .serif
837
+ case "monospaced": .monospaced
838
+ default: .default
839
+ }
840
+ var font: Font
841
+ if let family = m["family"] as? String {
842
+ font = .custom(family, size: uiCGFloat(m["size"]) ?? NSFont.systemFontSize)
843
+ } else if let size = uiCGFloat(m["size"]) {
844
+ font = .system(size: size, design: design)
845
+ } else {
846
+ let style: Font.TextStyle = switch m["textStyle"] as? String {
847
+ case "largeTitle": .largeTitle
848
+ case "title": .title
849
+ case "title2": .title2
850
+ case "title3": .title3
851
+ case "headline": .headline
852
+ case "subheadline": .subheadline
853
+ case "callout": .callout
854
+ case "footnote": .footnote
855
+ case "caption": .caption
856
+ case "caption2": .caption2
857
+ default: .body
858
+ }
859
+ font = .system(style, design: design)
860
+ }
861
+ if let weight { font = font.weight(weight) }
862
+ return font
863
+ }
864
+
865
+ func uiPadded(_ view: AnyView, _ m: [String: Any]) -> AnyView {
866
+ func length(_ key: String) -> CGFloat?? {
867
+ guard let value = m[key] else { return nil }
868
+ return .some(uiCGFloat(value)) // `default` is the system's padding
869
+ }
870
+ var out = view
871
+ var any = false
872
+ let edges: [(String, Edge.Set)] = [("all", .all), ("horizontal", .horizontal), ("vertical", .vertical), ("top", .top),
873
+ ("bottom", .bottom), ("leading", .leading), ("trailing", .trailing)]
874
+ for (key, edge) in edges {
875
+ if let value = length(key) {
876
+ out = AnyView(out.padding(edge, value))
877
+ any = true
878
+ }
879
+ }
880
+ return any ? out : AnyView(view.padding())
881
+ }
882
+
883
+ func uiShapeStyle(_ value: Any?) -> AnyShapeStyle? {
884
+ if let color = uiColor(value) { return AnyShapeStyle(color) }
885
+ guard let style = value as? [String: Any] else { return nil }
886
+ switch style["type"] as? String {
887
+ case "color":
888
+ return uiColor(style["color"]).map { AnyShapeStyle($0) }
889
+ case "hierarchical":
890
+ return switch style["hierarchical"] as? String {
891
+ case "secondary": AnyShapeStyle(.secondary)
892
+ case "tertiary": AnyShapeStyle(.tertiary)
893
+ case "quaternary": AnyShapeStyle(.quaternary)
894
+ default: AnyShapeStyle(.primary)
895
+ }
896
+ case "linearGradient":
897
+ let colors = (style["colors"] as? [Any] ?? []).compactMap(uiColor)
898
+ return AnyShapeStyle(LinearGradient(colors: colors, startPoint: .top, endPoint: .bottom))
899
+ default:
900
+ return nil
901
+ }
902
+ }
903
+
904
+ func uiModified(_ view: AnyView, _ modifiers: [[String: Any]]) -> AnyView {
905
+ modifiers.reduce(view) { view, m in uiModifier(view, m) }
906
+ }
907
+
908
+ // One of expo/ui's modifiers, by its `$type`. One with no macOS meaning, or none here yet, is
909
+ // skipped.
910
+ /// A sheet's height in a window `window` points tall from its detents, as a macOS sheet has none:
911
+ /// its smallest, as iOS opens a sheet at its smallest (`medium` half the window, `large` nine
912
+ /// tenths, a fraction of it, or a height), never taller than the window. Nil for none it knows.
913
+ func uiSheetHeight(_ detents: Any?, window: CGFloat) -> CGFloat? {
914
+ let heights = (detents as? [Any] ?? []).compactMap { detent -> CGFloat? in
915
+ switch detent {
916
+ case let name as String:
917
+ return name == "medium" ? window / 2 : name == "large" ? window * 0.9 : nil
918
+ case let shape as [String: Any]:
919
+ if let fraction = shape["fraction"] as? NSNumber { return window * CGFloat(fraction.doubleValue) }
920
+ if let height = shape["height"] as? NSNumber { return CGFloat(height.doubleValue) }
921
+ return nil
922
+ default:
923
+ return nil
924
+ }
925
+ }
926
+ return heights.min().map { min($0, window) }
927
+ }
928
+
929
+ @_cdecl("ngn_ui_sheet_height")
930
+ public func ngnUISheetHeight(_ detents: UnsafePointer<CChar>, _ window: Double) -> Double {
931
+ let parsed = try? JSONSerialization.jsonObject(with: Data(String(cString: detents).utf8))
932
+ return uiSheetHeight(parsed, window: CGFloat(window)).map(Double.init) ?? -1
933
+ }
934
+
935
+ func uiModifier(_ view: AnyView, _ m: [String: Any]) -> AnyView {
936
+ switch m["$type"] as? String {
937
+ case "padding":
938
+ return uiPadded(view, m)
939
+ case "presentationDetents":
940
+ // The key window's content height: a sheet opens on the window in front.
941
+ let window = (NSApp.keyWindow ?? NSApp.mainWindow)?.contentLayoutRect.height ?? 600
942
+ return uiSheetHeight(m["detents"], window: window).map { AnyView(view.frame(height: $0)) } ?? view
943
+ case "frame":
944
+ if m["width"] != nil || m["height"] != nil {
945
+ return AnyView(view.frame(width: uiCGFloat(m["width"]), height: uiCGFloat(m["height"]), alignment: uiAlignment(m["alignment"])))
946
+ }
947
+ return AnyView(view.frame(minWidth: uiLength(m["minWidth"]), idealWidth: uiLength(m["idealWidth"]), maxWidth: uiLength(m["maxWidth"]),
948
+ minHeight: uiLength(m["minHeight"]), idealHeight: uiLength(m["idealHeight"]),
949
+ maxHeight: uiLength(m["maxHeight"]), alignment: uiAlignment(m["alignment"])))
950
+ case "foregroundColor":
951
+ return uiColor(m["color"]).map { AnyView(view.foregroundColor($0)) } ?? view
952
+ case "foregroundStyle":
953
+ return uiShapeStyle(m["style"] ?? m["color"]).map { AnyView(view.foregroundStyle($0)) } ?? view
954
+ case "tint":
955
+ return uiColor((m["tint"] as? [String: Any])?["color"] ?? m["tint"] ?? m["color"]).map { AnyView(view.tint($0)) } ?? view
956
+ case "background":
957
+ return uiShapeStyle(m["style"] ?? m["color"]).map { AnyView(view.background($0)) } ?? view
958
+ case "opacity":
959
+ return AnyView(view.opacity((m["value"] as? NSNumber)?.doubleValue ?? 1))
960
+ case "font":
961
+ return AnyView(view.font(uiFont(m)))
962
+ case "bold":
963
+ return AnyView(view.bold())
964
+ case "italic":
965
+ return AnyView(view.italic())
966
+ case "monospacedDigit":
967
+ return AnyView(view.monospacedDigit())
968
+ case "disabled":
969
+ return AnyView(view.disabled((m["disabled"] as? Bool) ?? true))
970
+ case "hidden":
971
+ return (m["hidden"] as? Bool) ?? true ? AnyView(view.hidden()) : view
972
+ case "tag":
973
+ return uiTag(m["tag"]).map { AnyView(view.tag($0)) } ?? view
974
+ case "cornerRadius":
975
+ return AnyView(view.clipShape(RoundedRectangle(cornerRadius: uiCGFloat(m["radius"]) ?? 0)))
976
+ case "clipShape":
977
+ return switch m["shape"] as? String {
978
+ case "circle": AnyView(view.clipShape(Circle()))
979
+ case "capsule": AnyView(view.clipShape(Capsule()))
980
+ case "roundedRectangle": AnyView(view.clipShape(RoundedRectangle(cornerRadius: uiCGFloat(m["cornerRadius"]) ?? 0)))
981
+ default: AnyView(view.clipShape(Rectangle()))
982
+ }
983
+ case "clipped":
984
+ return (m["clipped"] as? Bool) ?? true ? AnyView(view.clipped()) : view
985
+ case "border":
986
+ return AnyView(view.border(uiColor(m["color"]) ?? .primary, width: uiCGFloat(m["width"]) ?? 1))
987
+ case "shadow":
988
+ return AnyView(view.shadow(color: uiColor(m["color"]) ?? .black.opacity(0.33), radius: uiCGFloat(m["radius"]) ?? 0,
989
+ x: uiCGFloat(m["x"]) ?? 0, y: uiCGFloat(m["y"]) ?? 0))
990
+ case "offset":
991
+ return AnyView(view.offset(x: uiCGFloat(m["x"]) ?? 0, y: uiCGFloat(m["y"]) ?? 0))
992
+ case "scaleEffect":
993
+ return AnyView(view.scaleEffect(x: uiCGFloat(m["x"]) ?? 1, y: uiCGFloat(m["y"]) ?? 1))
994
+ case "rotationEffect":
995
+ return AnyView(view.rotationEffect(.degrees((m["angle"] as? NSNumber)?.doubleValue ?? 0)))
996
+ case "zIndex":
997
+ return AnyView(view.zIndex((m["index"] as? NSNumber)?.doubleValue ?? 0))
998
+ case "layoutPriority":
999
+ return AnyView(view.layoutPriority((m["priority"] as? NSNumber)?.doubleValue ?? 0))
1000
+ case "blur":
1001
+ return AnyView(view.blur(radius: uiCGFloat(m["radius"]) ?? 0))
1002
+ case "fixedSize":
1003
+ return AnyView(view.fixedSize(horizontal: (m["horizontal"] as? Bool) ?? true, vertical: (m["vertical"] as? Bool) ?? true))
1004
+ case "aspectRatio":
1005
+ return AnyView(view.aspectRatio(uiCGFloat(m["ratio"]), contentMode: m["contentMode"] as? String == "fill" ? .fill : .fit))
1006
+ case "lineLimit":
1007
+ return AnyView(view.lineLimit((m["limit"] as? NSNumber)?.intValue ?? (m["max"] as? NSNumber)?.intValue))
1008
+ case "multilineTextAlignment":
1009
+ let alignment: TextAlignment = switch m["alignment"] as? String {
1010
+ case "center": .center
1011
+ case "trailing": .trailing
1012
+ default: .leading
1013
+ }
1014
+ return AnyView(view.multilineTextAlignment(alignment))
1015
+ case "textSelection":
1016
+ return (m["value"] as? Bool) == true ? AnyView(view.textSelection(.enabled)) : view
1017
+ case "labelsHidden":
1018
+ return AnyView(view.labelsHidden())
1019
+ case "accessibilityLabel":
1020
+ return AnyView(view.accessibilityLabel(Text(m["label"] as? String ?? "")))
1021
+ case "accessibilityHint":
1022
+ return AnyView(view.accessibilityHint(Text(m["hint"] as? String ?? "")))
1023
+ case "accessibilityHidden":
1024
+ return AnyView(view.accessibilityHidden((m["hidden"] as? Bool) ?? true))
1025
+ case "accessibilityIdentifier":
1026
+ return AnyView(view.accessibilityIdentifier(m["identifier"] as? String ?? ""))
1027
+ case "help":
1028
+ return AnyView(view.help(m["text"] as? String ?? ""))
1029
+ case "controlSize":
1030
+ let size: ControlSize = switch m["size"] as? String {
1031
+ case "mini": .mini
1032
+ case "small": .small
1033
+ case "large": .large
1034
+ case "extraLarge": .large
1035
+ default: .regular
1036
+ }
1037
+ return AnyView(view.controlSize(size))
1038
+ case "pickerStyle":
1039
+ return switch m["style"] as? String {
1040
+ case "menu": AnyView(view.pickerStyle(.menu))
1041
+ case "segmented", "palette": AnyView(view.pickerStyle(.segmented))
1042
+ case "inline": AnyView(view.pickerStyle(.inline))
1043
+ case "radioGroup": AnyView(view.pickerStyle(.radioGroup))
1044
+ default: view // `wheel` is iOS's
1045
+ }
1046
+ case "toggleStyle":
1047
+ return switch m["style"] as? String {
1048
+ case "switch": AnyView(view.toggleStyle(.switch))
1049
+ case "button": AnyView(view.toggleStyle(.button))
1050
+ case "checkbox": AnyView(view.toggleStyle(.checkbox))
1051
+ default: view
1052
+ }
1053
+ case "buttonStyle":
1054
+ return switch m["style"] as? String {
1055
+ case "bordered": AnyView(view.buttonStyle(.bordered))
1056
+ case "borderedProminent": AnyView(view.buttonStyle(.borderedProminent))
1057
+ case "borderless": AnyView(view.buttonStyle(.borderless))
1058
+ case "plain": AnyView(view.buttonStyle(.plain))
1059
+ case "link": AnyView(view.buttonStyle(.link))
1060
+ default: view
1061
+ }
1062
+ case "datePickerStyle":
1063
+ return switch m["style"] as? String {
1064
+ case "compact": AnyView(view.datePickerStyle(.compact))
1065
+ case "graphical": AnyView(view.datePickerStyle(.graphical))
1066
+ case "field": AnyView(view.datePickerStyle(.field))
1067
+ case "stepperField": AnyView(view.datePickerStyle(.stepperField))
1068
+ default: view // `wheel` is iOS's
1069
+ }
1070
+ case "progressViewStyle":
1071
+ return switch m["style"] as? String {
1072
+ case "circular": AnyView(view.progressViewStyle(.circular))
1073
+ case "linear": AnyView(view.progressViewStyle(.linear))
1074
+ default: view
1075
+ }
1076
+ case "gaugeStyle":
1077
+ return switch m["style"] as? String {
1078
+ case "circular": AnyView(view.gaugeStyle(.accessoryCircular))
1079
+ case "circularCapacity": AnyView(view.gaugeStyle(.accessoryCircularCapacity))
1080
+ case "linear": AnyView(view.gaugeStyle(.accessoryLinear))
1081
+ case "linearCapacity": AnyView(view.gaugeStyle(.linearCapacity))
1082
+ default: view
1083
+ }
1084
+ case "labelStyle":
1085
+ return switch m["style"] as? String {
1086
+ case "iconOnly": AnyView(view.labelStyle(.iconOnly))
1087
+ case "titleOnly": AnyView(view.labelStyle(.titleOnly))
1088
+ case "titleAndIcon": AnyView(view.labelStyle(.titleAndIcon))
1089
+ default: view
1090
+ }
1091
+ case "listStyle":
1092
+ return switch m["style"] as? String {
1093
+ case "plain": AnyView(view.listStyle(.plain))
1094
+ case "inset", "insetGrouped": AnyView(view.listStyle(.inset))
1095
+ case "sidebar": AnyView(view.listStyle(.sidebar))
1096
+ case "bordered": AnyView(view.listStyle(.bordered))
1097
+ default: view
1098
+ }
1099
+ case "textFieldStyle":
1100
+ return switch m["style"] as? String {
1101
+ case "plain": AnyView(view.textFieldStyle(.plain))
1102
+ case "roundedBorder": AnyView(view.textFieldStyle(.roundedBorder))
1103
+ case "squareBorder": AnyView(view.textFieldStyle(.squareBorder))
1104
+ default: view
1105
+ }
1106
+ case "menuStyle":
1107
+ return m["style"] as? String == "button" ? AnyView(view.menuStyle(.button)) : view
1108
+ case "imageScale":
1109
+ return switch m["scale"] as? String {
1110
+ case "small": AnyView(view.imageScale(.small))
1111
+ case "large": AnyView(view.imageScale(.large))
1112
+ default: AnyView(view.imageScale(.medium))
1113
+ }
1114
+ case "navigationTitle":
1115
+ return AnyView(view.navigationTitle(m["title"] as? String ?? ""))
1116
+ case "preferredColorScheme":
1117
+ return switch m["colorScheme"] as? String {
1118
+ case "dark": AnyView(view.environment(\.colorScheme, .dark))
1119
+ case "light": AnyView(view.environment(\.colorScheme, .light))
1120
+ default: view
1121
+ }
1122
+ case "badge":
1123
+ return AnyView(view.badge((m["value"] as? String).map { Text($0) }))
1124
+ case "underline":
1125
+ return AnyView(view.underline((m["isActive"] as? Bool) ?? true, color: uiColor(m["color"])))
1126
+ case "strikethrough":
1127
+ return AnyView(view.strikethrough((m["isActive"] as? Bool) ?? true, color: uiColor(m["color"])))
1128
+ case "kerning":
1129
+ return AnyView(view.kerning(uiCGFloat(m["value"]) ?? 0))
1130
+ case "lineSpacing":
1131
+ return AnyView(view.lineSpacing(uiCGFloat(m["value"]) ?? 0))
1132
+ case "textCase":
1133
+ return AnyView(view.textCase(m["value"] as? String == "lowercase" ? .lowercase : .uppercase))
1134
+ case "glassEffect":
1135
+ #if compiler(>=6.2)
1136
+ if #available(macOS 26, *) { return AnyView(view.glassEffect()) }
1137
+ #endif
1138
+ return view
1139
+ default:
1140
+ return view
1141
+ }
1142
+ }
1143
+
1144
+ // MARK: - The host
1145
+
1146
+ final class UIHostView: NSView {
1147
+ let store = UIStore()
1148
+ let controller: NSHostingController<UIRoot>
1149
+
1150
+ init() {
1151
+ controller = NSHostingController(rootView: UIRoot(store: store))
1152
+ super.init(frame: .zero)
1153
+ controller.view.frame = bounds
1154
+ controller.view.autoresizingMask = [.width, .height]
1155
+ addSubview(controller.view)
1156
+ }
1157
+
1158
+ @available(*, unavailable)
1159
+ required init?(coder: NSCoder) { fatalError() }
1160
+
1161
+ override var isFlipped: Bool { true }
1162
+ }
1163
+
1164
+ struct UIRoot: View {
1165
+ @ObservedObject var store: UIStore
1166
+ var body: some View {
1167
+ if let root = store.root {
1168
+ UINodeView(node: root, store: store)
1169
+ }
1170
+ }
1171
+ }
1172
+
1173
+ private func host(_ pointer: UnsafeMutableRawPointer) -> UIHostView {
1174
+ Unmanaged<UIHostView>.fromOpaque(pointer).takeUnretainedValue()
1175
+ }
1176
+
1177
+ private func json(_ text: UnsafePointer<CChar>) -> Any? {
1178
+ try? JSONSerialization.jsonObject(with: Data(String(cString: text).utf8), options: [.fragmentsAllowed])
1179
+ }
1180
+
1181
+ /// A host view, retained: its events go to `onEvent` and its RNHostViews come from `viewForTag`,
1182
+ /// each with `context`.
1183
+ @_cdecl("ngn_ui_host_make")
1184
+ public func ngnUIHostMake(_ context: UnsafeMutableRawPointer?, _ onEvent: NGNUIEvent, _ viewForTag: NGNUIViewForTag) -> UnsafeMutableRawPointer {
1185
+ let view = UIHostView()
1186
+ view.store.emit = { tag, name, payload in
1187
+ let data = (try? JSONSerialization.data(withJSONObject: payload)) ?? Data("{}".utf8)
1188
+ name.withCString { n in String(decoding: data, as: UTF8.self).withCString { p in onEvent(context, Int32(tag), n, p) } }
1189
+ }
1190
+ view.store.viewForTag = { tag in
1191
+ viewForTag(context, Int32(tag)).map { Unmanaged<NSView>.fromOpaque($0).takeUnretainedValue() }
1192
+ }
1193
+ return Unmanaged.passRetained(view).toOpaque()
1194
+ }
1195
+
1196
+ /// Sends no more events and asks for no more views: the renderer that made the view is gone.
1197
+ @_cdecl("ngn_ui_host_detach")
1198
+ public func ngnUIHostDetach(_ pointer: UnsafeMutableRawPointer) {
1199
+ let store = host(pointer).store
1200
+ store.emit = { _, _, _ in }
1201
+ store.viewForTag = { _ in nil }
1202
+ }
1203
+
1204
+ /// Draws `tree` (the HostView's, as JSON) from now on.
1205
+ @_cdecl("ngn_ui_host_set_tree")
1206
+ public func ngnUIHostSetTree(_ pointer: UnsafeMutableRawPointer, _ tree: UnsafePointer<CChar>) {
1207
+ host(pointer).store.set(json(tree).flatMap(UINode.init))
1208
+ }
1209
+
1210
+ /// The content's size: its fitting size, or with a `width` or `height` (when not negative) given,
1211
+ /// the size it takes in that.
1212
+ @_cdecl("ngn_ui_host_fit")
1213
+ public func ngnUIHostFit(_ pointer: UnsafeMutableRawPointer, _ width: Double, _ height: Double,
1214
+ _ outWidth: UnsafeMutablePointer<Double>, _ outHeight: UnsafeMutablePointer<Double>) {
1215
+ let view = host(pointer)
1216
+ let size: CGSize
1217
+ if width < 0 && height < 0 {
1218
+ size = view.controller.view.fittingSize
1219
+ } else {
1220
+ let ideal = view.controller.view.fittingSize
1221
+ size = view.controller.sizeThatFits(in: CGSize(width: width < 0 ? ideal.width : width, height: height < 0 ? .greatestFiniteMagnitude : height))
1222
+ }
1223
+ outWidth.pointee = size.width.isFinite ? Double(size.width) : 0
1224
+ outHeight.pointee = size.height.isFinite ? Double(size.height) : 0
1225
+ }
1226
+
1227
+ /// Acts on the view `tag` as the user would, with `action` (JSON): what a control is set to, a
1228
+ /// press, or a presentation's dismissal. False for a tag or an action the view does not take.
1229
+ @_cdecl("ngn_ui_host_perform")
1230
+ public func ngnUIHostPerform(_ pointer: UnsafeMutableRawPointer, _ tag: Int32, _ action: UnsafePointer<CChar>) -> Bool {
1231
+ let store = host(pointer).store
1232
+ guard let node = store.root?.find(Int(tag)) else { return false }
1233
+ let value = (json(action) as? [String: Any]) ?? [:]
1234
+ switch node.name {
1235
+ case "Button":
1236
+ store.emit(node.tag, "buttonPress", [:])
1237
+ case "MenuView":
1238
+ store.emit(node.tag, "primaryAction", [:])
1239
+ case "ToggleView":
1240
+ guard let on = value["isOn"] as? Bool else { return false }
1241
+ store.user(node, "isOn", on, event: "isOnChange", payload: ["isOn": on])
1242
+ case "SliderView":
1243
+ guard let number = value["value"] as? NSNumber else { return false }
1244
+ uiSlide(node, store, number.doubleValue)
1245
+ case "StepperView":
1246
+ guard let number = value["value"] as? NSNumber else { return false }
1247
+ store.user(node, "value", number.intValue, event: "valueChange", payload: ["value": number.intValue])
1248
+ case "PickerView":
1249
+ guard let tag = uiTag(value["selection"]) else { return false }
1250
+ store.user(node, "selection", uiTagValue(tag), event: "selectionChange", payload: ["selection": uiTagValue(tag)])
1251
+ case "DatePickerView":
1252
+ guard let date = uiDate(value["date"]) else { return false }
1253
+ let ms = date.timeIntervalSince1970 * 1000
1254
+ store.user(node, "selection", ms, event: "dateChange", payload: ["date": ms])
1255
+ case "ColorPickerView":
1256
+ guard let color = uiColor(value["value"]) else { return false }
1257
+ let hex = uiHex(color)
1258
+ store.user(node, "selection", hex, event: "selectionChange", payload: ["value": hex])
1259
+ case "TextFieldView", "SecureFieldView":
1260
+ guard let text = value["text"] as? String else { return false }
1261
+ uiType(node, store, text)
1262
+ case "DisclosureGroupView", "SectionView":
1263
+ guard let expanded = value["isExpanded"] as? Bool else { return false }
1264
+ store.user(node, "isExpanded", expanded, event: "isExpandedChange", payload: ["isExpanded": expanded])
1265
+ case "AlertView", "ConfirmationDialogView", "PopoverView", "BottomSheetView":
1266
+ guard let shown = value["isPresented"] as? Bool else { return false }
1267
+ uiPresented(node, store).wrappedValue = shown
1268
+ case "TabView":
1269
+ guard let selection = value["selection"] as? String else { return false }
1270
+ store.user(node, "selection", selection, event: "selectionChange", payload: ["selection": selection])
1271
+ case "ListView":
1272
+ guard let selection = value["selection"] as? [Any] else { return false }
1273
+ store.user(node, "selection", selection, event: "selectionChange", payload: ["selection": selection])
1274
+ default:
1275
+ return false
1276
+ }
1277
+ return true
1278
+ }
1279
+
1280
+ /// Whether the renderer draws the iOS view `name`.
1281
+ @_cdecl("ngn_ui_draws")
1282
+ public func ngnUIDraws(_ name: UnsafePointer<CChar>) -> Bool {
1283
+ uiDrawn.contains(String(cString: name))
1284
+ }