@native-sdk/cli 0.0.0 → 0.4.1

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 (373) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/assets/icon.icns +0 -0
  5. package/assets/icon.ico +0 -0
  6. package/assets/icon.png +0 -0
  7. package/assets/icon.svg +15 -0
  8. package/assets/native-sdk.entitlements +10 -0
  9. package/assets/native-sdk.manifest +12 -0
  10. package/bin/native.js +156 -0
  11. package/build/app.zig +716 -0
  12. package/build.zig +2593 -0
  13. package/build.zig.zon +24 -0
  14. package/native-sdk.d.ts +615 -0
  15. package/package.json +45 -8
  16. package/skill-data/automation/SKILL.md +248 -0
  17. package/skill-data/core/SKILL.md +249 -0
  18. package/skill-data/core/references/app-model-runtime.md +141 -0
  19. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  20. package/skill-data/core/references/frontend-assets.md +124 -0
  21. package/skill-data/core/references/project-anatomy.md +108 -0
  22. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  23. package/skill-data/native-ui/SKILL.md +1080 -0
  24. package/skills/native-sdk/SKILL.md +33 -0
  25. package/src/app_runner/root.zig +740 -0
  26. package/src/assets/root.zig +20 -0
  27. package/src/automation/protocol.zig +285 -0
  28. package/src/automation/root.zig +13 -0
  29. package/src/automation/server.zig +506 -0
  30. package/src/automation/snapshot.zig +1202 -0
  31. package/src/automation/watcher.zig +165 -0
  32. package/src/bridge/root.zig +507 -0
  33. package/src/debug/root.zig +246 -0
  34. package/src/embed/app_exports.zig +11 -0
  35. package/src/embed/c_api.zig +793 -0
  36. package/src/embed/c_exports.zig +10 -0
  37. package/src/embed/chrome.zig +168 -0
  38. package/src/embed/conversions.zig +359 -0
  39. package/src/embed/host.zig +960 -0
  40. package/src/embed/root.zig +81 -0
  41. package/src/embed/tests.zig +2552 -0
  42. package/src/embed/types.zig +382 -0
  43. package/src/embed/ui_host.zig +289 -0
  44. package/src/extensions/root.zig +197 -0
  45. package/src/frontend/root.zig +48 -0
  46. package/src/js/root.zig +65 -0
  47. package/src/platform/android/NativeSdkActivity.java +1370 -0
  48. package/src/platform/android/android_host.c +696 -0
  49. package/src/platform/android/files.zig +9 -0
  50. package/src/platform/android/native_sdk_app.h +237 -0
  51. package/src/platform/ios/files.zig +8 -0
  52. package/src/platform/ios/native_sdk_app.h +289 -0
  53. package/src/platform/ios/uikit_host.m +2739 -0
  54. package/src/platform/linux/cef_host.cpp +599 -0
  55. package/src/platform/linux/gtk_host.c +5362 -0
  56. package/src/platform/linux/gtk_host.h +265 -0
  57. package/src/platform/linux/root.zig +1519 -0
  58. package/src/platform/macos/appkit_host.h +604 -0
  59. package/src/platform/macos/appkit_host.m +10392 -0
  60. package/src/platform/macos/automation_host.h +14 -0
  61. package/src/platform/macos/automation_host.m +12 -0
  62. package/src/platform/macos/cef_host.mm +3028 -0
  63. package/src/platform/macos/root.zig +2260 -0
  64. package/src/platform/null_platform.zig +2232 -0
  65. package/src/platform/null_platform_tests.zig +670 -0
  66. package/src/platform/policy_values.zig +14 -0
  67. package/src/platform/root.zig +181 -0
  68. package/src/platform/types.zig +2681 -0
  69. package/src/platform/windows/cef_host.cpp +3 -0
  70. package/src/platform/windows/root.zig +1521 -0
  71. package/src/platform/windows/webview2_host.cpp +6230 -0
  72. package/src/primitives/app_dirs/root.zig +440 -0
  73. package/src/primitives/app_manifest/root.zig +109 -0
  74. package/src/primitives/app_manifest/tests.zig +758 -0
  75. package/src/primitives/app_manifest/types.zig +587 -0
  76. package/src/primitives/app_manifest/validation.zig +828 -0
  77. package/src/primitives/assets/root.zig +520 -0
  78. package/src/primitives/canvas/a11y_audit.zig +390 -0
  79. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  80. package/src/primitives/canvas/app_icon.zig +1590 -0
  81. package/src/primitives/canvas/chart.zig +392 -0
  82. package/src/primitives/canvas/chart_tests.zig +751 -0
  83. package/src/primitives/canvas/commands.zig +446 -0
  84. package/src/primitives/canvas/drawing.zig +309 -0
  85. package/src/primitives/canvas/equality.zig +316 -0
  86. package/src/primitives/canvas/events.zig +696 -0
  87. package/src/primitives/canvas/font_coverage.zig +118 -0
  88. package/src/primitives/canvas/font_ttf.zig +510 -0
  89. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  90. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  91. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  92. package/src/primitives/canvas/frame.zig +679 -0
  93. package/src/primitives/canvas/frame_metrics.zig +462 -0
  94. package/src/primitives/canvas/gpu.zig +639 -0
  95. package/src/primitives/canvas/hash.zig +112 -0
  96. package/src/primitives/canvas/icons/alert.svg +1 -0
  97. package/src/primitives/canvas/icons/archive.svg +1 -0
  98. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  99. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  100. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  101. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  102. package/src/primitives/canvas/icons/check.svg +1 -0
  103. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  104. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  105. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  106. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  107. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  108. package/src/primitives/canvas/icons/clock.svg +1 -0
  109. package/src/primitives/canvas/icons/copy.svg +1 -0
  110. package/src/primitives/canvas/icons/download.svg +1 -0
  111. package/src/primitives/canvas/icons/edit.svg +1 -0
  112. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  113. package/src/primitives/canvas/icons/external-link.svg +1 -0
  114. package/src/primitives/canvas/icons/eye.svg +1 -0
  115. package/src/primitives/canvas/icons/file-text.svg +1 -0
  116. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  117. package/src/primitives/canvas/icons/folder.svg +1 -0
  118. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  119. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  120. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  121. package/src/primitives/canvas/icons/info.svg +1 -0
  122. package/src/primitives/canvas/icons/menu.svg +1 -0
  123. package/src/primitives/canvas/icons/missing.svg +1 -0
  124. package/src/primitives/canvas/icons/moon.svg +1 -0
  125. package/src/primitives/canvas/icons/music.svg +1 -0
  126. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  127. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  128. package/src/primitives/canvas/icons/pause.svg +1 -0
  129. package/src/primitives/canvas/icons/play.svg +1 -0
  130. package/src/primitives/canvas/icons/plus.svg +1 -0
  131. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  132. package/src/primitives/canvas/icons/repeat.svg +1 -0
  133. package/src/primitives/canvas/icons/save.svg +1 -0
  134. package/src/primitives/canvas/icons/search.svg +1 -0
  135. package/src/primitives/canvas/icons/send.svg +1 -0
  136. package/src/primitives/canvas/icons/settings.svg +1 -0
  137. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  138. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  139. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  140. package/src/primitives/canvas/icons/sun.svg +1 -0
  141. package/src/primitives/canvas/icons/terminal.svg +1 -0
  142. package/src/primitives/canvas/icons/trash.svg +1 -0
  143. package/src/primitives/canvas/icons/volume.svg +1 -0
  144. package/src/primitives/canvas/icons/wrench.svg +1 -0
  145. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  146. package/src/primitives/canvas/icons/x.svg +1 -0
  147. package/src/primitives/canvas/icons.zig +249 -0
  148. package/src/primitives/canvas/layout_audit.zig +744 -0
  149. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  150. package/src/primitives/canvas/markdown.zig +1031 -0
  151. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  152. package/src/primitives/canvas/markdown_tests.zig +538 -0
  153. package/src/primitives/canvas/plan_key_index.zig +120 -0
  154. package/src/primitives/canvas/png.zig +355 -0
  155. package/src/primitives/canvas/reference.zig +1457 -0
  156. package/src/primitives/canvas/reference_blur.zig +104 -0
  157. package/src/primitives/canvas/reference_memo.zig +322 -0
  158. package/src/primitives/canvas/reference_paths.zig +184 -0
  159. package/src/primitives/canvas/reference_tests.zig +1650 -0
  160. package/src/primitives/canvas/render.zig +747 -0
  161. package/src/primitives/canvas/render_effects.zig +255 -0
  162. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  163. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  164. package/src/primitives/canvas/render_images.zig +247 -0
  165. package/src/primitives/canvas/render_layers.zig +260 -0
  166. package/src/primitives/canvas/render_paths.zig +347 -0
  167. package/src/primitives/canvas/render_resources.zig +51 -0
  168. package/src/primitives/canvas/render_tests.zig +3186 -0
  169. package/src/primitives/canvas/root.zig +744 -0
  170. package/src/primitives/canvas/serialization.zig +1528 -0
  171. package/src/primitives/canvas/svg_icon.zig +636 -0
  172. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  173. package/src/primitives/canvas/test_support.zig +422 -0
  174. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  175. package/src/primitives/canvas/tests.zig +30 -0
  176. package/src/primitives/canvas/text.zig +82 -0
  177. package/src/primitives/canvas/text_atlas.zig +408 -0
  178. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  179. package/src/primitives/canvas/text_interaction.zig +615 -0
  180. package/src/primitives/canvas/text_layout.zig +1069 -0
  181. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  182. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  183. package/src/primitives/canvas/text_layout_types.zig +128 -0
  184. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  185. package/src/primitives/canvas/text_metrics.zig +309 -0
  186. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  187. package/src/primitives/canvas/text_span_tests.zig +608 -0
  188. package/src/primitives/canvas/text_spans.zig +1010 -0
  189. package/src/primitives/canvas/text_tests.zig +1949 -0
  190. package/src/primitives/canvas/themes/geist.zig +470 -0
  191. package/src/primitives/canvas/tokens.zig +1522 -0
  192. package/src/primitives/canvas/ui.zig +2686 -0
  193. package/src/primitives/canvas/ui_markup.zig +3791 -0
  194. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  195. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  196. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  197. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  198. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  199. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  200. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  201. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  202. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  203. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  204. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  205. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  206. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  207. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  208. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  209. package/src/primitives/canvas/ui_provenance.zig +96 -0
  210. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  211. package/src/primitives/canvas/ui_schema.zig +825 -0
  212. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  213. package/src/primitives/canvas/ui_tests.zig +1432 -0
  214. package/src/primitives/canvas/vector.zig +919 -0
  215. package/src/primitives/canvas/vector_tests.zig +547 -0
  216. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  217. package/src/primitives/canvas/virtual_extents.zig +540 -0
  218. package/src/primitives/canvas/widget_access.zig +208 -0
  219. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  220. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  221. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  222. package/src/primitives/canvas/widget_layout.zig +2055 -0
  223. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  224. package/src/primitives/canvas/widget_metrics.zig +228 -0
  225. package/src/primitives/canvas/widget_render.zig +2534 -0
  226. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  227. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  228. package/src/primitives/canvas/widget_render_style.zig +626 -0
  229. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  230. package/src/primitives/canvas/widget_routing.zig +475 -0
  231. package/src/primitives/canvas/widget_runtime.zig +307 -0
  232. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  233. package/src/primitives/canvas/widget_semantics.zig +480 -0
  234. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  235. package/src/primitives/canvas/widget_tests.zig +8 -0
  236. package/src/primitives/canvas/widget_text_input.zig +351 -0
  237. package/src/primitives/canvas/widget_text_select.zig +147 -0
  238. package/src/primitives/canvas/widget_tree.zig +232 -0
  239. package/src/primitives/canvas/widgets.zig +1319 -0
  240. package/src/primitives/diagnostics/root.zig +445 -0
  241. package/src/primitives/geometry/root.zig +889 -0
  242. package/src/primitives/json/root.zig +272 -0
  243. package/src/primitives/platform_info/root.zig +450 -0
  244. package/src/primitives/trace/root.zig +569 -0
  245. package/src/root.zig +165 -0
  246. package/src/runtime/api.zig +431 -0
  247. package/src/runtime/async_bridge.zig +49 -0
  248. package/src/runtime/automation_commands.zig +686 -0
  249. package/src/runtime/automation_liveness_tests.zig +140 -0
  250. package/src/runtime/automation_snapshot.zig +246 -0
  251. package/src/runtime/automation_widget_dispatch.zig +617 -0
  252. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  253. package/src/runtime/bridge_payload.zig +194 -0
  254. package/src/runtime/bridge_permission_tests.zig +551 -0
  255. package/src/runtime/bridge_responses.zig +414 -0
  256. package/src/runtime/builtin_bridge.zig +554 -0
  257. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  258. package/src/runtime/canvas_font_tests.zig +410 -0
  259. package/src/runtime/canvas_fonts.zig +229 -0
  260. package/src/runtime/canvas_frame.zig +1734 -0
  261. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  262. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  263. package/src/runtime/canvas_frame_helpers.zig +414 -0
  264. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  265. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  266. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  267. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  268. package/src/runtime/canvas_frame_tests.zig +9 -0
  269. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  270. package/src/runtime/canvas_image_tests.zig +362 -0
  271. package/src/runtime/canvas_images.zig +224 -0
  272. package/src/runtime/canvas_limits.zig +317 -0
  273. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  274. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  275. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  276. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  277. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  278. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  279. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  280. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  281. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  282. package/src/runtime/canvas_widget_display.zig +677 -0
  283. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  284. package/src/runtime/canvas_widget_events.zig +1098 -0
  285. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  286. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  287. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  288. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  289. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  290. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  291. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  292. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  293. package/src/runtime/canvas_widget_state.zig +798 -0
  294. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  295. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  296. package/src/runtime/clock.zig +231 -0
  297. package/src/runtime/core.zig +927 -0
  298. package/src/runtime/effects.zig +4197 -0
  299. package/src/runtime/effects_audio_tests.zig +690 -0
  300. package/src/runtime/effects_clipboard_tests.zig +317 -0
  301. package/src/runtime/effects_fetch_tests.zig +1031 -0
  302. package/src/runtime/effects_file_tests.zig +407 -0
  303. package/src/runtime/effects_tests.zig +1251 -0
  304. package/src/runtime/flow.zig +1175 -0
  305. package/src/runtime/frame_profile.zig +221 -0
  306. package/src/runtime/gpu_surface_events.zig +639 -0
  307. package/src/runtime/launch_timing.zig +59 -0
  308. package/src/runtime/markdown_app_tests.zig +224 -0
  309. package/src/runtime/native_command_event_tests.zig +431 -0
  310. package/src/runtime/platform_bridge_tests.zig +8 -0
  311. package/src/runtime/platform_config_tests.zig +392 -0
  312. package/src/runtime/root.zig +150 -0
  313. package/src/runtime/runtime_event_tests.zig +1079 -0
  314. package/src/runtime/session_journal.zig +1522 -0
  315. package/src/runtime/session_record.zig +332 -0
  316. package/src/runtime/session_replay.zig +274 -0
  317. package/src/runtime/session_state.zig +30 -0
  318. package/src/runtime/session_tests.zig +399 -0
  319. package/src/runtime/shell_layout.zig +472 -0
  320. package/src/runtime/shell_layout_tests.zig +1246 -0
  321. package/src/runtime/shell_view_tests.zig +604 -0
  322. package/src/runtime/state.zig +110 -0
  323. package/src/runtime/system_services.zig +392 -0
  324. package/src/runtime/test_support.zig +79 -0
  325. package/src/runtime/tests.zig +30 -0
  326. package/src/runtime/ui_app.zig +3290 -0
  327. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  328. package/src/runtime/ui_app_provenance.zig +370 -0
  329. package/src/runtime/ui_app_tests.zig +3254 -0
  330. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  331. package/src/runtime/ui_app_window_tests.zig +442 -0
  332. package/src/runtime/validation.zig +206 -0
  333. package/src/runtime/view.zig +908 -0
  334. package/src/runtime/view_canvas.zig +850 -0
  335. package/src/runtime/view_widget_control.zig +433 -0
  336. package/src/runtime/view_widget_scroll.zig +360 -0
  337. package/src/runtime/view_widget_text.zig +275 -0
  338. package/src/runtime/view_widget_tree.zig +843 -0
  339. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  340. package/src/runtime/widget_bridge.zig +231 -0
  341. package/src/runtime/window_command_bridge_tests.zig +403 -0
  342. package/src/runtime/window_storage.zig +255 -0
  343. package/src/runtime/window_view_runtime.zig +727 -0
  344. package/src/runtime/window_views.zig +334 -0
  345. package/src/security/root.zig +118 -0
  346. package/src/tooling/android.zig +1172 -0
  347. package/src/tooling/assets.zig +128 -0
  348. package/src/tooling/buildgraph.zig +379 -0
  349. package/src/tooling/cef.zig +671 -0
  350. package/src/tooling/codesign.zig +172 -0
  351. package/src/tooling/components/identity_tests.zig +185 -0
  352. package/src/tooling/components/stepper.zig +113 -0
  353. package/src/tooling/components/timeline.native +27 -0
  354. package/src/tooling/components/timeline_item.zig +131 -0
  355. package/src/tooling/default_icon.icns +0 -0
  356. package/src/tooling/default_icon.png +0 -0
  357. package/src/tooling/dev.zig +172 -0
  358. package/src/tooling/doctor.zig +349 -0
  359. package/src/tooling/eject_components.zig +170 -0
  360. package/src/tooling/embedlib.zig +290 -0
  361. package/src/tooling/ios.zig +528 -0
  362. package/src/tooling/manifest.zig +1939 -0
  363. package/src/tooling/package.zig +2388 -0
  364. package/src/tooling/process_tree.zig +114 -0
  365. package/src/tooling/raw_manifest.zig +193 -0
  366. package/src/tooling/root.zig +22 -0
  367. package/src/tooling/templates.zig +3191 -0
  368. package/src/tooling/toolchain.zig +371 -0
  369. package/src/tooling/verbs.zig +204 -0
  370. package/src/tooling/web_engine.zig +135 -0
  371. package/src/tooling/xcodeproj.zig +462 -0
  372. package/src/window_state/root.zig +507 -0
  373. package/index.js +0 -2
@@ -0,0 +1,3254 @@
1
+ const std = @import("std");
2
+ const geometry = @import("geometry");
3
+ const canvas = @import("canvas");
4
+ const app_manifest = @import("app_manifest");
5
+ const core = @import("core.zig");
6
+ const ui_app_model = @import("ui_app.zig");
7
+ const effects_mod = @import("effects.zig");
8
+ const automation = @import("../automation/root.zig");
9
+ const zero_platform = @import("../platform/root.zig");
10
+ const null_platform_mod = @import("../platform/null_platform.zig");
11
+
12
+ const canvas_label = "counter-canvas";
13
+
14
+ const CounterModel = struct {
15
+ count: u32 = 0,
16
+ };
17
+
18
+ const CounterMsg = union(enum) {
19
+ increment,
20
+ reset,
21
+ };
22
+
23
+ const CounterApp = ui_app_model.UiApp(CounterModel, CounterMsg);
24
+
25
+ fn counterUpdate(model: *CounterModel, msg: CounterMsg) void {
26
+ switch (msg) {
27
+ .increment => model.count += 1,
28
+ .reset => model.count = 0,
29
+ }
30
+ }
31
+
32
+ fn counterView(ui: *CounterApp.Ui, model: *const CounterModel) CounterApp.Ui.Node {
33
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
34
+ ui.text(.{}, ui.fmt("Count {d}", .{model.count})),
35
+ ui.button(.{ .variant = .primary, .on_press = .increment }, "Increment"),
36
+ ui.button(.{ .on_press = .reset }, "Reset"),
37
+ });
38
+ }
39
+
40
+ fn counterCommand(name: []const u8) ?CounterMsg {
41
+ if (std.mem.eql(u8, name, "counter.reset")) return .reset;
42
+ return null;
43
+ }
44
+
45
+ const counter_views = [_]app_manifest.ShellView{
46
+ .{ .label = canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
47
+ };
48
+ const counter_windows = [_]app_manifest.ShellWindow{.{
49
+ .label = "main",
50
+ .title = "Counter",
51
+ .width = 400,
52
+ .height = 300,
53
+ .views = &counter_views,
54
+ }};
55
+ const counter_scene: app_manifest.ShellConfig = .{ .windows = &counter_windows };
56
+
57
+ fn counterOptions() CounterApp.Options {
58
+ return .{
59
+ .name = "ui-app-counter",
60
+ .scene = counter_scene,
61
+ .canvas_label = canvas_label,
62
+ .update = counterUpdate,
63
+ .view = counterView,
64
+ .on_command = counterCommand,
65
+ };
66
+ }
67
+
68
+ fn findWidgetIdByText(tree: anytype, kind: canvas.WidgetKind, text: []const u8) ?canvas.ObjectId {
69
+ return findIn(tree.root, kind, text);
70
+ }
71
+
72
+ fn findIn(widget: canvas.Widget, kind: canvas.WidgetKind, text: []const u8) ?canvas.ObjectId {
73
+ if (widget.kind == kind and std.mem.eql(u8, widget.text, text)) return widget.id;
74
+ for (widget.children) |child| {
75
+ if (findIn(child, kind, text)) |id| return id;
76
+ }
77
+ return null;
78
+ }
79
+
80
+ fn retainedTextExists(runtime: *core.Runtime, text: []const u8) !bool {
81
+ const layout = try runtime.canvasWidgetLayout(1, canvas_label);
82
+ for (layout.nodes) |node| {
83
+ if (node.widget.kind == .text and std.mem.eql(u8, node.widget.text, text)) return true;
84
+ }
85
+ return false;
86
+ }
87
+
88
+ test "ui app owns install, dispatch, and rebuild end to end" {
89
+ // The runtime and the app are both large structs; keep them off the
90
+ // test thread's stack.
91
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
92
+ defer harness.destroy(std.testing.allocator);
93
+ harness.null_platform.gpu_surfaces = true;
94
+
95
+ const app_state = try std.testing.allocator.create(CounterApp);
96
+ defer std.testing.allocator.destroy(app_state);
97
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, counterOptions());
98
+ defer app_state.deinit();
99
+ const app = app_state.app();
100
+ try harness.start(app);
101
+
102
+ // First gpu frame installs the widget tree and display list.
103
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
104
+ .label = canvas_label,
105
+ .size = geometry.SizeF.init(400, 300),
106
+ .scale_factor = 2,
107
+ .frame_index = 1,
108
+ .timestamp_ns = 1_000_000,
109
+ .nonblank = true,
110
+ } });
111
+ try std.testing.expect(app_state.installed);
112
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
113
+
114
+ // Automation clicks flow through typed dispatch into update + rebuild.
115
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
116
+ var command_buffer: [96]u8 = undefined;
117
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
118
+ try harness.runtime.dispatchAutomationCommand(app, click);
119
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
120
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
121
+
122
+ try harness.runtime.dispatchAutomationCommand(app, click);
123
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.count);
124
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 2"));
125
+
126
+ // Structural identity survives the rebuilds the dispatches triggered.
127
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
128
+
129
+ // Shell command events map into messages through on_command.
130
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "counter.reset", .window_id = 1 } });
131
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.count);
132
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
133
+ }
134
+
135
+ // -------------------------------------- context-menu fallback fixture
136
+
137
+ const TaskRowModel = struct {
138
+ completed: u32 = 0,
139
+ deleted: u32 = 0,
140
+ };
141
+
142
+ const TaskRowMsg = union(enum) {
143
+ complete,
144
+ delete,
145
+ };
146
+
147
+ const TaskRowApp = ui_app_model.UiApp(TaskRowModel, TaskRowMsg);
148
+
149
+ fn taskRowUpdate(model: *TaskRowModel, msg: TaskRowMsg) void {
150
+ switch (msg) {
151
+ .complete => model.completed += 1,
152
+ .delete => model.deleted += 1,
153
+ }
154
+ }
155
+
156
+ fn taskRowView(ui: *TaskRowApp.Ui, model: *const TaskRowModel) TaskRowApp.Ui.Node {
157
+ _ = model;
158
+ var row = ui.el(.list_item, .{
159
+ .padding = 8,
160
+ .context_menu = &.{
161
+ .{ .label = "Complete", .msg = .complete },
162
+ .{ .separator = true },
163
+ .{ .label = "Delete", .msg = .delete },
164
+ },
165
+ }, .{
166
+ ui.text(.{ .grow = 1 }, "Task"),
167
+ });
168
+ row.widget.text = "Task";
169
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{row});
170
+ }
171
+
172
+ fn taskRowOptions() TaskRowApp.Options {
173
+ return .{
174
+ .name = "ui-app-task-rows",
175
+ .scene = counter_scene,
176
+ .canvas_label = canvas_label,
177
+ .update = taskRowUpdate,
178
+ .view = taskRowView,
179
+ };
180
+ }
181
+
182
+ fn retainedWidgetKindExists(runtime: *core.Runtime, kind: canvas.WidgetKind) !bool {
183
+ const layout = try runtime.canvasWidgetLayout(1, canvas_label);
184
+ for (layout.nodes) |node| {
185
+ if (node.widget.kind == kind) return true;
186
+ }
187
+ return false;
188
+ }
189
+
190
+ test "a declared context menu presents as the anchored fallback surface on presenter-less hosts, end to end" {
191
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
192
+ defer harness.destroy(std.testing.allocator);
193
+ harness.null_platform.gpu_surfaces = true;
194
+ // A host without a native menu presenter (Linux GTK, Windows Win32
195
+ // today). Service pointers are captured at init, so re-capture.
196
+ harness.null_platform.context_menus = false;
197
+ harness.runtime.options.platform = harness.null_platform.platform();
198
+
199
+ const app_state = try std.testing.allocator.create(TaskRowApp);
200
+ defer std.testing.allocator.destroy(app_state);
201
+ app_state.* = TaskRowApp.init(std.heap.page_allocator, .{}, taskRowOptions());
202
+ defer app_state.deinit();
203
+ const app = app_state.app();
204
+ try harness.start(app);
205
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
206
+ .label = canvas_label,
207
+ .size = geometry.SizeF.init(400, 300),
208
+ .scale_factor = 2,
209
+ .frame_index = 1,
210
+ .timestamp_ns = 1_000_000,
211
+ .nonblank = true,
212
+ } });
213
+ try std.testing.expect(app_state.installed);
214
+
215
+ // At rest: no surface mounted, no fallback state.
216
+ try std.testing.expect(!try retainedWidgetKindExists(&harness.runtime, .dropdown_menu));
217
+ try std.testing.expect(app_state.tree.?.context_menu_fallback == null);
218
+
219
+ // Right-click the row: the SAME declared menu mounts as an anchored
220
+ // canvas surface (no native presenter to hand it to).
221
+ const row_id = findWidgetIdByText(app_state.tree.?, .list_item, "Task").?;
222
+ var command_buffer: [96]u8 = undefined;
223
+ const context_press = try std.fmt.bufPrint(&command_buffer, "widget-context-press {s} {d}", .{ canvas_label, row_id });
224
+ try harness.runtime.dispatchAutomationCommand(app, context_press);
225
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.context_menu_request_count);
226
+ const fallback = app_state.tree.?.context_menu_fallback orelse return error.TestUnexpectedResult;
227
+ try std.testing.expectEqual(row_id, fallback.target_id);
228
+ try std.testing.expectEqual(@as(usize, 3), fallback.item_ids.len);
229
+ try std.testing.expectEqual(@as(canvas.ObjectId, 0), fallback.item_ids[1]);
230
+ try std.testing.expect(try retainedWidgetKindExists(&harness.runtime, .dropdown_menu));
231
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .menu_item, "Delete") != null);
232
+
233
+ // Clicking "Delete" routes through the target's .context_menu
234
+ // handler — the same entry a native selection resolves — and closes
235
+ // the surface.
236
+ var click_buffer: [96]u8 = undefined;
237
+ const click_delete = try std.fmt.bufPrint(&click_buffer, "widget-click {s} {d}", .{ canvas_label, fallback.item_ids[2] });
238
+ try harness.runtime.dispatchAutomationCommand(app, click_delete);
239
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.deleted);
240
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.completed);
241
+ try std.testing.expect(app_state.tree.?.context_menu_fallback == null);
242
+ try std.testing.expect(!try retainedWidgetKindExists(&harness.runtime, .dropdown_menu));
243
+
244
+ // Reopen and dismiss (Escape/outside-click/automation all land on
245
+ // the same dismissal machinery): the surface closes, no Msg fires.
246
+ try harness.runtime.dispatchAutomationCommand(app, context_press);
247
+ const reopened = app_state.tree.?.context_menu_fallback orelse return error.TestUnexpectedResult;
248
+ var dismiss_buffer: [96]u8 = undefined;
249
+ const dismiss = try std.fmt.bufPrint(&dismiss_buffer, "widget-action {s} {d} dismiss", .{ canvas_label, reopened.surface_id });
250
+ try harness.runtime.dispatchAutomationCommand(app, dismiss);
251
+ try std.testing.expect(app_state.tree.?.context_menu_fallback == null);
252
+ try std.testing.expect(!try retainedWidgetKindExists(&harness.runtime, .dropdown_menu));
253
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.deleted);
254
+
255
+ // The widget-context-menu verb converges on the same dispatch with
256
+ // no surface involved at all.
257
+ var verb_buffer: [96]u8 = undefined;
258
+ const invoke_complete = try std.fmt.bufPrint(&verb_buffer, "widget-context-menu {s} {d} 0", .{ canvas_label, row_id });
259
+ try harness.runtime.dispatchAutomationCommand(app, invoke_complete);
260
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.completed);
261
+ try std.testing.expect(app_state.tree.?.context_menu_fallback == null);
262
+ }
263
+
264
+ // ------------------------------------------------- scroll event fixture
265
+
266
+ const FeedModel = struct {
267
+ /// Elm-style mirror of the scroll offset: on_scroll delivers the
268
+ /// offset the runtime already applied, the model stores it, and the
269
+ /// view echoes it back into `value` — which must never fight the
270
+ /// scroll reconcile rule (the echoed source value equals the runtime
271
+ /// offset).
272
+ offset: f32 = 0,
273
+ viewport_extent: f32 = 0,
274
+ content_extent: f32 = 0,
275
+ scroll_events: u32 = 0,
276
+ };
277
+
278
+ const FeedMsg = union(enum) {
279
+ feed_scrolled: canvas.ScrollState,
280
+ };
281
+
282
+ const FeedApp = ui_app_model.UiApp(FeedModel, FeedMsg);
283
+
284
+ fn feedUpdate(model: *FeedModel, msg: FeedMsg) void {
285
+ switch (msg) {
286
+ .feed_scrolled => |scroll_state| {
287
+ model.offset = scroll_state.offset;
288
+ model.viewport_extent = scroll_state.viewport_extent;
289
+ model.content_extent = scroll_state.content_extent;
290
+ model.scroll_events += 1;
291
+ },
292
+ }
293
+ }
294
+
295
+ fn feedView(ui: *FeedApp.Ui, model: *const FeedModel) FeedApp.Ui.Node {
296
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
297
+ ui.scroll(.{
298
+ .height = 96,
299
+ .value = model.offset,
300
+ .on_scroll = FeedApp.Ui.scrollMsg(.feed_scrolled),
301
+ }, ui.column(.{ .gap = 4 }, .{
302
+ ui.text(.{ .height = 80 }, "Row one"),
303
+ ui.text(.{ .height = 80 }, "Row two"),
304
+ ui.text(.{ .height = 80 }, "Row three"),
305
+ ui.text(.{ .height = 80 }, "Row four"),
306
+ })),
307
+ ui.text(.{}, ui.fmt("Offset {d:.0}", .{model.offset})),
308
+ });
309
+ }
310
+
311
+ fn feedOptions() FeedApp.Options {
312
+ return .{
313
+ .name = "ui-app-feed",
314
+ .scene = counter_scene,
315
+ .canvas_label = canvas_label,
316
+ .update = feedUpdate,
317
+ .view = feedView,
318
+ };
319
+ }
320
+
321
+ test "ui app on_scroll delivers wheel offsets and the echoed model offset survives the rebuild" {
322
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
323
+ defer harness.destroy(std.testing.allocator);
324
+ harness.null_platform.gpu_surfaces = true;
325
+
326
+ const app_state = try std.testing.allocator.create(FeedApp);
327
+ defer std.testing.allocator.destroy(app_state);
328
+ app_state.* = FeedApp.init(std.heap.page_allocator, .{}, feedOptions());
329
+ defer app_state.deinit();
330
+ const app = app_state.app();
331
+ try harness.start(app);
332
+
333
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
334
+ .label = canvas_label,
335
+ .size = geometry.SizeF.init(400, 300),
336
+ .scale_factor = 2,
337
+ .frame_index = 1,
338
+ .timestamp_ns = 1_000_000,
339
+ .nonblank = true,
340
+ } });
341
+ try std.testing.expect(app_state.installed);
342
+
343
+ const scroll_id = findWidgetIdByKind(app_state.tree.?.root, .scroll_view).?;
344
+ var command_buffer: [96]u8 = undefined;
345
+ const wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 18", .{ canvas_label, scroll_id });
346
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
347
+
348
+ // The wheel dispatched a typed scroll Msg carrying the applied
349
+ // offset and the extents (content spans four 80pt rows + gaps).
350
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.scroll_events);
351
+ try std.testing.expect(app_state.model.offset > 0);
352
+ try std.testing.expect(app_state.model.content_extent > app_state.model.viewport_extent);
353
+
354
+ // The dispatch rebuilt with the echoed offset; the retained runtime
355
+ // offset agrees with the model (echoing never fights the reconcile
356
+ // rule, because the echoed source value IS the runtime offset).
357
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
358
+ try std.testing.expectEqual(app_state.model.offset, layout.findById(scroll_id).?.widget.value);
359
+
360
+ // A second wheel accumulates from the reconciled offset.
361
+ const first_offset = app_state.model.offset;
362
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
363
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.scroll_events);
364
+ try std.testing.expect(app_state.model.offset > first_offset);
365
+ }
366
+
367
+ test "ui app presents pixels when the packet service is unsupported" {
368
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
369
+ defer harness.destroy(std.testing.allocator);
370
+ harness.null_platform.gpu_surfaces = true;
371
+ harness.null_platform.gpu_surface_packets = false;
372
+
373
+ const app_state = try std.testing.allocator.create(CounterApp);
374
+ defer std.testing.allocator.destroy(app_state);
375
+ app_state.* = CounterApp.init(std.testing.allocator, .{}, counterOptions());
376
+ defer app_state.deinit();
377
+ const app = app_state.app();
378
+ try harness.start(app);
379
+
380
+ // The installing frame falls back from the failing packet presenter to
381
+ // the CPU pixel path: the widget tree installs and the reference-rendered
382
+ // surface reaches the platform at device resolution.
383
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
384
+ .label = canvas_label,
385
+ .size = geometry.SizeF.init(400, 300),
386
+ .scale_factor = 2,
387
+ .frame_index = 1,
388
+ .timestamp_ns = 1_000_000,
389
+ } });
390
+ try std.testing.expect(app_state.installed);
391
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
392
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.gpu_surface_packet_present_count);
393
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.gpu_surface_present_count);
394
+ try std.testing.expectEqual(@as(usize, 800), harness.null_platform.gpu_surface_present_width);
395
+ try std.testing.expectEqual(@as(usize, 600), harness.null_platform.gpu_surface_present_height);
396
+ try std.testing.expectEqual(@as(f32, 2), harness.null_platform.gpu_surface_present_scale_factor);
397
+ try std.testing.expectEqual(@as(usize, 800 * 600 * 4), harness.null_platform.gpu_surface_present_byte_len);
398
+ try std.testing.expectEqualStrings(
399
+ canvas_label,
400
+ harness.null_platform.gpu_surface_present_label_storage[0..harness.null_platform.gpu_surface_present_label_len],
401
+ );
402
+
403
+ // Model changes keep presenting through the pixel path.
404
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
405
+ var command_buffer: [96]u8 = undefined;
406
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
407
+ try harness.runtime.dispatchAutomationCommand(app, click);
408
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
409
+
410
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
411
+ .label = canvas_label,
412
+ .size = geometry.SizeF.init(400, 300),
413
+ .scale_factor = 2,
414
+ .frame_index = 2,
415
+ .timestamp_ns = 17_000_000,
416
+ } });
417
+ try std.testing.expectEqual(@as(usize, 2), harness.null_platform.gpu_surface_present_count);
418
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.gpu_surface_packet_present_count);
419
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
420
+ }
421
+
422
+ const counter_markup =
423
+ \\<column gap="8" padding="12">
424
+ \\ <text>Count {count}</text>
425
+ \\ <button variant="primary" on-press="increment">Increment</button>
426
+ \\ <button on-press="reset">Reset</button>
427
+ \\</column>
428
+ ;
429
+
430
+ const counter_markup_v2 =
431
+ \\<column gap="8" padding="12">
432
+ \\ <text>Count {count}</text>
433
+ \\ <button variant="primary" on-press="increment">Increment</button>
434
+ \\ <button on-press="reset">Start over</button>
435
+ \\</column>
436
+ ;
437
+
438
+ fn markupCounterOptions() CounterApp.Options {
439
+ return .{
440
+ .name = "ui-app-markup-counter",
441
+ .scene = counter_scene,
442
+ .canvas_label = canvas_label,
443
+ .update = counterUpdate,
444
+ .markup = .{ .source = counter_markup },
445
+ .on_command = counterCommand,
446
+ };
447
+ }
448
+
449
+ test "markup views drive the ui app loop and hot reload preserves state" {
450
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
451
+ defer harness.destroy(std.testing.allocator);
452
+ harness.null_platform.gpu_surfaces = true;
453
+
454
+ const app_state = try std.testing.allocator.create(CounterApp);
455
+ defer std.testing.allocator.destroy(app_state);
456
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, markupCounterOptions());
457
+ defer app_state.deinit();
458
+ const app = app_state.app();
459
+ try harness.start(app);
460
+
461
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
462
+ .label = canvas_label,
463
+ .size = geometry.SizeF.init(400, 300),
464
+ .scale_factor = 2,
465
+ .frame_index = 1,
466
+ .timestamp_ns = 1_000_000,
467
+ .nonblank = true,
468
+ } });
469
+ try std.testing.expect(app_state.installed);
470
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
471
+
472
+ // Markup-declared handlers dispatch through the same typed loop.
473
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
474
+ var command_buffer: [96]u8 = undefined;
475
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
476
+ try harness.runtime.dispatchAutomationCommand(app, click);
477
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
478
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
479
+
480
+ // Hot reload: new view source, model state kept, ids stable.
481
+ try app_state.reloadMarkup(counter_markup_v2);
482
+ try app_state.rebuild(&harness.runtime, 1);
483
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
484
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
485
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
486
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
487
+
488
+ // A broken reload keeps the last good view and records the diagnostic.
489
+ try std.testing.expectError(error.MarkupSyntax, app_state.reloadMarkup("<column><oops</column>"));
490
+ try std.testing.expect(app_state.markup_diagnostic != null);
491
+ try app_state.rebuild(&harness.runtime, 1);
492
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
493
+ }
494
+
495
+ const counter_timer_id: u64 = 42;
496
+
497
+ fn counterTimer(id: u64, timestamp_ns: u64) ?CounterMsg {
498
+ _ = timestamp_ns;
499
+ if (id == counter_timer_id) return .increment;
500
+ return null;
501
+ }
502
+
503
+ test "ui app maps timer events into messages and rebuilds" {
504
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
505
+ defer harness.destroy(std.testing.allocator);
506
+ harness.null_platform.gpu_surfaces = true;
507
+
508
+ var options = counterOptions();
509
+ options.on_timer = counterTimer;
510
+ const app_state = try std.testing.allocator.create(CounterApp);
511
+ defer std.testing.allocator.destroy(app_state);
512
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
513
+ defer app_state.deinit();
514
+ const app = app_state.app();
515
+ try harness.start(app);
516
+
517
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
518
+ .label = canvas_label,
519
+ .size = geometry.SizeF.init(400, 300),
520
+ .scale_factor = 2,
521
+ .frame_index = 1,
522
+ .timestamp_ns = 1_000_000,
523
+ .nonblank = true,
524
+ } });
525
+ try std.testing.expect(app_state.installed);
526
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
527
+
528
+ // A fired timer maps through on_timer into update + rebuild.
529
+ try harness.runtime.startTimer(counter_timer_id, 100_000_000, true);
530
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(counter_timer_id, 2_000_000).?);
531
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
532
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
533
+
534
+ // Cancelled timers stop producing events entirely.
535
+ try harness.runtime.cancelTimer(counter_timer_id);
536
+ try std.testing.expect(harness.null_platform.fireTimer(counter_timer_id, 3_000_000) == null);
537
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
538
+ }
539
+
540
+ // -------------------------------------------------------- transform channel
541
+
542
+ const SlideModel = struct {
543
+ tick: u32 = 0,
544
+ };
545
+
546
+ const SlideMsg = union(enum) {
547
+ tick,
548
+ };
549
+
550
+ const SlideApp = ui_app_model.UiApp(SlideModel, SlideMsg);
551
+
552
+ const slide_timer_id: u64 = 43;
553
+
554
+ fn slideUpdate(model: *SlideModel, msg: SlideMsg) void {
555
+ switch (msg) {
556
+ .tick => model.tick += 1,
557
+ }
558
+ }
559
+
560
+ fn slideOffset(tick: u32) f32 {
561
+ return @as(f32, @floatFromInt(tick)) * 8;
562
+ }
563
+
564
+ fn slideView(ui: *SlideApp.Ui, model: *const SlideModel) SlideApp.Ui.Node {
565
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
566
+ ui.el(.panel, .{
567
+ .transform = canvas.Affine.translate(slideOffset(model.tick), 0),
568
+ .opacity = 0.9,
569
+ .width = 80,
570
+ .height = 40,
571
+ }, .{
572
+ ui.text(.{}, "Slide"),
573
+ }),
574
+ });
575
+ }
576
+
577
+ fn slideTimer(id: u64, timestamp_ns: u64) ?SlideMsg {
578
+ _ = timestamp_ns;
579
+ if (id == slide_timer_id) return .tick;
580
+ return null;
581
+ }
582
+
583
+ fn slideOptions() SlideApp.Options {
584
+ return .{
585
+ .name = "ui-app-slide",
586
+ .scene = counter_scene,
587
+ .canvas_label = canvas_label,
588
+ .update = slideUpdate,
589
+ .view = slideView,
590
+ .on_timer = slideTimer,
591
+ };
592
+ }
593
+
594
+ fn retainedPanelTransform(runtime: *core.Runtime) !canvas.Affine {
595
+ const layout = try runtime.canvasWidgetLayout(1, canvas_label);
596
+ for (layout.nodes) |node| {
597
+ if (node.widget.kind == .panel) return node.widget.transform;
598
+ }
599
+ return error.MissingPanel;
600
+ }
601
+
602
+ test "view-mapped transforms rebuild and invalidate per tick" {
603
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
604
+ defer harness.destroy(std.testing.allocator);
605
+ harness.null_platform.gpu_surfaces = true;
606
+
607
+ const app_state = try std.testing.allocator.create(SlideApp);
608
+ defer std.testing.allocator.destroy(app_state);
609
+ app_state.* = SlideApp.init(std.heap.page_allocator, .{}, slideOptions());
610
+ defer app_state.deinit();
611
+ const app = app_state.app();
612
+ try harness.start(app);
613
+
614
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
615
+ .label = canvas_label,
616
+ .size = geometry.SizeF.init(400, 300),
617
+ .scale_factor = 2,
618
+ .frame_index = 1,
619
+ .timestamp_ns = 1_000_000,
620
+ .nonblank = true,
621
+ } });
622
+ try std.testing.expect(app_state.installed);
623
+ // Tick 0 authors translate(0, 0): the identity default, so the retained
624
+ // tree starts untransformed.
625
+ try std.testing.expectEqualDeep(canvas.Affine.identity(), try retainedPanelTransform(&harness.runtime));
626
+
627
+ // Each fired tick maps model state into a fresh view transform: the
628
+ // rebuilt tree carries it and the dirty machinery schedules a repaint.
629
+ try harness.runtime.startTimer(slide_timer_id, 16_000_000, true);
630
+ harness.runtime.invalidated = false;
631
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(slide_timer_id, 2_000_000).?);
632
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.tick);
633
+ try std.testing.expectEqualDeep(canvas.Affine.translate(8, 0), try retainedPanelTransform(&harness.runtime));
634
+ try std.testing.expect(harness.runtime.invalidated);
635
+
636
+ harness.runtime.invalidated = false;
637
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(slide_timer_id, 18_000_000).?);
638
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.tick);
639
+ try std.testing.expectEqualDeep(canvas.Affine.translate(16, 0), try retainedPanelTransform(&harness.runtime));
640
+ try std.testing.expect(harness.runtime.invalidated);
641
+ }
642
+
643
+ // ------------------------------------------------------------------ hooks
644
+
645
+ const ThemedModel = struct {
646
+ count: u32 = 0,
647
+ dark: bool = false,
648
+ high_contrast: bool = false,
649
+ frame_reports: u32 = 0,
650
+ slider_value: f32 = 0.5,
651
+ /// How many times `on_change` reached update — the pointer test
652
+ /// counts one dispatch per gesture step (down, each drag move).
653
+ slider_changes: u32 = 0,
654
+ };
655
+
656
+ const ThemedMsg = union(enum) {
657
+ increment,
658
+ appearance: struct { dark: bool, high_contrast: bool },
659
+ frame_seen,
660
+ slider_changed,
661
+ };
662
+
663
+ const ThemedApp = ui_app_model.UiApp(ThemedModel, ThemedMsg);
664
+
665
+ const themed_light_background = canvas.Color.rgb8(240, 244, 250);
666
+ const themed_dark_background = canvas.Color.rgb8(18, 22, 30);
667
+ const themed_chrome_background_id: canvas.ObjectId = 1;
668
+ const themed_chrome_footer_id: canvas.ObjectId = 2;
669
+
670
+ fn themedUpdate(model: *ThemedModel, msg: ThemedMsg) void {
671
+ switch (msg) {
672
+ .increment => model.count += 1,
673
+ .appearance => |appearance| {
674
+ model.dark = appearance.dark;
675
+ model.high_contrast = appearance.high_contrast;
676
+ },
677
+ .frame_seen => model.frame_reports += 1,
678
+ // The value itself arrives through the `sync` hook before this
679
+ // Msg is applied (the runtime-owned slider contract); update
680
+ // only counts the dispatch.
681
+ .slider_changed => model.slider_changes += 1,
682
+ }
683
+ }
684
+
685
+ fn themedView(ui: *ThemedApp.Ui, model: *const ThemedModel) ThemedApp.Ui.Node {
686
+ return ui.column(.{ .gap = 8, .padding = 12, .style_tokens = .{ .background = .background } }, .{
687
+ ui.text(.{}, ui.fmt("Count {d}", .{model.count})),
688
+ ui.button(.{ .variant = .primary, .on_press = .increment }, "Add"),
689
+ ui.el(.slider, .{ .value = model.slider_value, .on_change = .slider_changed, .semantics = .{ .label = "Level" } }, .{}),
690
+ });
691
+ }
692
+
693
+ fn themedTokens(model: *const ThemedModel) canvas.DesignTokens {
694
+ var tokens = canvas.DesignTokens{};
695
+ tokens.colors.background = if (model.dark) themed_dark_background else themed_light_background;
696
+ tokens.pixel_snap = .{ .geometry = true, .text = true };
697
+ return tokens;
698
+ }
699
+
700
+ fn themedChrome(model: *const ThemedModel, builder: *canvas.Builder, size: geometry.SizeF, tokens: canvas.DesignTokens) anyerror!void {
701
+ _ = model;
702
+ // One prefix command (backdrop) and one suffix command (footer rule).
703
+ try builder.fillRect(.{
704
+ .id = themed_chrome_background_id,
705
+ .rect = geometry.RectF.init(0, 0, size.width, size.height),
706
+ .fill = .{ .color = tokens.colors.background },
707
+ });
708
+ try builder.fillRect(.{
709
+ .id = themed_chrome_footer_id,
710
+ .rect = geometry.RectF.init(0, size.height - 1, size.width, 1),
711
+ .fill = .{ .color = tokens.colors.text },
712
+ });
713
+ }
714
+
715
+ fn themedAnimations(model: *const ThemedModel, tree: *const ThemedApp.Ui.Tree, start_ns: u64, out: []canvas.CanvasRenderAnimation) usize {
716
+ _ = model;
717
+ const button_id = findIn(tree.root, .button, "Add") orelse return 0;
718
+ if (out.len < 1) return 0;
719
+ out[0] = .{
720
+ .id = canvas.widgetCommandPartId(.{ .widget_id = button_id, .slot = 1 }),
721
+ .start_ns = start_ns,
722
+ .duration_ms = 400,
723
+ .from_opacity = 0.6,
724
+ .to_opacity = 1,
725
+ };
726
+ return 1;
727
+ }
728
+
729
+ fn themedAppearance(appearance: core.Appearance) ?ThemedMsg {
730
+ return ThemedMsg{ .appearance = .{
731
+ .dark = appearance.color_scheme == .dark,
732
+ .high_contrast = appearance.high_contrast,
733
+ } };
734
+ }
735
+
736
+ fn themedFrame(model: *const ThemedModel, frame: @import("../platform/root.zig").GpuFrame) ?ThemedMsg {
737
+ if (model.frame_reports > 0) return null;
738
+ if (frame.canvas_command_count == 0) return null;
739
+ return .frame_seen;
740
+ }
741
+
742
+ fn themedSync(model: *ThemedModel, layout: canvas.WidgetLayoutTree) void {
743
+ for (layout.nodes) |node| {
744
+ if (node.widget.kind == .slider) model.slider_value = node.widget.value;
745
+ }
746
+ }
747
+
748
+ fn themedOptions() ThemedApp.Options {
749
+ return .{
750
+ .name = "ui-app-themed",
751
+ .scene = counter_scene,
752
+ .canvas_label = canvas_label,
753
+ .update = themedUpdate,
754
+ .view = themedView,
755
+ .tokens_fn = themedTokens,
756
+ .chrome = .{ .prefix_commands = 1, .suffix_commands = 1, .build = themedChrome },
757
+ .animations = themedAnimations,
758
+ .on_appearance = themedAppearance,
759
+ .on_frame = themedFrame,
760
+ .sync = themedSync,
761
+ };
762
+ }
763
+
764
+ fn expectChromeFillRect(display_list: canvas.DisplayList, id: canvas.ObjectId, expected_rect: geometry.RectF, expected_color: canvas.Color) !void {
765
+ const command_ref = display_list.findCommandById(id) orelse return error.MissingChromeCommand;
766
+ switch (command_ref.command) {
767
+ .fill_rect => |fill| {
768
+ try std.testing.expectApproxEqAbs(expected_rect.width, fill.rect.width, 0.001);
769
+ try std.testing.expectApproxEqAbs(expected_rect.height, fill.rect.height, 0.001);
770
+ switch (fill.fill) {
771
+ .color => |actual| try std.testing.expectEqualDeep(expected_color, actual),
772
+ else => return error.UnexpectedChromeCommand,
773
+ }
774
+ },
775
+ else => return error.UnexpectedChromeCommand,
776
+ }
777
+ }
778
+
779
+ test "ui app hooks drive chrome, dynamic tokens, animations, and frame reports" {
780
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
781
+ defer harness.destroy(std.testing.allocator);
782
+ harness.null_platform.gpu_surfaces = true;
783
+
784
+ const app_state = try std.testing.allocator.create(ThemedApp);
785
+ defer std.testing.allocator.destroy(app_state);
786
+ app_state.* = ThemedApp.init(std.heap.page_allocator, .{}, themedOptions());
787
+ defer app_state.deinit();
788
+ const app = app_state.app();
789
+ try harness.start(app);
790
+
791
+ // Install: the chrome prefix and suffix wrap the widget commands, the
792
+ // model-derived tokens are stored (with the surface scale stamped into
793
+ // pixel snapping), and the animation hook is applied with the install
794
+ // frame timestamp.
795
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
796
+ .label = canvas_label,
797
+ .size = geometry.SizeF.init(400, 300),
798
+ .scale_factor = 2,
799
+ .frame_index = 1,
800
+ .timestamp_ns = 1_000_000_000,
801
+ .nonblank = true,
802
+ } });
803
+ try std.testing.expect(app_state.installed);
804
+
805
+ var display_list = try harness.runtime.canvasDisplayList(1, canvas_label);
806
+ try std.testing.expect(display_list.commandCount() > 2);
807
+ try expectChromeFillRect(display_list, themed_chrome_background_id, geometry.RectF.init(0, 0, 400, 300), themed_light_background);
808
+ try std.testing.expect(display_list.findCommandById(themed_chrome_footer_id) != null);
809
+ // The chrome prefix stays first and the suffix stays last around the
810
+ // regenerated widget commands.
811
+ try std.testing.expectEqual(themed_chrome_background_id, display_list.commands[0].fill_rect.id);
812
+ try std.testing.expectEqual(themed_chrome_footer_id, display_list.commands[display_list.commands.len - 1].fill_rect.id);
813
+
814
+ const stored_tokens = try harness.runtime.canvasWidgetDesignTokens(1, canvas_label);
815
+ try std.testing.expectEqualDeep(themed_light_background, stored_tokens.colors.background);
816
+ try std.testing.expectEqual(@as(f32, 2), stored_tokens.pixel_snap.scale);
817
+
818
+ // The root's style token ref resolved against the model-derived tokens.
819
+ try std.testing.expectEqualDeep(themed_light_background, app_state.tree.?.root.style.background.?);
820
+
821
+ const animations = try harness.runtime.canvasRenderAnimations(1, canvas_label);
822
+ try std.testing.expectEqual(@as(usize, 1), animations.len);
823
+ try std.testing.expectEqual(@as(u64, 1_000_000_000), animations[0].start_ns);
824
+ const button_id = findIn(app_state.tree.?.root, .button, "Add").?;
825
+ try std.testing.expectEqual(canvas.widgetCommandPartId(.{ .widget_id = button_id, .slot = 1 }), animations[0].id);
826
+
827
+ // A dispatch-driven rebuild keeps the chrome and updates the widgets.
828
+ var command_buffer: [96]u8 = undefined;
829
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, button_id });
830
+ try harness.runtime.dispatchAutomationCommand(app, click);
831
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
832
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
833
+ display_list = try harness.runtime.canvasDisplayList(1, canvas_label);
834
+ try expectChromeFillRect(display_list, themed_chrome_background_id, geometry.RectF.init(0, 0, 400, 300), themed_light_background);
835
+
836
+ // Runtime-owned slider state syncs back into the model before update.
837
+ const slider_id = blk: {
838
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
839
+ for (layout.nodes) |node| {
840
+ if (node.widget.kind == .slider) break :blk node.widget.id;
841
+ }
842
+ return error.TestUnexpectedResult;
843
+ };
844
+ const increment = try std.fmt.bufPrint(&command_buffer, "widget-action {s} {d} increment", .{ canvas_label, slider_id });
845
+ try harness.runtime.dispatchAutomationCommand(app, increment);
846
+ try std.testing.expect(app_state.model.slider_value > 0.5);
847
+
848
+ // Appearance changes map into messages; the model-owned scheme drives
849
+ // new tokens and a chrome rebuild.
850
+ try harness.runtime.dispatchPlatformEvent(app, .{ .appearance_changed = .{ .color_scheme = .dark, .high_contrast = true } });
851
+ try std.testing.expect(app_state.model.dark);
852
+ try std.testing.expect(app_state.model.high_contrast);
853
+ const dark_tokens = try harness.runtime.canvasWidgetDesignTokens(1, canvas_label);
854
+ try std.testing.expectEqualDeep(themed_dark_background, dark_tokens.colors.background);
855
+ // Style token refs re-resolve on the retheme rebuild: the same widget
856
+ // now carries the dark token's concrete color.
857
+ try std.testing.expectEqualDeep(themed_dark_background, app_state.tree.?.root.style.background.?);
858
+ display_list = try harness.runtime.canvasDisplayList(1, canvas_label);
859
+ try expectChromeFillRect(display_list, themed_chrome_background_id, geometry.RectF.init(0, 0, 400, 300), themed_dark_background);
860
+
861
+ // Resizes rebuild the chrome at the new surface size.
862
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_resized = .{
863
+ .window_id = 1,
864
+ .label = canvas_label,
865
+ .frame = geometry.RectF.init(0, 0, 640, 480),
866
+ .scale_factor = 2,
867
+ } });
868
+ display_list = try harness.runtime.canvasDisplayList(1, canvas_label);
869
+ try expectChromeFillRect(display_list, themed_chrome_background_id, geometry.RectF.init(0, 0, 640, 480), themed_dark_background);
870
+
871
+ // Non-installing frames report presented gpu frames through on_frame.
872
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.frame_reports);
873
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
874
+ .label = canvas_label,
875
+ .size = geometry.SizeF.init(640, 480),
876
+ .scale_factor = 2,
877
+ .frame_index = 2,
878
+ .timestamp_ns = 1_016_000_000,
879
+ .nonblank = true,
880
+ } });
881
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.frame_reports);
882
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
883
+ .label = canvas_label,
884
+ .size = geometry.SizeF.init(640, 480),
885
+ .scale_factor = 2,
886
+ .frame_index = 3,
887
+ .timestamp_ns = 1_032_000_000,
888
+ .nonblank = true,
889
+ } });
890
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.frame_reports);
891
+ }
892
+
893
+ test "slider pointer gestures dispatch on_change: rail click commits, drag scrubs" {
894
+ // Regression: the pointer path applied slider values as the visual
895
+ // echo but never dispatched the app's `on_change` — a rail click
896
+ // moved the thumb on screen while the model heard nothing, so a
897
+ // model-driven slider (a transport scrubber) snapped back on its
898
+ // next source rebuild. Pointer changes now drain into
899
+ // `canvas_widget_change` events; this pins the full pipeline:
900
+ // platform pointer input -> runtime echo -> change drain -> the
901
+ // slider's Msg -> `sync` reading the applied value into the model.
902
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
903
+ defer harness.destroy(std.testing.allocator);
904
+ harness.null_platform.gpu_surfaces = true;
905
+
906
+ const app_state = try std.testing.allocator.create(ThemedApp);
907
+ defer std.testing.allocator.destroy(app_state);
908
+ app_state.* = ThemedApp.init(std.heap.page_allocator, .{}, themedOptions());
909
+ defer app_state.deinit();
910
+ const app = app_state.app();
911
+ try harness.start(app);
912
+
913
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
914
+ .label = canvas_label,
915
+ .size = geometry.SizeF.init(400, 300),
916
+ .scale_factor = 1,
917
+ .frame_index = 1,
918
+ .timestamp_ns = 1_000_000_000,
919
+ .nonblank = true,
920
+ } });
921
+ try std.testing.expect(app_state.installed);
922
+
923
+ // The slider's laid-out rail, straight from the runtime's layout.
924
+ const rail = blk: {
925
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
926
+ for (layout.nodes) |node| {
927
+ if (node.widget.kind == .slider) break :blk node.frame.normalized();
928
+ }
929
+ return error.TestUnexpectedResult;
930
+ };
931
+ const rail_y = rail.y + rail.height / 2;
932
+
933
+ // Rail click: pressing at 3/4 along the rail (nowhere near the
934
+ // thumb, which sits at the initial 0.5) commits the proportional
935
+ // value in ONE dispatch — the standard native scrubber jump.
936
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
937
+ .window_id = 1,
938
+ .label = canvas_label,
939
+ .kind = .pointer_down,
940
+ .x = rail.x + rail.width * 0.75,
941
+ .y = rail_y,
942
+ } });
943
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.slider_changes);
944
+ try std.testing.expectApproxEqAbs(@as(f32, 0.75), app_state.model.slider_value, 0.01);
945
+
946
+ // Click-then-drag scrubs continuously: the same gesture keeps
947
+ // dispatching as the pointer moves, and the model follows live.
948
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
949
+ .window_id = 1,
950
+ .label = canvas_label,
951
+ .kind = .pointer_drag,
952
+ .x = rail.x + rail.width * 0.25,
953
+ .y = rail_y,
954
+ } });
955
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.slider_changes);
956
+ try std.testing.expectApproxEqAbs(@as(f32, 0.25), app_state.model.slider_value, 0.01);
957
+
958
+ // Releasing where the drag ended applies no new value: one gesture
959
+ // never double-commits its final position.
960
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
961
+ .window_id = 1,
962
+ .label = canvas_label,
963
+ .kind = .pointer_up,
964
+ .x = rail.x + rail.width * 0.25,
965
+ .y = rail_y,
966
+ } });
967
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.slider_changes);
968
+ try std.testing.expectApproxEqAbs(@as(f32, 0.25), app_state.model.slider_value, 0.01);
969
+
970
+ // Keyboard steps are UNCHANGED: they dispatch through the keyboard
971
+ // path exactly once — the pointer-change drain must not add a
972
+ // second delivery for the same step.
973
+ const slider_id = blk: {
974
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
975
+ for (layout.nodes) |node| {
976
+ if (node.widget.kind == .slider) break :blk node.widget.id;
977
+ }
978
+ return error.TestUnexpectedResult;
979
+ };
980
+ var command_buffer: [96]u8 = undefined;
981
+ const increment = try std.fmt.bufPrint(&command_buffer, "widget-action {s} {d} increment", .{ canvas_label, slider_id });
982
+ try harness.runtime.dispatchAutomationCommand(app, increment);
983
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.slider_changes);
984
+ try std.testing.expectApproxEqAbs(@as(f32, 0.30), app_state.model.slider_value, 0.01);
985
+ }
986
+
987
+ test "unthemed apps follow the system appearance live; explicit tokens opt out" {
988
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
989
+ defer harness.destroy(std.testing.allocator);
990
+ harness.null_platform.gpu_surfaces = true;
991
+
992
+ const app_state = try std.testing.allocator.create(CounterApp);
993
+ defer std.testing.allocator.destroy(app_state);
994
+ // The counter sets neither `tokens` nor `tokens_fn`: the stock theme
995
+ // follows the system appearance.
996
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, counterOptions());
997
+ defer app_state.deinit();
998
+ const app = app_state.app();
999
+ try harness.start(app);
1000
+
1001
+ // An appearance delivered BEFORE the install (the platform emits one
1002
+ // right after start) makes the very first build dark.
1003
+ try harness.runtime.dispatchPlatformEvent(app, .{ .appearance_changed = .{ .color_scheme = .dark } });
1004
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1005
+ .label = canvas_label,
1006
+ .size = geometry.SizeF.init(400, 300),
1007
+ .scale_factor = 2,
1008
+ .frame_index = 1,
1009
+ .timestamp_ns = 1_000_000,
1010
+ .nonblank = true,
1011
+ } });
1012
+ try std.testing.expect(app_state.installed);
1013
+ const dark = canvas.DesignTokens.theme(.{ .color_scheme = .dark });
1014
+ var stored = try harness.runtime.canvasWidgetDesignTokens(1, canvas_label);
1015
+ try std.testing.expectEqualDeep(dark.colors.background, stored.colors.background);
1016
+ try std.testing.expectEqual(@as(f32, 2), stored.pixel_snap.scale);
1017
+
1018
+ // Flipping the OS setting re-themes the RUNNING app: no restart, no
1019
+ // app wiring.
1020
+ try harness.runtime.dispatchPlatformEvent(app, .{ .appearance_changed = .{ .color_scheme = .light } });
1021
+ const light = canvas.DesignTokens.theme(.{ .color_scheme = .light });
1022
+ stored = try harness.runtime.canvasWidgetDesignTokens(1, canvas_label);
1023
+ try std.testing.expectEqualDeep(light.colors.background, stored.colors.background);
1024
+
1025
+ // Reduce-motion and high-contrast ride the same channel.
1026
+ try harness.runtime.dispatchPlatformEvent(app, .{ .appearance_changed = .{ .color_scheme = .dark, .high_contrast = true, .reduce_motion = true } });
1027
+ stored = try harness.runtime.canvasWidgetDesignTokens(1, canvas_label);
1028
+ const dark_hc = canvas.DesignTokens.theme(.{ .color_scheme = .dark, .contrast = .high, .reduce_motion = true });
1029
+ try std.testing.expectEqualDeep(dark_hc.colors.background, stored.colors.background);
1030
+ try std.testing.expectEqualDeep(dark_hc.colors.focus_ring, stored.colors.focus_ring);
1031
+ try std.testing.expectEqual(@as(u32, 0), stored.motion.normal_ms);
1032
+
1033
+ // Explicit static tokens OPT OUT: the app owns its look and an
1034
+ // appearance flip never restyles it.
1035
+ const fixed_state = try std.testing.allocator.create(CounterApp);
1036
+ defer std.testing.allocator.destroy(fixed_state);
1037
+ var fixed_options = counterOptions();
1038
+ fixed_options.name = "ui-app-counter-fixed";
1039
+ fixed_options.tokens = canvas.DesignTokens.theme(.{ .color_scheme = .light });
1040
+ fixed_state.* = CounterApp.init(std.heap.page_allocator, .{}, fixed_options);
1041
+ defer fixed_state.deinit();
1042
+ try std.testing.expectEqualDeep(light.colors.background, fixed_state.effectiveTokens().colors.background);
1043
+ fixed_state.system_appearance = .{ .color_scheme = .dark };
1044
+ try std.testing.expectEqualDeep(light.colors.background, fixed_state.effectiveTokens().colors.background);
1045
+ }
1046
+
1047
+ test "markup watch polls from the reserved runtime timer" {
1048
+ const io = std.testing.io;
1049
+ const watch_path = ".zig-cache/ui-app-markup-watch-test.native";
1050
+ const cwd = std.Io.Dir.cwd();
1051
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = counter_markup });
1052
+ defer cwd.deleteFile(io, watch_path) catch {};
1053
+
1054
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1055
+ defer harness.destroy(std.testing.allocator);
1056
+ harness.null_platform.gpu_surfaces = true;
1057
+
1058
+ var options = markupCounterOptions();
1059
+ options.markup = .{ .source = counter_markup, .watch_path = watch_path, .io = io };
1060
+ const app_state = try std.testing.allocator.create(CounterApp);
1061
+ defer std.testing.allocator.destroy(app_state);
1062
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
1063
+ defer app_state.deinit();
1064
+ const app = app_state.app();
1065
+ try harness.start(app);
1066
+
1067
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1068
+ .label = canvas_label,
1069
+ .size = geometry.SizeF.init(400, 300),
1070
+ .scale_factor = 2,
1071
+ .frame_index = 1,
1072
+ .timestamp_ns = 1_000_000,
1073
+ .nonblank = true,
1074
+ } });
1075
+ try std.testing.expect(app_state.installed);
1076
+
1077
+ // Install started the reserved repeating watch timer.
1078
+ const watch_timer = harness.null_platform.startedTimer(CounterApp.markup_watch_timer_id).?;
1079
+ try std.testing.expect(watch_timer.active);
1080
+ try std.testing.expect(watch_timer.repeats);
1081
+ try std.testing.expectEqual(@as(u64, 500_000_000), watch_timer.interval_ns);
1082
+
1083
+ // An idle poll (file unchanged) issues no frame-chain keepalive request.
1084
+ const frame_requests_after_install = harness.null_platform.gpu_surface_frame_request_count;
1085
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1086
+ try std.testing.expectEqual(frame_requests_after_install, harness.null_platform.gpu_surface_frame_request_count);
1087
+
1088
+ // Advance model state, then hot swap the file: the timer poll reloads
1089
+ // the markup, rebuilds, and keeps model state.
1090
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
1091
+ var command_buffer: [96]u8 = undefined;
1092
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
1093
+ try harness.runtime.dispatchAutomationCommand(app, click);
1094
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1095
+
1096
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = counter_markup_v2 });
1097
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1098
+
1099
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1100
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1101
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
1102
+ }
1103
+
1104
+ const watch_import_root_markup =
1105
+ \\<import src="ui-app-markup-watch-parts.native"/>
1106
+ \\<column gap="8" padding="12">
1107
+ \\ <text>Count {count}</text>
1108
+ \\ <use template="actions" />
1109
+ \\</column>
1110
+ ;
1111
+
1112
+ const watch_import_parts_markup =
1113
+ \\<template name="actions">
1114
+ \\ <column gap="4">
1115
+ \\ <button variant="primary" on-press="increment">Increment</button>
1116
+ \\ <button on-press="reset">Reset</button>
1117
+ \\ </column>
1118
+ \\</template>
1119
+ ;
1120
+
1121
+ const watch_import_parts_markup_v2 =
1122
+ \\<template name="actions">
1123
+ \\ <column gap="4">
1124
+ \\ <button variant="primary" on-press="increment">Increment</button>
1125
+ \\ <button on-press="reset">Start over</button>
1126
+ \\ </column>
1127
+ \\</template>
1128
+ ;
1129
+
1130
+ test "the markup watch reloads when an IMPORTED file changes on disk" {
1131
+ const io = std.testing.io;
1132
+ const watch_path = ".zig-cache/ui-app-markup-watch-import-test.native";
1133
+ const parts_path = ".zig-cache/ui-app-markup-watch-parts.native";
1134
+ const cwd = std.Io.Dir.cwd();
1135
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = watch_import_root_markup });
1136
+ defer cwd.deleteFile(io, watch_path) catch {};
1137
+ try cwd.writeFile(io, .{ .sub_path = parts_path, .data = watch_import_parts_markup });
1138
+ defer cwd.deleteFile(io, parts_path) catch {};
1139
+
1140
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1141
+ defer harness.destroy(std.testing.allocator);
1142
+ harness.null_platform.gpu_surfaces = true;
1143
+
1144
+ // The embedded source set mirrors the on-disk closure (paths relative
1145
+ // to the root file's directory), so the first build and the disk poll
1146
+ // agree until something actually changes.
1147
+ var options = markupCounterOptions();
1148
+ options.markup = .{
1149
+ .source = watch_import_root_markup,
1150
+ .sources = &.{
1151
+ .{ .path = "ui-app-markup-watch-parts.native", .source = watch_import_parts_markup },
1152
+ },
1153
+ .watch_path = watch_path,
1154
+ .io = io,
1155
+ };
1156
+ const app_state = try std.testing.allocator.create(CounterApp);
1157
+ defer std.testing.allocator.destroy(app_state);
1158
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
1159
+ defer app_state.deinit();
1160
+ const app = app_state.app();
1161
+ try harness.start(app);
1162
+
1163
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1164
+ .label = canvas_label,
1165
+ .size = geometry.SizeF.init(400, 300),
1166
+ .scale_factor = 2,
1167
+ .frame_index = 1,
1168
+ .timestamp_ns = 1_000_000,
1169
+ .nonblank = true,
1170
+ } });
1171
+ try std.testing.expect(app_state.installed);
1172
+ // The imported template built into the view.
1173
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
1174
+
1175
+ // An idle poll (closure unchanged) swaps nothing.
1176
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1177
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Reset") != null);
1178
+
1179
+ // Advance model state, then edit only the IMPORTED file: the poll
1180
+ // covers the whole closure, so the change reloads and rebuilds while
1181
+ // model state and ids hold.
1182
+ var command_buffer: [96]u8 = undefined;
1183
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
1184
+ try harness.runtime.dispatchAutomationCommand(app, click);
1185
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1186
+
1187
+ try cwd.writeFile(io, .{ .sub_path = parts_path, .data = watch_import_parts_markup_v2 });
1188
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1189
+
1190
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1191
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1192
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
1193
+
1194
+ // A broken edit to the imported file keeps the last good view and
1195
+ // records a diagnostic naming the imported file.
1196
+ try cwd.writeFile(io, .{ .sub_path = parts_path, .data = "<template name=\"actions\"><column><oops</column></template>" });
1197
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_500_000).?);
1198
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1199
+ try std.testing.expect(app_state.markup_diagnostic != null);
1200
+ try std.testing.expect(std.mem.indexOf(u8, app_state.markup_diagnostic.?.path, "ui-app-markup-watch-parts.native") != null);
1201
+ }
1202
+
1203
+ const watch_import_sources = [_]canvas.ui_markup.SourceFile{
1204
+ .{ .path = "ui-app-markup-watch-import-baseline.native", .source = watch_import_root_markup },
1205
+ .{ .path = "ui-app-markup-watch-parts.native", .source = watch_import_parts_markup },
1206
+ };
1207
+
1208
+ const CompiledImportCounterView = canvas.CompiledMarkupImports(
1209
+ CounterModel,
1210
+ CounterMsg,
1211
+ "ui-app-markup-watch-import-baseline.native",
1212
+ &watch_import_sources,
1213
+ );
1214
+
1215
+ test "with imports the compiled view stays the baseline until the watched closure changes" {
1216
+ const io = std.testing.io;
1217
+ const watch_path = ".zig-cache/ui-app-markup-watch-import-baseline.native";
1218
+ const parts_path = ".zig-cache/ui-app-markup-watch-parts.native";
1219
+ const cwd = std.Io.Dir.cwd();
1220
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = watch_import_root_markup });
1221
+ defer cwd.deleteFile(io, watch_path) catch {};
1222
+ try cwd.writeFile(io, .{ .sub_path = parts_path, .data = watch_import_parts_markup });
1223
+ defer cwd.deleteFile(io, parts_path) catch {};
1224
+
1225
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1226
+ defer harness.destroy(std.testing.allocator);
1227
+ harness.null_platform.gpu_surfaces = true;
1228
+
1229
+ var options = markupCounterOptions();
1230
+ options.view = CompiledImportCounterView.build;
1231
+ options.markup = .{
1232
+ .source = watch_import_root_markup,
1233
+ .sources = &watch_import_sources,
1234
+ .watch_path = watch_path,
1235
+ .io = io,
1236
+ };
1237
+ const app_state = try std.testing.allocator.create(CounterApp);
1238
+ defer std.testing.allocator.destroy(app_state);
1239
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
1240
+ defer app_state.deinit();
1241
+ const app = app_state.app();
1242
+ try harness.start(app);
1243
+
1244
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1245
+ .label = canvas_label,
1246
+ .size = geometry.SizeF.init(400, 300),
1247
+ .scale_factor = 2,
1248
+ .frame_index = 1,
1249
+ .timestamp_ns = 1_000_000,
1250
+ .nonblank = true,
1251
+ } });
1252
+ try std.testing.expect(app_state.installed);
1253
+ try std.testing.expect(app_state.markup_view == null);
1254
+
1255
+ // The disk closure matches the embedded one (the baseline hash covers
1256
+ // imports in the same root-relative path space), so an idle poll never
1257
+ // phantom-swaps to the interpreter.
1258
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1259
+ try std.testing.expect(app_state.markup_view == null);
1260
+
1261
+ // An edit to the IMPORTED file flips the baseline to the interpreter.
1262
+ try cwd.writeFile(io, .{ .sub_path = parts_path, .data = watch_import_parts_markup_v2 });
1263
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1264
+ try std.testing.expect(app_state.markup_view != null);
1265
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1266
+ }
1267
+
1268
+ const CompiledCounterView = canvas.CompiledMarkupView(CounterModel, CounterMsg, counter_markup);
1269
+
1270
+ test "a compiled markup view drives the ui app with the runtime markup engine compiled out" {
1271
+ const LeanApp = ui_app_model.UiAppWithFeatures(CounterModel, CounterMsg, .{ .runtime_markup = false });
1272
+
1273
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1274
+ defer harness.destroy(std.testing.allocator);
1275
+ harness.null_platform.gpu_surfaces = true;
1276
+
1277
+ const app_state = try std.testing.allocator.create(LeanApp);
1278
+ defer std.testing.allocator.destroy(app_state);
1279
+ app_state.* = LeanApp.init(std.heap.page_allocator, .{}, .{
1280
+ .name = "ui-app-compiled-counter",
1281
+ .scene = counter_scene,
1282
+ .canvas_label = canvas_label,
1283
+ .update = counterUpdate,
1284
+ .view = CompiledCounterView.build,
1285
+ .on_command = counterCommand,
1286
+ });
1287
+ defer app_state.deinit();
1288
+ const app = app_state.app();
1289
+ try harness.start(app);
1290
+
1291
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1292
+ .label = canvas_label,
1293
+ .size = geometry.SizeF.init(400, 300),
1294
+ .scale_factor = 2,
1295
+ .frame_index = 1,
1296
+ .timestamp_ns = 1_000_000,
1297
+ .nonblank = true,
1298
+ } });
1299
+ try std.testing.expect(app_state.installed);
1300
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
1301
+
1302
+ // Compiled-markup handlers dispatch through the same typed loop.
1303
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
1304
+ var command_buffer: [96]u8 = undefined;
1305
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
1306
+ try harness.runtime.dispatchAutomationCommand(app, click);
1307
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1308
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
1309
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
1310
+
1311
+ // The runtime engine is compiled out: no watch timer, no reload path.
1312
+ try std.testing.expect(harness.null_platform.startedTimer(LeanApp.markup_watch_timer_id) == null);
1313
+ try std.testing.expectError(error.MarkupEngineDisabled, app_state.reloadMarkup(counter_markup_v2));
1314
+ }
1315
+
1316
+ test "with view and markup both set the compiled view renders until the watched file changes" {
1317
+ const io = std.testing.io;
1318
+ const watch_path = ".zig-cache/ui-app-compiled-watch-test.native";
1319
+ const cwd = std.Io.Dir.cwd();
1320
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = counter_markup });
1321
+ defer cwd.deleteFile(io, watch_path) catch {};
1322
+
1323
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1324
+ defer harness.destroy(std.testing.allocator);
1325
+ harness.null_platform.gpu_surfaces = true;
1326
+
1327
+ var options = markupCounterOptions();
1328
+ options.view = CompiledCounterView.build;
1329
+ options.markup = .{ .source = counter_markup, .watch_path = watch_path, .io = io };
1330
+ const app_state = try std.testing.allocator.create(CounterApp);
1331
+ defer std.testing.allocator.destroy(app_state);
1332
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
1333
+ defer app_state.deinit();
1334
+ const app = app_state.app();
1335
+ try harness.start(app);
1336
+
1337
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1338
+ .label = canvas_label,
1339
+ .size = geometry.SizeF.init(400, 300),
1340
+ .scale_factor = 2,
1341
+ .frame_index = 1,
1342
+ .timestamp_ns = 1_000_000,
1343
+ .nonblank = true,
1344
+ } });
1345
+ try std.testing.expect(app_state.installed);
1346
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 0"));
1347
+
1348
+ // The compiled view rendered: the interpreter never parsed anything.
1349
+ try std.testing.expect(app_state.markup_view == null);
1350
+
1351
+ // An idle poll (file matches the embedded source) keeps it that way.
1352
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1353
+ try std.testing.expect(app_state.markup_view == null);
1354
+
1355
+ // Advance model state, then edit the file: the interpreter takes over
1356
+ // with the new source, keeping model state and structural ids.
1357
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
1358
+ var command_buffer: [96]u8 = undefined;
1359
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
1360
+ try harness.runtime.dispatchAutomationCommand(app, click);
1361
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1362
+
1363
+ try cwd.writeFile(io, .{ .sub_path = watch_path, .data = counter_markup_v2 });
1364
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1365
+
1366
+ try std.testing.expect(app_state.markup_view != null);
1367
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1368
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1369
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
1370
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
1371
+ }
1372
+
1373
+ // ------------------------------------------------- fragment hot reload
1374
+ // A HYBRID root: a Zig builder view embedding compiled markup fragments.
1375
+ // The fragment watch (Options.fragment_watch) is what keeps the edit-see
1376
+ // loop alive for these apps — without it, editing a fragment's .native
1377
+ // source in dev does nothing because the fragment was compiled at
1378
+ // comptime.
1379
+
1380
+ const fragment_actions_markup =
1381
+ \\<column gap="4">
1382
+ \\ <button variant="primary" on-press="increment">Increment</button>
1383
+ \\ <button on-press="reset">Reset</button>
1384
+ \\</column>
1385
+ ;
1386
+
1387
+ const fragment_actions_markup_v2 =
1388
+ \\<column gap="4">
1389
+ \\ <button variant="primary" on-press="increment">Increment</button>
1390
+ \\ <button on-press="reset">Start over</button>
1391
+ \\</column>
1392
+ ;
1393
+
1394
+ const fragment_actions_path = ".zig-cache/ui-app-fragment-actions.native";
1395
+
1396
+ const FragmentActionsView = canvas.CompiledMarkupView(CounterModel, CounterMsg, fragment_actions_markup);
1397
+
1398
+ fn hybridCounterView(ui: *CounterApp.Ui, model: *const CounterModel) CounterApp.Ui.Node {
1399
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
1400
+ ui.text(.{}, ui.fmt("Count {d}", .{model.count})),
1401
+ FragmentActionsView.build(ui, model),
1402
+ });
1403
+ }
1404
+
1405
+ const hybrid_counter_fragments = [_]canvas.MarkupFragment{
1406
+ FragmentActionsView.fragment(fragment_actions_path),
1407
+ };
1408
+
1409
+ fn hybridCounterOptions(io: std.Io) CounterApp.Options {
1410
+ var options = counterOptions();
1411
+ options.name = "ui-app-hybrid-counter";
1412
+ options.view = hybridCounterView;
1413
+ options.fragment_watch = .{ .fragments = &hybrid_counter_fragments, .io = io };
1414
+ return options;
1415
+ }
1416
+
1417
+ /// Install the app on the harness and drive the first gpu frame (the
1418
+ /// installing frame, which also arms the markup watch).
1419
+ fn installCounterApp(harness: anytype, app: core.App) !void {
1420
+ try harness.start(app);
1421
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1422
+ .label = canvas_label,
1423
+ .size = geometry.SizeF.init(400, 300),
1424
+ .scale_factor = 2,
1425
+ .frame_index = 1,
1426
+ .timestamp_ns = 1_000_000,
1427
+ .nonblank = true,
1428
+ } });
1429
+ }
1430
+
1431
+ test "the fragment watch reloads a compiled fragment embedded in a Zig view" {
1432
+ const io = std.testing.io;
1433
+ const cwd = std.Io.Dir.cwd();
1434
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = fragment_actions_markup });
1435
+ defer cwd.deleteFile(io, fragment_actions_path) catch {};
1436
+
1437
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1438
+ defer harness.destroy(std.testing.allocator);
1439
+ harness.null_platform.gpu_surfaces = true;
1440
+
1441
+ const app_state = try std.testing.allocator.create(CounterApp);
1442
+ defer std.testing.allocator.destroy(app_state);
1443
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, hybridCounterOptions(io));
1444
+ defer app_state.deinit();
1445
+ const app = app_state.app();
1446
+ try installCounterApp(harness, app);
1447
+ try std.testing.expect(app_state.installed);
1448
+
1449
+ // Registered fragments arm the watch — the same reserved repeating
1450
+ // timer as the single-root watch — and the armed state is honest in
1451
+ // the automation snapshot bit even though the app has no markup root.
1452
+ try std.testing.expect(harness.null_platform.startedTimer(CounterApp.markup_watch_timer_id) != null);
1453
+ try std.testing.expect(harness.runtime.markup_watch_armed);
1454
+
1455
+ // An idle poll (file matches the embedded baseline) keeps the
1456
+ // comptime-compiled path: no override document is adopted.
1457
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1458
+ try std.testing.expect(app_state.markup_fragment_slots[0].document == null);
1459
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Reset") != null);
1460
+
1461
+ // Advance model state, then edit the fragment's file: the poll
1462
+ // reloads THAT fragment through the interpreter and rebuilds while
1463
+ // model state and structural ids hold.
1464
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
1465
+ var command_buffer: [96]u8 = undefined;
1466
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
1467
+ try harness.runtime.dispatchAutomationCommand(app, click);
1468
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1469
+
1470
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = fragment_actions_markup_v2 });
1471
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1472
+ try std.testing.expect(app_state.markup_fragment_slots[0].document != null);
1473
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1474
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
1475
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "Count 1"));
1476
+ try std.testing.expectEqual(increment_id, findWidgetIdByText(app_state.tree.?, .button, "Increment").?);
1477
+
1478
+ // Reverting the file byte for byte drops the override: back to the
1479
+ // comptime-compiled path, the release-identical one.
1480
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = fragment_actions_markup });
1481
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_500_000).?);
1482
+ try std.testing.expect(app_state.markup_fragment_slots[0].document == null);
1483
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Reset") != null);
1484
+ }
1485
+
1486
+ test "a broken fragment save keeps the last good view and the next good save recovers" {
1487
+ const io = std.testing.io;
1488
+ const cwd = std.Io.Dir.cwd();
1489
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = fragment_actions_markup });
1490
+ defer cwd.deleteFile(io, fragment_actions_path) catch {};
1491
+
1492
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1493
+ defer harness.destroy(std.testing.allocator);
1494
+ harness.null_platform.gpu_surfaces = true;
1495
+
1496
+ const app_state = try std.testing.allocator.create(CounterApp);
1497
+ defer std.testing.allocator.destroy(app_state);
1498
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, hybridCounterOptions(io));
1499
+ defer app_state.deinit();
1500
+ const app = app_state.app();
1501
+ try installCounterApp(harness, app);
1502
+ try std.testing.expect(app_state.installed);
1503
+
1504
+ // A save that does not parse: the fragment keeps its last good view,
1505
+ // the app keeps running, and the teaching diagnostic names the file.
1506
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = "<column><oops</column>" });
1507
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1508
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Reset") != null);
1509
+ try std.testing.expect(app_state.markup_diagnostic != null);
1510
+ try std.testing.expect(std.mem.indexOf(u8, app_state.markup_diagnostic.?.path, "ui-app-fragment-actions.native") != null);
1511
+
1512
+ // A save that parses but cannot build against the Model (a binding
1513
+ // naming no model field — what the compiled engine rejects at
1514
+ // comptime): the frame aborts, the last good tree stays up, and the
1515
+ // diagnostic reports through the same channel.
1516
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = "<column><text>{missing_field}</text></column>" });
1517
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1518
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Reset") != null);
1519
+ try std.testing.expect(app_state.markup_diagnostic != null);
1520
+
1521
+ // The next good save recovers in place.
1522
+ try cwd.writeFile(io, .{ .sub_path = fragment_actions_path, .data = fragment_actions_markup_v2 });
1523
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_500_000).?);
1524
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .button, "Start over") != null);
1525
+ try std.testing.expect(app_state.markup_diagnostic == null);
1526
+ }
1527
+
1528
+ // Two fragments importing ONE shared component file: the import-closure
1529
+ // propagation rule is that editing the shared file reloads every fragment
1530
+ // whose closure reaches it, in the same poll.
1531
+
1532
+ const fragment_badge_a_markup =
1533
+ \\<import src="ui-app-fragment-parts.native"/>
1534
+ \\<row gap="4">
1535
+ \\ <text>Badge A</text>
1536
+ \\ <use template="chip" />
1537
+ \\</row>
1538
+ ;
1539
+
1540
+ const fragment_badge_b_markup =
1541
+ \\<import src="ui-app-fragment-parts.native"/>
1542
+ \\<row gap="4">
1543
+ \\ <text>Badge B</text>
1544
+ \\ <use template="chip" />
1545
+ \\</row>
1546
+ ;
1547
+
1548
+ const fragment_parts_markup =
1549
+ \\<template name="chip">
1550
+ \\ <text>Alpha</text>
1551
+ \\</template>
1552
+ ;
1553
+
1554
+ const fragment_parts_markup_v2 =
1555
+ \\<template name="chip">
1556
+ \\ <text>Beta</text>
1557
+ \\</template>
1558
+ ;
1559
+
1560
+ const fragment_badge_a_path = ".zig-cache/ui-app-fragment-badge-a.native";
1561
+ const fragment_badge_b_path = ".zig-cache/ui-app-fragment-badge-b.native";
1562
+ const fragment_parts_path = ".zig-cache/ui-app-fragment-parts.native";
1563
+
1564
+ const fragment_badge_a_sources = [_]canvas.ui_markup.SourceFile{
1565
+ .{ .path = "ui-app-fragment-badge-a.native", .source = fragment_badge_a_markup },
1566
+ .{ .path = "ui-app-fragment-parts.native", .source = fragment_parts_markup },
1567
+ };
1568
+ const fragment_badge_b_sources = [_]canvas.ui_markup.SourceFile{
1569
+ .{ .path = "ui-app-fragment-badge-b.native", .source = fragment_badge_b_markup },
1570
+ .{ .path = "ui-app-fragment-parts.native", .source = fragment_parts_markup },
1571
+ };
1572
+
1573
+ const FragmentBadgeAView = canvas.CompiledMarkupImports(CounterModel, CounterMsg, "ui-app-fragment-badge-a.native", &fragment_badge_a_sources);
1574
+ const FragmentBadgeBView = canvas.CompiledMarkupImports(CounterModel, CounterMsg, "ui-app-fragment-badge-b.native", &fragment_badge_b_sources);
1575
+
1576
+ fn badgesCounterView(ui: *CounterApp.Ui, model: *const CounterModel) CounterApp.Ui.Node {
1577
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
1578
+ FragmentBadgeAView.build(ui, model),
1579
+ FragmentBadgeBView.build(ui, model),
1580
+ });
1581
+ }
1582
+
1583
+ const badges_counter_fragments = [_]canvas.MarkupFragment{
1584
+ FragmentBadgeAView.fragment(fragment_badge_a_path),
1585
+ FragmentBadgeBView.fragment(fragment_badge_b_path),
1586
+ };
1587
+
1588
+ fn countTextIn(widget: canvas.Widget, text: []const u8) usize {
1589
+ var count: usize = 0;
1590
+ if (widget.kind == .text and std.mem.eql(u8, widget.text, text)) count += 1;
1591
+ for (widget.children) |child| count += countTextIn(child, text);
1592
+ return count;
1593
+ }
1594
+
1595
+ test "editing a shared imported file reloads every fragment whose imports reach it" {
1596
+ const io = std.testing.io;
1597
+ const cwd = std.Io.Dir.cwd();
1598
+ try cwd.writeFile(io, .{ .sub_path = fragment_badge_a_path, .data = fragment_badge_a_markup });
1599
+ defer cwd.deleteFile(io, fragment_badge_a_path) catch {};
1600
+ try cwd.writeFile(io, .{ .sub_path = fragment_badge_b_path, .data = fragment_badge_b_markup });
1601
+ defer cwd.deleteFile(io, fragment_badge_b_path) catch {};
1602
+ try cwd.writeFile(io, .{ .sub_path = fragment_parts_path, .data = fragment_parts_markup });
1603
+ defer cwd.deleteFile(io, fragment_parts_path) catch {};
1604
+
1605
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1606
+ defer harness.destroy(std.testing.allocator);
1607
+ harness.null_platform.gpu_surfaces = true;
1608
+
1609
+ var options = counterOptions();
1610
+ options.name = "ui-app-badges-counter";
1611
+ options.view = badgesCounterView;
1612
+ options.fragment_watch = .{ .fragments = &badges_counter_fragments, .io = io };
1613
+ const app_state = try std.testing.allocator.create(CounterApp);
1614
+ defer std.testing.allocator.destroy(app_state);
1615
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, options);
1616
+ defer app_state.deinit();
1617
+ const app = app_state.app();
1618
+ try installCounterApp(harness, app);
1619
+ try std.testing.expect(app_state.installed);
1620
+
1621
+ // Both compiled fragments rendered the shared template.
1622
+ try std.testing.expectEqual(@as(usize, 2), countTextIn(app_state.tree.?.root, "Alpha"));
1623
+
1624
+ // An idle poll leaves both fragments compiled: the embedded baseline
1625
+ // hash covers the whole import closure, so nothing phantom-reloads.
1626
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 1_500_000).?);
1627
+ try std.testing.expect(app_state.markup_fragment_slots[0].document == null);
1628
+ try std.testing.expect(app_state.markup_fragment_slots[1].document == null);
1629
+
1630
+ // Editing only the SHARED imported file reloads BOTH fragments in
1631
+ // one poll — a file may serve several fragments, and every one of
1632
+ // its dependents rebuilds fresh.
1633
+ try cwd.writeFile(io, .{ .sub_path = fragment_parts_path, .data = fragment_parts_markup_v2 });
1634
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_000_000).?);
1635
+ try std.testing.expectEqual(@as(usize, 2), countTextIn(app_state.tree.?.root, "Beta"));
1636
+ try std.testing.expectEqual(@as(usize, 0), countTextIn(app_state.tree.?.root, "Alpha"));
1637
+
1638
+ // Editing one fragment's ROOT file reloads only that fragment; the
1639
+ // other keeps its current view.
1640
+ const badge_a_v2 = try std.mem.concat(std.testing.allocator, u8, &.{ fragment_badge_a_markup, "\n" });
1641
+ defer std.testing.allocator.free(badge_a_v2);
1642
+ try cwd.writeFile(io, .{ .sub_path = fragment_badge_a_path, .data = badge_a_v2 });
1643
+ try harness.runtime.dispatchPlatformEvent(app, harness.null_platform.fireTimer(CounterApp.markup_watch_timer_id, 2_500_000).?);
1644
+ try std.testing.expect(app_state.markup_fragment_slots[0].document != null);
1645
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .text, "Badge A") != null);
1646
+ try std.testing.expect(findWidgetIdByText(app_state.tree.?, .text, "Badge B") != null);
1647
+ }
1648
+
1649
+ test "a hybrid app with no registered fragments keeps the markup watch off" {
1650
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1651
+ defer harness.destroy(std.testing.allocator);
1652
+ harness.null_platform.gpu_surfaces = true;
1653
+
1654
+ const app_state = try std.testing.allocator.create(CounterApp);
1655
+ defer std.testing.allocator.destroy(app_state);
1656
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, counterOptions());
1657
+ defer app_state.deinit();
1658
+ const app = app_state.app();
1659
+ try installCounterApp(harness, app);
1660
+ try std.testing.expect(app_state.installed);
1661
+
1662
+ // No markup root, no fragments: the watch never arms and the
1663
+ // automation snapshot bit honestly reports off.
1664
+ try std.testing.expect(harness.null_platform.startedTimer(CounterApp.markup_watch_timer_id) == null);
1665
+ try std.testing.expect(!harness.runtime.markup_watch_armed);
1666
+ }
1667
+
1668
+ const RosterModel = struct {
1669
+ row_count: usize = 70,
1670
+
1671
+ pub fn rows(model: *const RosterModel, arena: std.mem.Allocator) []const usize {
1672
+ const out = arena.alloc(usize, model.row_count) catch return &.{};
1673
+ for (out, 0..) |*slot, index| slot.* = index;
1674
+ return out[0..model.row_count];
1675
+ }
1676
+ };
1677
+
1678
+ const RosterMsg = union(enum) { noop };
1679
+ const RosterApp = ui_app_model.UiApp(RosterModel, RosterMsg);
1680
+
1681
+ fn rosterUpdate(model: *RosterModel, msg: RosterMsg) void {
1682
+ _ = model;
1683
+ _ = msg;
1684
+ }
1685
+
1686
+ fn rosterKey(index: *const usize) canvas.UiKey {
1687
+ return canvas.uiKey(@as(u64, index.*));
1688
+ }
1689
+
1690
+ fn rosterRow(ui: *RosterApp.Ui, index: *const usize) RosterApp.Ui.Node {
1691
+ return ui.row(.{ .gap = 4 }, .{
1692
+ ui.checkbox(.{ .on_toggle = .noop }),
1693
+ ui.text(.{ .grow = 1 }, ui.fmt("Row {d}", .{index.*})),
1694
+ });
1695
+ }
1696
+
1697
+ fn rosterView(ui: *RosterApp.Ui, model: *const RosterModel) RosterApp.Ui.Node {
1698
+ return ui.column(.{ .gap = 2 }, ui.each(model.rows(ui.arena), rosterKey, rosterRow));
1699
+ }
1700
+
1701
+ test "widget trees beyond the old 64-node cap install and reconcile" {
1702
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 2000) });
1703
+ defer harness.destroy(std.testing.allocator);
1704
+ harness.null_platform.gpu_surfaces = true;
1705
+
1706
+ const app_state = try std.testing.allocator.create(RosterApp);
1707
+ defer std.testing.allocator.destroy(app_state);
1708
+ app_state.* = RosterApp.init(std.heap.page_allocator, .{}, .{
1709
+ .name = "ui-app-roster",
1710
+ .scene = counter_scene,
1711
+ .canvas_label = canvas_label,
1712
+ .update = rosterUpdate,
1713
+ .view = rosterView,
1714
+ });
1715
+ defer app_state.deinit();
1716
+ const app = app_state.app();
1717
+ try harness.start(app);
1718
+
1719
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1720
+ .label = canvas_label,
1721
+ .size = geometry.SizeF.init(400, 2000),
1722
+ .scale_factor = 1,
1723
+ .frame_index = 1,
1724
+ .timestamp_ns = 1_000_000,
1725
+ .nonblank = true,
1726
+ } });
1727
+ try std.testing.expect(app_state.installed);
1728
+
1729
+ // 70 keyed rows x (row + checkbox + text) + root column = 211 nodes.
1730
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
1731
+ try std.testing.expect(layout.nodes.len > 64);
1732
+ try std.testing.expectEqual(@as(usize, 211), layout.nodes.len);
1733
+
1734
+ // A rebuild through the reconcile path holds at that size.
1735
+ try app_state.rebuild(&harness.runtime, 1);
1736
+ try std.testing.expectEqual(@as(usize, 211), (try harness.runtime.canvasWidgetLayout(1, canvas_label)).nodes.len);
1737
+ }
1738
+
1739
+ // ---------------------------------------------------------------- set_text
1740
+
1741
+ const mirror_canvas_label = "mirror-canvas";
1742
+
1743
+ const MirrorModel = struct {
1744
+ draft: canvas.TextBuffer(64) = .{},
1745
+ edit_count: u32 = 0,
1746
+ submit_count: u32 = 0,
1747
+ };
1748
+
1749
+ const MirrorMsg = union(enum) {
1750
+ draft_edit: canvas.TextInputEvent,
1751
+ submit,
1752
+ };
1753
+
1754
+ const MirrorApp = ui_app_model.UiApp(MirrorModel, MirrorMsg);
1755
+
1756
+ fn mirrorUpdate(model: *MirrorModel, msg: MirrorMsg) void {
1757
+ switch (msg) {
1758
+ .draft_edit => |edit| {
1759
+ model.draft.apply(edit);
1760
+ model.edit_count += 1;
1761
+ },
1762
+ .submit => model.submit_count += 1,
1763
+ }
1764
+ }
1765
+
1766
+ fn mirrorView(ui: *MirrorApp.Ui, model: *const MirrorModel) MirrorApp.Ui.Node {
1767
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
1768
+ ui.textField(.{
1769
+ .text = model.draft.text(),
1770
+ .placeholder = "Message",
1771
+ .on_input = MirrorApp.Ui.inputMsg(.draft_edit),
1772
+ .on_submit = .submit,
1773
+ }),
1774
+ ui.text(.{}, if (model.draft.isEmpty()) "Send disabled" else "Send enabled"),
1775
+ });
1776
+ }
1777
+
1778
+ const mirror_views = [_]app_manifest.ShellView{
1779
+ .{ .label = mirror_canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
1780
+ };
1781
+ const mirror_windows = [_]app_manifest.ShellWindow{.{
1782
+ .label = "main",
1783
+ .title = "Mirror",
1784
+ .width = 400,
1785
+ .height = 300,
1786
+ .views = &mirror_views,
1787
+ }};
1788
+ const mirror_scene: app_manifest.ShellConfig = .{ .windows = &mirror_windows };
1789
+
1790
+ fn findWidgetIdByKind(widget: canvas.Widget, kind: canvas.WidgetKind) ?canvas.ObjectId {
1791
+ if (widget.kind == kind) return widget.id;
1792
+ for (widget.children) |child| {
1793
+ if (findWidgetIdByKind(child, kind)) |id| return id;
1794
+ }
1795
+ return null;
1796
+ }
1797
+
1798
+ test "automation set_text routes through the input path so the elm mirror stays consistent" {
1799
+ // `widget-action <id> set_text` used to write the
1800
+ // runtime editor state directly and never dispatch `on_input`, so a
1801
+ // TEA app's model still saw an empty buffer (Send stayed disabled
1802
+ // while the field visibly held text — a state no real user can
1803
+ // produce).
1804
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1805
+ defer harness.destroy(std.testing.allocator);
1806
+ harness.null_platform.gpu_surfaces = true;
1807
+
1808
+ const app_state = try std.testing.allocator.create(MirrorApp);
1809
+ defer std.testing.allocator.destroy(app_state);
1810
+ app_state.* = MirrorApp.init(std.heap.page_allocator, .{}, .{
1811
+ .name = "ui-app-mirror",
1812
+ .scene = mirror_scene,
1813
+ .canvas_label = mirror_canvas_label,
1814
+ .update = mirrorUpdate,
1815
+ .view = mirrorView,
1816
+ });
1817
+ defer app_state.deinit();
1818
+ const app = app_state.app();
1819
+ try harness.start(app);
1820
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1821
+ .label = mirror_canvas_label,
1822
+ .size = geometry.SizeF.init(400, 300),
1823
+ .scale_factor = 1,
1824
+ .frame_index = 1,
1825
+ .timestamp_ns = 1_000_000,
1826
+ .nonblank = true,
1827
+ } });
1828
+ try std.testing.expect(app_state.installed);
1829
+
1830
+ const field_id = findWidgetIdByKind(app_state.tree.?.root, .text_field).?;
1831
+
1832
+ // set_text lands in the runtime editor AND the model mirror.
1833
+ try core.testing.dispatchAutomationWidgetAction(&harness.runtime, app, .{
1834
+ .view_label = mirror_canvas_label,
1835
+ .id = field_id,
1836
+ .action = .set_text,
1837
+ .value = "ship the fix",
1838
+ });
1839
+ try std.testing.expectEqualStrings("ship the fix", app_state.model.draft.text());
1840
+ try std.testing.expect(app_state.model.edit_count > 0);
1841
+ const layout = try harness.runtime.canvasWidgetLayout(1, mirror_canvas_label);
1842
+ try std.testing.expectEqualStrings("ship the fix", layout.findById(field_id).?.widget.text);
1843
+
1844
+ // The dependent view state follows the model, not just the editor.
1845
+ var found_enabled = false;
1846
+ for (layout.nodes) |node| {
1847
+ if (node.widget.kind == .text and std.mem.eql(u8, node.widget.text, "Send enabled")) found_enabled = true;
1848
+ }
1849
+ try std.testing.expect(found_enabled);
1850
+
1851
+ // Replacing existing text keeps model and editor in lockstep.
1852
+ try core.testing.dispatchAutomationWidgetAction(&harness.runtime, app, .{
1853
+ .view_label = mirror_canvas_label,
1854
+ .id = field_id,
1855
+ .action = .set_text,
1856
+ .value = "second draft",
1857
+ });
1858
+ try std.testing.expectEqualStrings("second draft", app_state.model.draft.text());
1859
+ const replaced_layout = try harness.runtime.canvasWidgetLayout(1, mirror_canvas_label);
1860
+ try std.testing.expectEqualStrings("second draft", replaced_layout.findById(field_id).?.widget.text);
1861
+
1862
+ // Clearing through set_text "" also flows through the input path.
1863
+ try core.testing.dispatchAutomationWidgetAction(&harness.runtime, app, .{
1864
+ .view_label = mirror_canvas_label,
1865
+ .id = field_id,
1866
+ .action = .set_text,
1867
+ .value = "",
1868
+ });
1869
+ try std.testing.expectEqualStrings("", app_state.model.draft.text());
1870
+ const cleared_layout = try harness.runtime.canvasWidgetLayout(1, mirror_canvas_label);
1871
+ try std.testing.expectEqualStrings("", cleared_layout.findById(field_id).?.widget.text);
1872
+
1873
+ // The automation snapshot agrees with both.
1874
+ const snapshot = harness.runtime.automationSnapshot("Mirror");
1875
+ for (snapshot.widgets) |widget| {
1876
+ if (widget.id == field_id) try std.testing.expectEqualStrings("", widget.text_value);
1877
+ }
1878
+ }
1879
+
1880
+ // ------------------------------------------------- autofocus (notes flow)
1881
+
1882
+ const autofocus_canvas_label = "autofocus-canvas"; // shell scene label below
1883
+
1884
+ const AutofocusModel = struct {
1885
+ editing: bool = false,
1886
+ draft: canvas.TextBuffer(64) = .{},
1887
+ edit_count: u32 = 0,
1888
+ };
1889
+
1890
+ const AutofocusMsg = union(enum) {
1891
+ begin_edit,
1892
+ draft_edit: canvas.TextInputEvent,
1893
+ };
1894
+
1895
+ const AutofocusApp = ui_app_model.UiApp(AutofocusModel, AutofocusMsg);
1896
+
1897
+ fn autofocusUpdate(model: *AutofocusModel, msg: AutofocusMsg) void {
1898
+ switch (msg) {
1899
+ .begin_edit => model.editing = true,
1900
+ .draft_edit => |edit| {
1901
+ model.draft.apply(edit);
1902
+ model.edit_count += 1;
1903
+ },
1904
+ }
1905
+ }
1906
+
1907
+ /// The notes shape: Cmd-N-style command mounts an inline editor that
1908
+ /// must receive the keyboard without a click.
1909
+ fn autofocusView(ui: *AutofocusApp.Ui, model: *const AutofocusModel) AutofocusApp.Ui.Node {
1910
+ if (!model.editing) {
1911
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
1912
+ ui.button(.{ .on_press = AutofocusMsg.begin_edit }, "New note"),
1913
+ });
1914
+ }
1915
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
1916
+ ui.button(.{ .on_press = AutofocusMsg.begin_edit }, "New note"),
1917
+ ui.textField(.{
1918
+ .autofocus = true,
1919
+ .text = model.draft.text(),
1920
+ .on_input = AutofocusApp.Ui.inputMsg(.draft_edit),
1921
+ }),
1922
+ });
1923
+ }
1924
+
1925
+ fn autofocusCommand(name: []const u8) ?AutofocusMsg {
1926
+ if (std.mem.eql(u8, name, "note.new")) return .begin_edit;
1927
+ return null;
1928
+ }
1929
+
1930
+ const autofocus_views = [_]app_manifest.ShellView{
1931
+ .{ .label = autofocus_canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
1932
+ };
1933
+ const autofocus_windows = [_]app_manifest.ShellWindow{.{
1934
+ .label = "main",
1935
+ .title = "Autofocus",
1936
+ .width = 400,
1937
+ .height = 300,
1938
+ .views = &autofocus_views,
1939
+ }};
1940
+ const autofocus_scene: app_manifest.ShellConfig = .{ .windows = &autofocus_windows };
1941
+
1942
+ test "ui app autofocus moves the keyboard to a freshly mounted editor through the real dispatch path" {
1943
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
1944
+ defer harness.destroy(std.testing.allocator);
1945
+ harness.null_platform.gpu_surfaces = true;
1946
+
1947
+ const app_state = try std.testing.allocator.create(AutofocusApp);
1948
+ defer std.testing.allocator.destroy(app_state);
1949
+ app_state.* = AutofocusApp.init(std.heap.page_allocator, .{}, .{
1950
+ .name = "ui-app-autofocus",
1951
+ .scene = autofocus_scene,
1952
+ .canvas_label = autofocus_canvas_label,
1953
+ .update = autofocusUpdate,
1954
+ .view = autofocusView,
1955
+ .on_command = autofocusCommand,
1956
+ });
1957
+ defer app_state.deinit();
1958
+ const app = app_state.app();
1959
+ try harness.start(app);
1960
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
1961
+ .label = autofocus_canvas_label,
1962
+ .size = geometry.SizeF.init(400, 300),
1963
+ .scale_factor = 1,
1964
+ .frame_index = 1,
1965
+ .timestamp_ns = 1_000_000,
1966
+ .nonblank = true,
1967
+ } });
1968
+ try std.testing.expect(app_state.installed);
1969
+
1970
+ var view_index: usize = 0;
1971
+ for (harness.runtime.views[0..harness.runtime.view_count], 0..) |view, index| {
1972
+ if (std.mem.eql(u8, view.label, autofocus_canvas_label)) view_index = index;
1973
+ }
1974
+ try std.testing.expectEqual(@as(canvas.ObjectId, 0), harness.runtime.views[view_index].canvas_widget_focused_id);
1975
+
1976
+ // The Cmd-N-shaped command mounts the editor; the rebuild's
1977
+ // autofocus edge moves keyboard focus to it — no click.
1978
+ try harness.runtime.dispatchPlatformEvent(app, .{ .menu_command = .{ .name = "note.new", .window_id = 1 } });
1979
+ try std.testing.expect(app_state.model.editing);
1980
+ const field_id = findWidgetIdByKind(app_state.tree.?.root, .text_field).?;
1981
+ try std.testing.expectEqual(field_id, harness.runtime.views[view_index].canvas_widget_focused_id);
1982
+
1983
+ // Typing lands in the model through the ordinary input path.
1984
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
1985
+ .window_id = 1,
1986
+ .label = autofocus_canvas_label,
1987
+ .kind = .text_input,
1988
+ .text = "Groceries",
1989
+ } });
1990
+ try std.testing.expectEqualStrings("Groceries", app_state.model.draft.text());
1991
+ try std.testing.expect(app_state.model.edit_count > 0);
1992
+
1993
+ // A later rebuild with the flag still true never re-steals focus:
1994
+ // click the button (its press dispatches begin_edit and rebuilds).
1995
+ const button_id = findWidgetIdByKind(app_state.tree.?.root, .button).?;
1996
+ var command_buffer: [96]u8 = undefined;
1997
+ const click_command = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ autofocus_canvas_label, button_id });
1998
+ try harness.runtime.dispatchAutomationCommand(app, click_command);
1999
+ try std.testing.expectEqual(button_id, harness.runtime.views[view_index].canvas_widget_focused_id);
2000
+ }
2001
+
2002
+ // -------------------------------------------------------- layout capacity
2003
+
2004
+ const CapacityModel = struct {
2005
+ row_count: usize = 4,
2006
+
2007
+ pub fn rows(model: *const CapacityModel, arena: std.mem.Allocator) []const usize {
2008
+ const out = arena.alloc(usize, model.row_count) catch return &.{};
2009
+ for (out, 0..) |*slot, index| slot.* = index;
2010
+ return out;
2011
+ }
2012
+ };
2013
+
2014
+ const CapacityMsg = union(enum) {
2015
+ start,
2016
+ grew: effects_mod.EffectExit,
2017
+ };
2018
+
2019
+ const CapacityApp = ui_app_model.UiApp(CapacityModel, CapacityMsg);
2020
+ const CapacityEffects = CapacityApp.Effects;
2021
+ const capacity_key: u64 = 77;
2022
+
2023
+ fn capacityUpdate(model: *CapacityModel, msg: CapacityMsg, fx: *CapacityEffects) void {
2024
+ switch (msg) {
2025
+ .start => fx.spawn(.{
2026
+ .key = capacity_key,
2027
+ .argv = &.{"grow"},
2028
+ .on_exit = CapacityEffects.exitMsg(.grew),
2029
+ }),
2030
+ // The grown roster far exceeds the per-view widget budget.
2031
+ .grew => model.row_count = core.max_canvas_widget_nodes_per_view + 40,
2032
+ }
2033
+ }
2034
+
2035
+ fn capacityKey(index: *const usize) canvas.UiKey {
2036
+ return canvas.uiKey(@as(u64, index.*));
2037
+ }
2038
+
2039
+ fn capacityRow(ui: *CapacityApp.Ui, index: *const usize) CapacityApp.Ui.Node {
2040
+ return ui.text(.{}, ui.fmt("Row {d}", .{index.*}));
2041
+ }
2042
+
2043
+ fn capacityView(ui: *CapacityApp.Ui, model: *const CapacityModel) CapacityApp.Ui.Node {
2044
+ return ui.column(.{ .gap = 2 }, ui.each(model.rows(ui.arena), capacityKey, capacityRow));
2045
+ }
2046
+
2047
+ test "an effects-wake rebuild past the widget budget fails tests loudly and degrades in production" {
2048
+ // A rebuild that blew max_canvas_widget_nodes_per_view
2049
+ // on an effects-wake drain used to vanish into the dispatch-error ring — the
2050
+ // test saw a passing dispatch and a silently stale frame.
2051
+ // The failing layout warns through std.log (the teaching diagnostic
2052
+ // under test would otherwise fail the build runner's stderr check).
2053
+ const saved_log_level = std.testing.log_level;
2054
+ std.testing.log_level = .err;
2055
+ defer std.testing.log_level = saved_log_level;
2056
+
2057
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 2000) });
2058
+ defer harness.destroy(std.testing.allocator);
2059
+ harness.null_platform.gpu_surfaces = true;
2060
+
2061
+ const app_state = try std.testing.allocator.create(CapacityApp);
2062
+ defer std.testing.allocator.destroy(app_state);
2063
+ app_state.* = CapacityApp.init(std.heap.page_allocator, .{}, .{
2064
+ .name = "ui-app-capacity",
2065
+ .scene = counter_scene,
2066
+ .canvas_label = canvas_label,
2067
+ .update_fx = capacityUpdate,
2068
+ .view = capacityView,
2069
+ });
2070
+ defer app_state.deinit();
2071
+ app_state.effects.executor = .fake;
2072
+ const app = app_state.app();
2073
+ try harness.start(app);
2074
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2075
+ .label = canvas_label,
2076
+ .size = geometry.SizeF.init(400, 2000),
2077
+ .scale_factor = 1,
2078
+ .frame_index = 1,
2079
+ .timestamp_ns = 1_000_000,
2080
+ .nonblank = true,
2081
+ } });
2082
+ try std.testing.expect(app_state.installed);
2083
+
2084
+ // A fake spawn exit flips the model past the budget; the wake drain's
2085
+ // rebuild fails — and under the harness's `.propagate` default the
2086
+ // error reaches the test instead of leaving a stale frame.
2087
+ try app_state.dispatch(&harness.runtime, 1, .start);
2088
+ try app_state.effects.feedExit(capacity_key, 0);
2089
+ try std.testing.expectError(
2090
+ error.WidgetLayoutListFull,
2091
+ harness.runtime.dispatchPlatformEvent(app, .wake),
2092
+ );
2093
+ // Recording still happened before the propagate.
2094
+ try std.testing.expectEqual(@as(usize, 1), harness.runtime.dispatchErrors().len);
2095
+ try std.testing.expectEqualStrings("effects_wake", harness.runtime.dispatchErrors()[0].event);
2096
+ try std.testing.expectEqualStrings("WidgetLayoutListFull", harness.runtime.dispatchErrors()[0].error_name);
2097
+
2098
+ // Production policy: the same failure degrades — recorded in the
2099
+ // dispatch-error ring, never fatal.
2100
+ harness.runtime.dispatch_error_policy = .degrade;
2101
+ app_state.model.row_count = 4;
2102
+ try app_state.dispatch(&harness.runtime, 1, .start);
2103
+ try app_state.effects.feedExit(capacity_key, 0);
2104
+ try harness.runtime.dispatchPlatformEvent(app, .wake);
2105
+ try std.testing.expectEqual(@as(usize, 2), harness.runtime.dispatchErrors().len);
2106
+ try std.testing.expectEqualStrings("WidgetLayoutListFull", harness.runtime.dispatchErrors()[1].error_name);
2107
+ }
2108
+
2109
+ // --------------------------------------------------- automation degrade
2110
+
2111
+ test "a stale automation widget click degrades instead of killing the frame callback" {
2112
+ // `frame()` used to `try` the consumed automation
2113
+ // command, so a widget-click on an unmounted id escaped the
2114
+ // frame_requested platform callback and stopped the whole app
2115
+ // (CallbackFailed). Automation misuse always degrades — even under
2116
+ // the harness's `.propagate` policy.
2117
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2118
+ defer harness.destroy(std.testing.allocator);
2119
+ harness.null_platform.gpu_surfaces = true;
2120
+
2121
+ const app_state = try std.testing.allocator.create(CounterApp);
2122
+ defer std.testing.allocator.destroy(app_state);
2123
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, counterOptions());
2124
+ defer app_state.deinit();
2125
+ const app = app_state.app();
2126
+ try harness.start(app);
2127
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2128
+ .label = canvas_label,
2129
+ .size = geometry.SizeF.init(400, 300),
2130
+ .scale_factor = 1,
2131
+ .frame_index = 1,
2132
+ .timestamp_ns = 1_000_000,
2133
+ .nonblank = true,
2134
+ } });
2135
+ try std.testing.expect(app_state.installed);
2136
+
2137
+ // Wire a file-backed automation server and inject a click on a
2138
+ // widget id that is not mounted.
2139
+ const io = std.testing.io;
2140
+ const directory = ".zig-cache/test-ui-app-automation-degrade";
2141
+ var cwd = std.Io.Dir.cwd();
2142
+ cwd.deleteTree(io, directory) catch {};
2143
+ try cwd.createDirPath(io, directory);
2144
+ defer cwd.deleteTree(io, directory) catch {};
2145
+ harness.runtime.options.automation = automation.Server.init(io, directory, "Degrade");
2146
+ var command_path_buffer: [128]u8 = undefined;
2147
+ const command_path = try std.fmt.bufPrint(&command_path_buffer, "{s}/command-1.txt", .{directory});
2148
+ try cwd.writeFile(io, .{ .sub_path = command_path, .data = "widget-click counter-canvas 999999\n" });
2149
+
2150
+ // The frame pump consumes the command without propagating.
2151
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2152
+ const errors = harness.runtime.dispatchErrors();
2153
+ try std.testing.expectEqual(@as(usize, 1), errors.len);
2154
+ try std.testing.expectEqualStrings("automation.widget_click", errors[0].event);
2155
+ try std.testing.expectEqualStrings("InvalidCommand", errors[0].error_name);
2156
+
2157
+ // The app is still alive: a real click keeps dispatching.
2158
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
2159
+ var command_buffer: [96]u8 = undefined;
2160
+ const click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, increment_id });
2161
+ try harness.runtime.dispatchAutomationCommand(app, click);
2162
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
2163
+ }
2164
+
2165
+ test "rapid-fire automation commands all dispatch, one per frame turn" {
2166
+ // The field reproduction for the queued dropbox: three commands land
2167
+ // back-to-back BEFORE the app drains any of them (the old
2168
+ // single-entry slot lost one of these to an overwrite). Zero may be
2169
+ // lost, and the drain must stay one-command-per-`frame_requested`
2170
+ // turn — the recorded event boundary replay determinism hangs on.
2171
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2172
+ defer harness.destroy(std.testing.allocator);
2173
+ harness.null_platform.gpu_surfaces = true;
2174
+
2175
+ const app_state = try std.testing.allocator.create(CounterApp);
2176
+ defer std.testing.allocator.destroy(app_state);
2177
+ app_state.* = CounterApp.init(std.heap.page_allocator, .{}, counterOptions());
2178
+ defer app_state.deinit();
2179
+ const app = app_state.app();
2180
+ try harness.start(app);
2181
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2182
+ .label = canvas_label,
2183
+ .size = geometry.SizeF.init(400, 300),
2184
+ .scale_factor = 1,
2185
+ .frame_index = 1,
2186
+ .timestamp_ns = 1_000_000,
2187
+ .nonblank = true,
2188
+ } });
2189
+ try std.testing.expect(app_state.installed);
2190
+
2191
+ const io = std.testing.io;
2192
+ const directory = ".zig-cache/test-ui-app-automation-rapid-fire";
2193
+ var cwd = std.Io.Dir.cwd();
2194
+ cwd.deleteTree(io, directory) catch {};
2195
+ try cwd.createDirPath(io, directory);
2196
+ defer cwd.deleteTree(io, directory) catch {};
2197
+ harness.runtime.options.automation = automation.Server.init(io, directory, "RapidFire");
2198
+
2199
+ // Three increments queued before a single frame runs.
2200
+ const increment_id = findWidgetIdByText(app_state.tree.?, .button, "Increment").?;
2201
+ var sequence: u64 = 1;
2202
+ while (sequence <= 3) : (sequence += 1) {
2203
+ var command_path_buffer: [128]u8 = undefined;
2204
+ var command_buffer: [128]u8 = undefined;
2205
+ try cwd.writeFile(io, .{
2206
+ .sub_path = try std.fmt.bufPrint(&command_path_buffer, "{s}/command-{d}.txt", .{ directory, sequence }),
2207
+ .data = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}\n", .{ canvas_label, increment_id }),
2208
+ });
2209
+ }
2210
+
2211
+ // Each frame turn consumes exactly one queued command — never two,
2212
+ // never zero — until the queue is drained.
2213
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2214
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.count);
2215
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2216
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.count);
2217
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2218
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.count);
2219
+ // Drained: further frames dispatch nothing and no errors were
2220
+ // recorded along the way.
2221
+ try harness.runtime.dispatchPlatformEvent(app, .frame_requested);
2222
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.count);
2223
+ try std.testing.expectEqual(@as(usize, 0), harness.runtime.dispatchErrors().len);
2224
+ }
2225
+
2226
+ // ---------------------------------------------------------- webview panes
2227
+
2228
+ const preview_canvas_label = "preview-canvas";
2229
+ const preview_pane_anchor = "preview-pane";
2230
+ const example_url = "https://example.com/";
2231
+ const docs_url = "https://native-sdk.dev/";
2232
+
2233
+ const PreviewModel = struct {
2234
+ show_docs: bool = false,
2235
+ reload_token: u64 = 0,
2236
+
2237
+ fn url(model: *const PreviewModel) []const u8 {
2238
+ return if (model.show_docs) docs_url else example_url;
2239
+ }
2240
+ };
2241
+
2242
+ const PreviewMsg = union(enum) {
2243
+ show_docs,
2244
+ show_example,
2245
+ reload,
2246
+ };
2247
+
2248
+ const PreviewApp = ui_app_model.UiApp(PreviewModel, PreviewMsg);
2249
+
2250
+ fn previewUpdate(model: *PreviewModel, msg: PreviewMsg) void {
2251
+ switch (msg) {
2252
+ .show_docs => model.show_docs = true,
2253
+ .show_example => model.show_docs = false,
2254
+ .reload => model.reload_token += 1,
2255
+ }
2256
+ }
2257
+
2258
+ fn previewView(ui: *PreviewApp.Ui, model: *const PreviewModel) PreviewApp.Ui.Node {
2259
+ _ = model;
2260
+ return ui.row(.{ .gap = 0 }, .{
2261
+ ui.column(.{ .width = 200, .padding = 12, .gap = 8 }, .{
2262
+ ui.button(.{ .on_press = .show_docs }, "Docs"),
2263
+ ui.button(.{ .on_press = .show_example }, "Example"),
2264
+ ui.button(.{ .on_press = .reload }, "Reload"),
2265
+ }),
2266
+ // The empty panel that reserves the webview region: the pane
2267
+ // anchor resolves to this widget's layout frame.
2268
+ ui.panel(.{ .grow = 1, .semantics = .{ .label = preview_pane_anchor } }, .{}),
2269
+ });
2270
+ }
2271
+
2272
+ fn previewPanes(model: *const PreviewModel, out: []PreviewApp.WebViewPane) usize {
2273
+ out[0] = .{
2274
+ .label = "preview",
2275
+ .anchor = preview_pane_anchor,
2276
+ .url = model.url(),
2277
+ .reload_token = model.reload_token,
2278
+ };
2279
+ return 1;
2280
+ }
2281
+
2282
+ const preview_views = [_]app_manifest.ShellView{
2283
+ .{ .label = preview_canvas_label, .kind = .gpu_surface, .fill = true, .gpu_backend = .metal },
2284
+ .{ .label = "preview", .kind = .webview, .parent = preview_canvas_label, .url = example_url, .x = 200, .y = 0, .width = 440, .height = 480 },
2285
+ };
2286
+ const preview_windows = [_]app_manifest.ShellWindow{.{
2287
+ .label = "main",
2288
+ .title = "Preview",
2289
+ .width = 640,
2290
+ .height = 480,
2291
+ .views = &preview_views,
2292
+ }};
2293
+ const preview_scene: app_manifest.ShellConfig = .{ .windows = &preview_windows };
2294
+ const preview_origins = [_][]const u8{ "https://example.com", "https://native-sdk.dev", "zero://app", "zero://inline" };
2295
+
2296
+ fn previewOptions() PreviewApp.Options {
2297
+ return .{
2298
+ .name = "ui-app-preview",
2299
+ .scene = preview_scene,
2300
+ .canvas_label = preview_canvas_label,
2301
+ .update = previewUpdate,
2302
+ .view = previewView,
2303
+ .web_panes = previewPanes,
2304
+ };
2305
+ }
2306
+
2307
+ fn previewHarnessAndApp(app_state: *PreviewApp) !*core.TestHarness() {
2308
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(640, 480) });
2309
+ errdefer harness.destroy(std.testing.allocator);
2310
+ harness.null_platform.gpu_surfaces = true;
2311
+ harness.runtime.options.security.navigation.allowed_origins = &preview_origins;
2312
+
2313
+ app_state.* = PreviewApp.init(std.heap.page_allocator, .{}, previewOptions());
2314
+ const app = app_state.app();
2315
+ try harness.start(app);
2316
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2317
+ .label = preview_canvas_label,
2318
+ .size = geometry.SizeF.init(640, 480),
2319
+ .scale_factor = 1,
2320
+ .frame_index = 1,
2321
+ .timestamp_ns = 1_000_000,
2322
+ .nonblank = true,
2323
+ } });
2324
+ return harness;
2325
+ }
2326
+
2327
+ fn previewNullWebView(harness: *core.TestHarness()) !null_platform_mod.NullWebView {
2328
+ for (harness.null_platform.webviews[0..harness.null_platform.webview_count]) |webview| {
2329
+ if (std.mem.eql(u8, webview.label, "preview")) return webview;
2330
+ }
2331
+ return error.TestUnexpectedResult;
2332
+ }
2333
+
2334
+ test "ui app scene with a child webview stays main-webview-free" {
2335
+ const app_state = try std.testing.allocator.create(PreviewApp);
2336
+ defer std.testing.allocator.destroy(app_state);
2337
+ const harness = try previewHarnessAndApp(app_state);
2338
+ defer harness.destroy(std.testing.allocator);
2339
+ defer app_state.deinit();
2340
+
2341
+ // The canvas-first scene never grows an implicit main webview: the
2342
+ // loaded source stays null and only the declared views exist.
2343
+ try std.testing.expect(harness.runtime.loaded_source == null);
2344
+ var views_buffer: [8]zero_platform.ViewInfo = undefined;
2345
+ const views = harness.runtime.listViews(1, &views_buffer);
2346
+ try std.testing.expectEqual(@as(usize, 2), views.len);
2347
+ for (views) |view| {
2348
+ try std.testing.expect(!std.mem.eql(u8, view.label, "main"));
2349
+ }
2350
+ }
2351
+
2352
+ test "ui app webview pane snaps the webview to the anchor widget frame" {
2353
+ const app_state = try std.testing.allocator.create(PreviewApp);
2354
+ defer std.testing.allocator.destroy(app_state);
2355
+ const harness = try previewHarnessAndApp(app_state);
2356
+ defer harness.destroy(std.testing.allocator);
2357
+ defer app_state.deinit();
2358
+
2359
+ try std.testing.expect(app_state.installed);
2360
+ const webview = try previewNullWebView(harness);
2361
+ try std.testing.expect(webview.open);
2362
+ try std.testing.expectEqualStrings(example_url, webview.url);
2363
+
2364
+ // The pane frame is the anchor widget's layout frame: the row's
2365
+ // remaining width after the 200pt sidebar column.
2366
+ const layout = try harness.runtime.canvasWidgetLayout(1, preview_canvas_label);
2367
+ var anchor_frame: ?geometry.RectF = null;
2368
+ for (layout.nodes) |node| {
2369
+ if (std.mem.eql(u8, node.widget.semantics.label, preview_pane_anchor)) anchor_frame = node.frame;
2370
+ }
2371
+ try std.testing.expect(anchor_frame != null);
2372
+ try std.testing.expect(anchor_frame.?.width > 0);
2373
+ try std.testing.expectApproxEqAbs(anchor_frame.?.x, webview.frame.x, 0.5);
2374
+ try std.testing.expectApproxEqAbs(anchor_frame.?.y, webview.frame.y, 0.5);
2375
+ try std.testing.expectApproxEqAbs(anchor_frame.?.width, webview.frame.width, 0.5);
2376
+ try std.testing.expectApproxEqAbs(anchor_frame.?.height, webview.frame.height, 0.5);
2377
+
2378
+ // A resize rebuild follows the anchor to its new frame.
2379
+ try harness.runtime.dispatchPlatformEvent(app_state.app(), .{ .gpu_surface_resized = .{
2380
+ .label = preview_canvas_label,
2381
+ .window_id = 1,
2382
+ .frame = geometry.RectF.init(0, 0, 900, 600),
2383
+ .scale_factor = 1,
2384
+ } });
2385
+ const resized = try previewNullWebView(harness);
2386
+ try std.testing.expectApproxEqAbs(@as(f32, 900 - 200), resized.frame.width, 0.5);
2387
+ try std.testing.expectApproxEqAbs(@as(f32, 600), resized.frame.height, 0.5);
2388
+ }
2389
+
2390
+ test "ui app webview pane navigates on url change and reloads on token bump" {
2391
+ const app_state = try std.testing.allocator.create(PreviewApp);
2392
+ defer std.testing.allocator.destroy(app_state);
2393
+ const harness = try previewHarnessAndApp(app_state);
2394
+ defer harness.destroy(std.testing.allocator);
2395
+ defer app_state.deinit();
2396
+
2397
+ const navigations_after_install = harness.null_platform.webview_navigate_count;
2398
+
2399
+ // A model-driven URL change navigates the webview.
2400
+ try app_state.dispatch(&harness.runtime, 1, .show_docs);
2401
+ var webview = try previewNullWebView(harness);
2402
+ try std.testing.expectEqualStrings(docs_url, webview.url);
2403
+ try std.testing.expectEqual(navigations_after_install + 1, harness.null_platform.webview_navigate_count);
2404
+
2405
+ // A rebuild without a URL change does not renavigate.
2406
+ try app_state.dispatch(&harness.runtime, 1, .show_docs);
2407
+ try std.testing.expectEqual(navigations_after_install + 1, harness.null_platform.webview_navigate_count);
2408
+
2409
+ // Bumping the reload token renavigates the same URL.
2410
+ try app_state.dispatch(&harness.runtime, 1, .reload);
2411
+ webview = try previewNullWebView(harness);
2412
+ try std.testing.expectEqualStrings(docs_url, webview.url);
2413
+ try std.testing.expectEqual(navigations_after_install + 2, harness.null_platform.webview_navigate_count);
2414
+ }
2415
+
2416
+ // ----------------------------------------------------------- status item
2417
+
2418
+ const StatusModel = struct {
2419
+ refresh_count: u32 = 0,
2420
+ };
2421
+
2422
+ const StatusMsg = union(enum) {
2423
+ refresh,
2424
+ };
2425
+
2426
+ const StatusApp = ui_app_model.UiApp(StatusModel, StatusMsg);
2427
+
2428
+ fn statusUpdate(model: *StatusModel, msg: StatusMsg) void {
2429
+ switch (msg) {
2430
+ .refresh => model.refresh_count += 1,
2431
+ }
2432
+ }
2433
+
2434
+ fn statusView(ui: *StatusApp.Ui, model: *const StatusModel) StatusApp.Ui.Node {
2435
+ return ui.column(.{ .padding = 12 }, .{
2436
+ ui.text(.{}, ui.fmt("Refreshed {d}", .{model.refresh_count})),
2437
+ });
2438
+ }
2439
+
2440
+ fn statusCommand(name: []const u8) ?StatusMsg {
2441
+ if (std.mem.eql(u8, name, "app.refresh")) return .refresh;
2442
+ return null;
2443
+ }
2444
+
2445
+ const status_items = [_]zero_platform.TrayMenuItem{
2446
+ .{ .id = 1, .label = "Refresh", .command = "app.refresh" },
2447
+ .{ .separator = true },
2448
+ .{ .id = 2, .label = "About" },
2449
+ };
2450
+
2451
+ test "ui app status item installs a tray and dispatches its commands" {
2452
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2453
+ defer harness.destroy(std.testing.allocator);
2454
+ harness.null_platform.gpu_surfaces = true;
2455
+
2456
+ const app_state = try std.testing.allocator.create(StatusApp);
2457
+ defer std.testing.allocator.destroy(app_state);
2458
+ app_state.* = StatusApp.init(std.heap.page_allocator, .{}, .{
2459
+ .name = "ui-app-status",
2460
+ .scene = counter_scene,
2461
+ .canvas_label = canvas_label,
2462
+ .update = statusUpdate,
2463
+ .view = statusView,
2464
+ .on_command = statusCommand,
2465
+ .status_item = .{
2466
+ .title = "NS",
2467
+ .tooltip = "native-sdk status",
2468
+ .items = &status_items,
2469
+ },
2470
+ });
2471
+ defer app_state.deinit();
2472
+ const app = app_state.app();
2473
+ try harness.start(app);
2474
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.trayCreateCount());
2475
+
2476
+ // The installing frame creates the status item exactly once.
2477
+ const frame_event = zero_platform.GpuSurfaceFrameEvent{
2478
+ .label = canvas_label,
2479
+ .size = geometry.SizeF.init(400, 300),
2480
+ .scale_factor = 1,
2481
+ .frame_index = 1,
2482
+ .timestamp_ns = 1_000_000,
2483
+ .nonblank = true,
2484
+ };
2485
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = frame_event });
2486
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayCreateCount());
2487
+ try std.testing.expectEqualStrings("NS", harness.null_platform.lastTrayTitle());
2488
+ try std.testing.expectEqualStrings("native-sdk status", harness.null_platform.lastTrayTooltip());
2489
+ try std.testing.expectEqual(@as(usize, 3), harness.null_platform.trayItems().len);
2490
+ var second_frame = frame_event;
2491
+ second_frame.frame_index = 2;
2492
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = second_frame });
2493
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayCreateCount());
2494
+
2495
+ // Selecting the item dispatches its command through on_command.
2496
+ try harness.runtime.dispatchPlatformEvent(app, .{ .tray_action = 1 });
2497
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.refresh_count);
2498
+ // Items without commands fall back to the generic name and map to
2499
+ // no Msg here.
2500
+ try harness.runtime.dispatchPlatformEvent(app, .{ .tray_action = 2 });
2501
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.refresh_count);
2502
+ }
2503
+
2504
+ // ------------------------------------------------ model-driven status item
2505
+
2506
+ const TrayStateModel = struct {
2507
+ open_count: u32 = 3,
2508
+ selected_issue: u32 = 0,
2509
+ issues: [2][]const u8 = .{ "Fix crash on resize", "Adopt the tray seam" },
2510
+ };
2511
+
2512
+ const TrayStateMsg = union(enum) {
2513
+ refresh,
2514
+ select_issue: u32,
2515
+ };
2516
+
2517
+ const TrayStateApp = ui_app_model.UiApp(TrayStateModel, TrayStateMsg);
2518
+
2519
+ fn trayStateUpdate(model: *TrayStateModel, msg: TrayStateMsg) void {
2520
+ switch (msg) {
2521
+ .refresh => model.open_count += 1,
2522
+ .select_issue => |index| model.selected_issue = index,
2523
+ }
2524
+ }
2525
+
2526
+ fn trayStateView(ui: *TrayStateApp.Ui, model: *const TrayStateModel) TrayStateApp.Ui.Node {
2527
+ return ui.column(.{ .padding = 12 }, .{
2528
+ ui.text(.{}, ui.fmt("Selected {d}", .{model.selected_issue})),
2529
+ });
2530
+ }
2531
+
2532
+ fn trayStateCommand(name: []const u8) ?TrayStateMsg {
2533
+ if (std.mem.eql(u8, name, "app.refresh")) return .refresh;
2534
+ if (std.mem.eql(u8, name, "issue.select.0")) return .{ .select_issue = 0 };
2535
+ if (std.mem.eql(u8, name, "issue.select.1")) return .{ .select_issue = 1 };
2536
+ return null;
2537
+ }
2538
+
2539
+ /// A desktop issues-client menu-bar extra shape: an open-count badge in
2540
+ /// the title and the latest issues in the dropdown, each row selecting
2541
+ /// its issue.
2542
+ fn trayStateStatusItem(model: *const TrayStateModel, scratch: *TrayStateApp.StatusItemScratch) TrayStateApp.StatusItemState {
2543
+ const title = std.fmt.bufPrint(&scratch.title_buffer, "ZN {d}", .{model.open_count}) catch "ZN";
2544
+ scratch.items[0] = .{ .id = 1, .label = "Refresh", .command = "app.refresh" };
2545
+ scratch.items[1] = .{ .separator = true };
2546
+ const commands = [_][]const u8{ "issue.select.0", "issue.select.1" };
2547
+ for (model.issues, 0..) |issue_title, index| {
2548
+ scratch.items[2 + index] = .{
2549
+ .id = @intCast(10 + index),
2550
+ .label = issue_title,
2551
+ .command = commands[index],
2552
+ // The selected row reads as such (also exercises menu-change
2553
+ // detection when the selection moves).
2554
+ .enabled = model.selected_issue != index,
2555
+ };
2556
+ }
2557
+ return .{ .title = title, .items = scratch.items[0..4] };
2558
+ }
2559
+
2560
+ test "ui app status_item_fn drives the tray title and menu from the model" {
2561
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2562
+ defer harness.destroy(std.testing.allocator);
2563
+ harness.null_platform.gpu_surfaces = true;
2564
+
2565
+ const app_state = try std.testing.allocator.create(TrayStateApp);
2566
+ defer std.testing.allocator.destroy(app_state);
2567
+ app_state.* = TrayStateApp.init(std.heap.page_allocator, .{}, .{
2568
+ .name = "ui-app-tray-state",
2569
+ .scene = counter_scene,
2570
+ .canvas_label = canvas_label,
2571
+ .update = trayStateUpdate,
2572
+ .view = trayStateView,
2573
+ .on_command = trayStateCommand,
2574
+ .status_item = .{ .tooltip = "issue tracker" },
2575
+ .status_item_fn = trayStateStatusItem,
2576
+ });
2577
+ defer app_state.deinit();
2578
+ const app = app_state.app();
2579
+ try harness.start(app);
2580
+
2581
+ // The installing frame creates the tray FROM THE MODEL: derived
2582
+ // title, derived dropdown, static tooltip.
2583
+ const frame_event = zero_platform.GpuSurfaceFrameEvent{
2584
+ .label = canvas_label,
2585
+ .size = geometry.SizeF.init(400, 300),
2586
+ .scale_factor = 1,
2587
+ .frame_index = 1,
2588
+ .timestamp_ns = 1_000_000,
2589
+ .nonblank = true,
2590
+ };
2591
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = frame_event });
2592
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayCreateCount());
2593
+ try std.testing.expectEqualStrings("ZN 3", harness.null_platform.lastTrayTitle());
2594
+ try std.testing.expectEqualStrings("issue tracker", harness.null_platform.lastTrayTooltip());
2595
+ try std.testing.expectEqual(@as(usize, 4), harness.null_platform.trayItems().len);
2596
+ try std.testing.expectEqualStrings("Fix crash on resize", harness.null_platform.trayItems()[2].label);
2597
+ const updates_after_install = harness.null_platform.trayUpdateCount();
2598
+ try std.testing.expectEqual(@as(usize, 0), harness.null_platform.trayTitleUpdateCount());
2599
+
2600
+ // A model change that only affects the TITLE re-titles the live
2601
+ // button without rebuilding the menu or re-creating the item.
2602
+ try harness.runtime.dispatchPlatformEvent(app, .{ .tray_action = 1 });
2603
+ try std.testing.expectEqual(@as(u32, 4), app_state.model.open_count);
2604
+ try std.testing.expectEqualStrings("ZN 4", harness.null_platform.lastTrayTitle());
2605
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayTitleUpdateCount());
2606
+ try std.testing.expectEqual(updates_after_install, harness.null_platform.trayUpdateCount());
2607
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayCreateCount());
2608
+
2609
+ // Selecting a dropdown row closes the loop: tray action -> command ->
2610
+ // Msg -> model, and the menu (not the title) re-applies.
2611
+ try harness.runtime.dispatchPlatformEvent(app, .{ .tray_action = 11 });
2612
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.selected_issue);
2613
+ try std.testing.expectEqual(updates_after_install + 1, harness.null_platform.trayUpdateCount());
2614
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayTitleUpdateCount());
2615
+ try std.testing.expect(!harness.null_platform.trayItems()[3].enabled);
2616
+
2617
+ // A rebuild whose tray output is unchanged touches nothing (the
2618
+ // repeat selection Msg still rebuilds the view).
2619
+ try harness.runtime.dispatchPlatformEvent(app, .{ .tray_action = 11 });
2620
+ try std.testing.expectEqual(updates_after_install + 1, harness.null_platform.trayUpdateCount());
2621
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayTitleUpdateCount());
2622
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.trayCreateCount());
2623
+ }
2624
+
2625
+ test "ui app tray state rides automation snapshots and tray-action drives a row" {
2626
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2627
+ defer harness.destroy(std.testing.allocator);
2628
+ harness.null_platform.gpu_surfaces = true;
2629
+
2630
+ const app_state = try std.testing.allocator.create(TrayStateApp);
2631
+ defer std.testing.allocator.destroy(app_state);
2632
+ app_state.* = TrayStateApp.init(std.heap.page_allocator, .{}, .{
2633
+ .name = "ui-app-tray-automation",
2634
+ .scene = counter_scene,
2635
+ .canvas_label = canvas_label,
2636
+ .update = trayStateUpdate,
2637
+ .view = trayStateView,
2638
+ .on_command = trayStateCommand,
2639
+ .status_item = .{ .tooltip = "issue tracker" },
2640
+ .status_item_fn = trayStateStatusItem,
2641
+ });
2642
+ defer app_state.deinit();
2643
+ const app = app_state.app();
2644
+ try harness.start(app);
2645
+
2646
+ // Before the tray installs, snapshots carry no tray lines.
2647
+ {
2648
+ var buffer: [32768]u8 = undefined;
2649
+ var writer = std.Io.Writer.fixed(&buffer);
2650
+ try automation.snapshot.writeText(harness.runtime.automationSnapshot("Tray"), &writer);
2651
+ try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "tray title=") == null);
2652
+ }
2653
+
2654
+ const frame_event = zero_platform.GpuSurfaceFrameEvent{
2655
+ .label = canvas_label,
2656
+ .size = geometry.SizeF.init(400, 300),
2657
+ .scale_factor = 1,
2658
+ .frame_index = 1,
2659
+ .timestamp_ns = 1_000_000,
2660
+ .nonblank = true,
2661
+ };
2662
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = frame_event });
2663
+
2664
+ // The snapshot exposes the applied tray: model-derived title, every
2665
+ // dropdown row with id/label/command/enabled, and separators —
2666
+ // the menu bar is outside every window capture, so this is the only
2667
+ // automation-visible evidence the model-driven tray exists.
2668
+ {
2669
+ var buffer: [32768]u8 = undefined;
2670
+ var writer = std.Io.Writer.fixed(&buffer);
2671
+ try automation.snapshot.writeText(harness.runtime.automationSnapshot("Tray"), &writer);
2672
+ const text = writer.buffered();
2673
+ try std.testing.expect(std.mem.indexOf(u8, text, "tray title=\"ZN 3\" items=4\n") != null);
2674
+ try std.testing.expect(std.mem.indexOf(u8, text, " tray-item #1 label=\"Refresh\" command=\"app.refresh\" enabled=true\n") != null);
2675
+ try std.testing.expect(std.mem.indexOf(u8, text, " tray-item separator\n") != null);
2676
+ // The fixture disables the SELECTED row (initially issue 0).
2677
+ try std.testing.expect(std.mem.indexOf(u8, text, " tray-item #10 label=\"Fix crash on resize\" command=\"issue.select.0\" enabled=false\n") != null);
2678
+ }
2679
+
2680
+ // `tray-action <id>` drives a dropdown row through the same platform
2681
+ // event a real NSStatusItem menu click emits: command -> Msg -> model,
2682
+ // and the re-derived tray re-applies.
2683
+ try harness.runtime.dispatchAutomationCommand(app, "tray-action 11");
2684
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.selected_issue);
2685
+ {
2686
+ var buffer: [32768]u8 = undefined;
2687
+ var writer = std.Io.Writer.fixed(&buffer);
2688
+ try automation.snapshot.writeText(harness.runtime.automationSnapshot("Tray"), &writer);
2689
+ const text = writer.buffered();
2690
+ try std.testing.expect(std.mem.indexOf(u8, text, " tray-item #11 label=\"Adopt the tray seam\" command=\"issue.select.1\" enabled=false\n") != null);
2691
+ try std.testing.expect(std.mem.indexOf(u8, text, " tray-item #10 label=\"Fix crash on resize\" command=\"issue.select.0\" enabled=true\n") != null);
2692
+ }
2693
+
2694
+ // Unknown or malformed item ids are loud driver misuse, never a
2695
+ // silent no-op or a fallback command dispatch.
2696
+ try std.testing.expectError(error.InvalidCommand, harness.runtime.dispatchAutomationCommand(app, "tray-action 99"));
2697
+ try std.testing.expectError(error.InvalidCommand, harness.runtime.dispatchAutomationCommand(app, "tray-action open"));
2698
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.selected_issue);
2699
+ }
2700
+
2701
+ const TaskModel = struct {
2702
+ completed: u32 = 0,
2703
+ deleted: u32 = 0,
2704
+ };
2705
+
2706
+ const TaskMsg = union(enum) {
2707
+ complete,
2708
+ delete,
2709
+ };
2710
+
2711
+ const TaskApp = ui_app_model.UiApp(TaskModel, TaskMsg);
2712
+
2713
+ fn taskUpdate(model: *TaskModel, msg: TaskMsg) void {
2714
+ switch (msg) {
2715
+ .complete => model.completed += 1,
2716
+ .delete => model.deleted += 1,
2717
+ }
2718
+ }
2719
+
2720
+ fn taskView(ui: *TaskApp.Ui, model: *const TaskModel) TaskApp.Ui.Node {
2721
+ _ = model;
2722
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
2723
+ ui.el(.list_item, .{
2724
+ .text = "Ship the release",
2725
+ .context_menu = &.{
2726
+ .{ .label = "Complete", .msg = .complete },
2727
+ .{ .separator = true },
2728
+ .{ .label = "Delete", .msg = .delete },
2729
+ },
2730
+ }, .{}),
2731
+ });
2732
+ }
2733
+
2734
+ test "ui app dispatches native context menu selections as typed messages" {
2735
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2736
+ defer harness.destroy(std.testing.allocator);
2737
+ harness.null_platform.gpu_surfaces = true;
2738
+
2739
+ const app_state = try std.testing.allocator.create(TaskApp);
2740
+ defer std.testing.allocator.destroy(app_state);
2741
+ app_state.* = TaskApp.init(std.heap.page_allocator, .{}, .{
2742
+ .name = "ui-app-context-menu",
2743
+ .scene = counter_scene,
2744
+ .canvas_label = canvas_label,
2745
+ .update = taskUpdate,
2746
+ .view = taskView,
2747
+ });
2748
+ defer app_state.deinit();
2749
+ const app = app_state.app();
2750
+ try harness.start(app);
2751
+
2752
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2753
+ .label = canvas_label,
2754
+ .size = geometry.SizeF.init(400, 300),
2755
+ .scale_factor = 2,
2756
+ .frame_index = 1,
2757
+ .timestamp_ns = 1_000_000,
2758
+ .nonblank = true,
2759
+ } });
2760
+ try std.testing.expect(app_state.installed);
2761
+
2762
+ // Right-click inside the row's retained frame.
2763
+ const row_id = findIn(app_state.tree.?.root, .list_item, "Ship the release").?;
2764
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
2765
+ var row_frame: geometry.RectF = .{};
2766
+ for (layout.nodes) |node| {
2767
+ if (node.widget.id == row_id) row_frame = node.frame;
2768
+ }
2769
+ try std.testing.expect(!row_frame.isEmpty());
2770
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
2771
+ .window_id = 1,
2772
+ .label = canvas_label,
2773
+ .kind = .pointer_down,
2774
+ .button = 1,
2775
+ .x = row_frame.x + 4,
2776
+ .y = row_frame.y + 4,
2777
+ .timestamp_ns = 2_000_000,
2778
+ } });
2779
+ try std.testing.expectEqual(@as(usize, 1), harness.null_platform.context_menu_request_count);
2780
+ try std.testing.expectEqual(@as(u64, row_id), harness.null_platform.context_menu_token);
2781
+ try std.testing.expectEqual(@as(usize, 3), harness.null_platform.contextMenuItems().len);
2782
+
2783
+ // Selecting "Delete" (item id 3 = third declared entry) dispatches
2784
+ // the declared Msg through update.
2785
+ try harness.runtime.dispatchPlatformEvent(app, .{ .context_menu_action = .{
2786
+ .window_id = 1,
2787
+ .view_label = canvas_label,
2788
+ .token = row_id,
2789
+ .item_id = 3,
2790
+ } });
2791
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.deleted);
2792
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.completed);
2793
+ }
2794
+
2795
+ // ------------------------------------------------- press fall-through fixture
2796
+
2797
+ const RowsModel = struct {
2798
+ picked: u32 = 0,
2799
+ picks: u32 = 0,
2800
+ button_hits: u32 = 0,
2801
+ };
2802
+
2803
+ const RowsMsg = union(enum) {
2804
+ pick: u32,
2805
+ button_hit,
2806
+ };
2807
+
2808
+ const RowsApp = ui_app_model.UiApp(RowsModel, RowsMsg);
2809
+
2810
+ fn rowsUpdate(model: *RowsModel, msg: RowsMsg) void {
2811
+ switch (msg) {
2812
+ .pick => |id| {
2813
+ model.picked = id;
2814
+ model.picks += 1;
2815
+ },
2816
+ .button_hit => model.button_hits += 1,
2817
+ }
2818
+ }
2819
+
2820
+ fn rowsView(ui: *RowsApp.Ui, model: *const RowsModel) RowsApp.Ui.Node {
2821
+ _ = model;
2822
+ // The showcase row shape the press fall-through exists for: pressable
2823
+ // panels whose visible content is plain (selectable) text — no
2824
+ // empty-text overlays, no duplicated handlers on the text leaves.
2825
+ return ui.column(.{ .gap = 8, .padding = 12 }, .{
2826
+ ui.panel(.{ .on_press = RowsMsg{ .pick = 1 }, .height = 48 }, .{
2827
+ ui.row(.{ .gap = 8, .padding = 8 }, .{
2828
+ ui.text(.{ .grow = 1 }, "Alpha row label"),
2829
+ }),
2830
+ }),
2831
+ ui.panel(.{ .on_press = RowsMsg{ .pick = 2 }, .height = 48 }, .{
2832
+ ui.row(.{ .gap = 8, .padding = 8 }, .{
2833
+ ui.text(.{ .grow = 1 }, "Beta row label"),
2834
+ ui.button(.{ .on_press = .button_hit }, "Open"),
2835
+ }),
2836
+ }),
2837
+ });
2838
+ }
2839
+
2840
+ fn rowsOptions() RowsApp.Options {
2841
+ return .{
2842
+ .name = "ui-app-rows",
2843
+ .scene = counter_scene,
2844
+ .canvas_label = canvas_label,
2845
+ .update = rowsUpdate,
2846
+ .view = rowsView,
2847
+ };
2848
+ }
2849
+
2850
+ fn rowsWidgetCenter(runtime: *core.Runtime, id: canvas.ObjectId) !geometry.PointF {
2851
+ const layout = try runtime.canvasWidgetLayout(1, canvas_label);
2852
+ return layout.findById(id).?.frame.normalized().center();
2853
+ }
2854
+
2855
+ fn rowsPointer(kind: zero_platform.GpuSurfaceInputKind, point: geometry.PointF, timestamp_ns: u64) zero_platform.Event {
2856
+ return .{ .gpu_surface_input = .{
2857
+ .label = canvas_label,
2858
+ .kind = kind,
2859
+ .timestamp_ns = timestamp_ns,
2860
+ .x = point.x,
2861
+ .y = point.y,
2862
+ } };
2863
+ }
2864
+
2865
+ fn rowsTextSelection(runtime: *core.Runtime, id: canvas.ObjectId) !?canvas.TextSelection {
2866
+ const layout = try runtime.canvasWidgetLayout(1, canvas_label);
2867
+ return layout.findById(id).?.widget.text_selection;
2868
+ }
2869
+
2870
+ test "presses on a pressable row's plain text land on the row, live and via automation" {
2871
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2872
+ defer harness.destroy(std.testing.allocator);
2873
+ harness.null_platform.gpu_surfaces = true;
2874
+
2875
+ const app_state = try std.testing.allocator.create(RowsApp);
2876
+ defer std.testing.allocator.destroy(app_state);
2877
+ app_state.* = RowsApp.init(std.heap.page_allocator, .{}, rowsOptions());
2878
+ defer app_state.deinit();
2879
+ const app = app_state.app();
2880
+ try harness.start(app);
2881
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2882
+ .label = canvas_label,
2883
+ .size = geometry.SizeF.init(400, 300),
2884
+ .scale_factor = 2,
2885
+ .frame_index = 1,
2886
+ .timestamp_ns = 1_000_000,
2887
+ .nonblank = true,
2888
+ } });
2889
+ try std.testing.expect(app_state.installed);
2890
+
2891
+ const tree = app_state.tree.?;
2892
+ const alpha_row_id = tree.root.children[0].id;
2893
+ const alpha_text_id = findIn(tree.root, .text, "Alpha row label").?;
2894
+ const button_id = findIn(tree.root, .button, "Open").?;
2895
+
2896
+ // A live click on the row's plain text lands on the row's on_press.
2897
+ const text_center = try rowsWidgetCenter(&harness.runtime, alpha_text_id);
2898
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_down, text_center, 2_000_000));
2899
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_up, text_center, 2_100_000));
2900
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.picks);
2901
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.picked);
2902
+
2903
+ // A button inside a pressable row claims its own press — the button
2904
+ // wins, the row does not fire.
2905
+ const button_center = try rowsWidgetCenter(&harness.runtime, button_id);
2906
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_down, button_center, 3_000_000));
2907
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_up, button_center, 3_100_000));
2908
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.button_hits);
2909
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.picks);
2910
+
2911
+ // The automation click path agrees with the live hit test: clicking
2912
+ // the row id (whose center is covered by its text) and clicking the
2913
+ // text id both land on the row.
2914
+ var command_buffer: [96]u8 = undefined;
2915
+ const row_click = try std.fmt.bufPrint(&command_buffer, "widget-click {s} {d}", .{ canvas_label, alpha_row_id });
2916
+ try harness.runtime.dispatchAutomationCommand(app, row_click);
2917
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.picks);
2918
+ var text_command_buffer: [96]u8 = undefined;
2919
+ const text_click = try std.fmt.bufPrint(&text_command_buffer, "widget-click {s} {d}", .{ canvas_label, alpha_text_id });
2920
+ try harness.runtime.dispatchAutomationCommand(app, text_click);
2921
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.picks);
2922
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.button_hits);
2923
+ }
2924
+
2925
+ test "selection drag inside a pressable row selects without pressing; a click still presses" {
2926
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
2927
+ defer harness.destroy(std.testing.allocator);
2928
+ harness.null_platform.gpu_surfaces = true;
2929
+
2930
+ const app_state = try std.testing.allocator.create(RowsApp);
2931
+ defer std.testing.allocator.destroy(app_state);
2932
+ app_state.* = RowsApp.init(std.heap.page_allocator, .{}, rowsOptions());
2933
+ defer app_state.deinit();
2934
+ const app = app_state.app();
2935
+ try harness.start(app);
2936
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
2937
+ .label = canvas_label,
2938
+ .size = geometry.SizeF.init(400, 300),
2939
+ .scale_factor = 2,
2940
+ .frame_index = 1,
2941
+ .timestamp_ns = 1_000_000,
2942
+ .nonblank = true,
2943
+ } });
2944
+
2945
+ const alpha_text_id = findIn(app_state.tree.?.root, .text, "Alpha row label").?;
2946
+ const layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
2947
+ const text_frame = layout.findById(alpha_text_id).?.frame.normalized();
2948
+ const start = geometry.PointF.init(text_frame.x + 2, text_frame.center().y);
2949
+ const end = geometry.PointF.init(text_frame.x + text_frame.width * 0.7, text_frame.center().y);
2950
+
2951
+ // Down + drag + up: the gesture selects text within the row and
2952
+ // presses NOTHING — dragging selects, clicking presses.
2953
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_down, start, 2_000_000));
2954
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_drag, end, 2_050_000));
2955
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_up, end, 2_100_000));
2956
+ const selection = (try rowsTextSelection(&harness.runtime, alpha_text_id)).?;
2957
+ try std.testing.expect(!selection.isCollapsed("Alpha row label".len));
2958
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.picks);
2959
+
2960
+ // A plain click on the same text collapses the selection on the way
2961
+ // down and the press lands on the row.
2962
+ const center = try rowsWidgetCenter(&harness.runtime, alpha_text_id);
2963
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_down, center, 3_000_000));
2964
+ try harness.runtime.dispatchPlatformEvent(app, rowsPointer(.pointer_up, center, 3_100_000));
2965
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.picks);
2966
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.picked);
2967
+ }
2968
+
2969
+ // --------------------------------------------------------------- on_chrome
2970
+
2971
+ const ChromeInsetModel = struct {
2972
+ leading: f32 = 0,
2973
+ top: f32 = 0,
2974
+ /// The traffic-light cluster's vertical centerline — what a header
2975
+ /// centers its controls against in the tall band.
2976
+ buttons_center_y: f32 = 0,
2977
+ deliveries: u32 = 0,
2978
+ };
2979
+
2980
+ const ChromeInsetMsg = union(enum) {
2981
+ chrome: zero_platform.WindowChrome,
2982
+ };
2983
+
2984
+ const ChromeInsetApp = ui_app_model.UiApp(ChromeInsetModel, ChromeInsetMsg);
2985
+
2986
+ fn chromeInsetUpdate(model: *ChromeInsetModel, msg: ChromeInsetMsg) void {
2987
+ switch (msg) {
2988
+ .chrome => |chrome| {
2989
+ model.leading = chrome.insets.left;
2990
+ model.top = chrome.insets.top;
2991
+ model.buttons_center_y = chrome.buttons.y + chrome.buttons.height / 2;
2992
+ model.deliveries += 1;
2993
+ },
2994
+ }
2995
+ }
2996
+
2997
+ fn chromeInsetView(ui: *ChromeInsetApp.Ui, model: *const ChromeInsetModel) ChromeInsetApp.Ui.Node {
2998
+ return ui.column(.{ .gap = 8 }, .{
2999
+ ui.row(.{ .window_drag = true, .height = 40 }, .{
3000
+ ui.el(.stack, .{ .width = model.leading }, .{}),
3001
+ ui.text(.{}, "Header"),
3002
+ }),
3003
+ ui.text(.{}, ui.fmt("leading {d}", .{model.leading})),
3004
+ });
3005
+ }
3006
+
3007
+ fn chromeInsetMap(chrome: zero_platform.WindowChrome) ?ChromeInsetMsg {
3008
+ return .{ .chrome = chrome };
3009
+ }
3010
+
3011
+ test "ui app delivers chrome overlay geometry before install and on change" {
3012
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
3013
+ defer harness.destroy(std.testing.allocator);
3014
+ harness.null_platform.gpu_surfaces = true;
3015
+ // Model a tall hidden-titlebar macOS host: unified band 52pt tall,
3016
+ // traffic lights ending 78pt in and vertically centered in the band.
3017
+ harness.null_platform.window_chrome = .{
3018
+ .insets = .{ .top = 52, .left = 78 },
3019
+ .buttons = geometry.RectF.init(12, 19, 54, 14),
3020
+ };
3021
+
3022
+ const app_state = try std.testing.allocator.create(ChromeInsetApp);
3023
+ defer std.testing.allocator.destroy(app_state);
3024
+ app_state.* = ChromeInsetApp.init(std.heap.page_allocator, .{}, .{
3025
+ .name = "ui-app-chrome",
3026
+ .scene = counter_scene,
3027
+ .canvas_label = canvas_label,
3028
+ .update = chromeInsetUpdate,
3029
+ .view = chromeInsetView,
3030
+ .on_chrome = chromeInsetMap,
3031
+ });
3032
+ defer app_state.deinit();
3033
+ const app = app_state.app();
3034
+ try harness.start(app);
3035
+
3036
+ // The insets land in the model BEFORE the first view build, so the
3037
+ // installing frame already renders the padded header.
3038
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
3039
+ .label = canvas_label,
3040
+ .size = geometry.SizeF.init(400, 300),
3041
+ .scale_factor = 2,
3042
+ .frame_index = 1,
3043
+ .timestamp_ns = 1_000_000,
3044
+ .nonblank = true,
3045
+ } });
3046
+ try std.testing.expect(app_state.installed);
3047
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.deliveries);
3048
+ try std.testing.expectEqual(@as(f32, 78), app_state.model.leading);
3049
+ try std.testing.expectEqual(@as(f32, 52), app_state.model.top);
3050
+ // The buttons frame carries the vertical truth: centerline at
3051
+ // 19 + 14/2 = 26, the tall band's midpoint.
3052
+ try std.testing.expectEqual(@as(f32, 26), app_state.model.buttons_center_y);
3053
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "leading 78"));
3054
+
3055
+ // A resize with unchanged insets dispatches nothing extra.
3056
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_resized = .{
3057
+ .window_id = 1,
3058
+ .label = canvas_label,
3059
+ .frame = geometry.RectF.init(0, 0, 640, 480),
3060
+ .scale_factor = 2,
3061
+ } });
3062
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.deliveries);
3063
+
3064
+ // Fullscreen hides the chrome: the resize that accompanies the
3065
+ // transition re-queries and delivers the zeroed geometry.
3066
+ harness.null_platform.window_chrome = .{};
3067
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_resized = .{
3068
+ .window_id = 1,
3069
+ .label = canvas_label,
3070
+ .frame = geometry.RectF.init(0, 0, 1440, 900),
3071
+ .scale_factor = 2,
3072
+ } });
3073
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.deliveries);
3074
+ try std.testing.expectEqual(@as(f32, 0), app_state.model.leading);
3075
+ try std.testing.expectEqual(@as(f32, 0), app_state.model.buttons_center_y);
3076
+ try std.testing.expect(try retainedTextExists(&harness.runtime, "leading 0"));
3077
+ }
3078
+
3079
+ // -------------------------------------- windowed virtual list fixture
3080
+
3081
+ const VirtualFeedModel = struct {
3082
+ /// Items currently loaded; `load_more` appends batches to a cap.
3083
+ loaded: usize = 400,
3084
+ /// Every reach-end dispatch, including the ones past the cap.
3085
+ fetches: u32 = 0,
3086
+ };
3087
+
3088
+ const VirtualFeedMsg = union(enum) {
3089
+ load_more,
3090
+ };
3091
+
3092
+ const VirtualFeedApp = ui_app_model.UiApp(VirtualFeedModel, VirtualFeedMsg);
3093
+
3094
+ const virtual_feed_batch: usize = 100;
3095
+ const virtual_feed_cap: usize = 600;
3096
+ const virtual_row_extent: f32 = 24;
3097
+
3098
+ fn virtualFeedUpdate(model: *VirtualFeedModel, msg: VirtualFeedMsg) void {
3099
+ switch (msg) {
3100
+ .load_more => {
3101
+ model.fetches += 1;
3102
+ if (model.loaded < virtual_feed_cap) model.loaded += virtual_feed_batch;
3103
+ },
3104
+ }
3105
+ }
3106
+
3107
+ fn virtualFeedOptions(model: *const VirtualFeedModel) VirtualFeedApp.Ui.VirtualListOptions {
3108
+ return .{
3109
+ .id = "vfeed",
3110
+ .item_count = model.loaded,
3111
+ .item_extent = virtual_row_extent,
3112
+ .overscan = 2,
3113
+ .grow = 1,
3114
+ .on_reach_end = .load_more,
3115
+ };
3116
+ }
3117
+
3118
+ /// The windowed pattern: ask for the visible range, build ONLY those
3119
+ /// rows from the model, hand both to `virtualList`. Deliberately no
3120
+ /// `on_scroll` binding — the runtime re-derives the view on scroll for
3121
+ /// mounted virtual lists on its own.
3122
+ fn virtualFeedView(ui: *VirtualFeedApp.Ui, model: *const VirtualFeedModel) VirtualFeedApp.Ui.Node {
3123
+ const options = virtualFeedOptions(model);
3124
+ const window = ui.virtualWindow(options);
3125
+ const rows = ui.arena.alloc(VirtualFeedApp.Ui.Node, window.itemCount()) catch {
3126
+ ui.failed = true;
3127
+ return ui.column(.{}, .{});
3128
+ };
3129
+ for (rows, 0..) |*row, offset| {
3130
+ const index = window.start_index + offset;
3131
+ var node = ui.listItem(.{}, ui.fmt("Item {d}", .{index}));
3132
+ node.key = .{ .int = @intCast(index) };
3133
+ row.* = node;
3134
+ }
3135
+ return ui.virtualList(options, window, .{rows});
3136
+ }
3137
+
3138
+ fn virtualFeedAppOptions() VirtualFeedApp.Options {
3139
+ return .{
3140
+ .name = "ui-app-virtual-feed",
3141
+ .scene = counter_scene,
3142
+ .canvas_label = canvas_label,
3143
+ .update = virtualFeedUpdate,
3144
+ .view = virtualFeedView,
3145
+ };
3146
+ }
3147
+
3148
+ test "windowed virtual list scrolls, re-windows, budgets to the viewport, and fires reach-end with hysteresis" {
3149
+ const harness = try core.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(400, 300) });
3150
+ defer harness.destroy(std.testing.allocator);
3151
+ harness.null_platform.gpu_surfaces = true;
3152
+
3153
+ const app_state = try std.testing.allocator.create(VirtualFeedApp);
3154
+ defer std.testing.allocator.destroy(app_state);
3155
+ app_state.* = VirtualFeedApp.init(std.heap.page_allocator, .{}, virtualFeedAppOptions());
3156
+ defer app_state.deinit();
3157
+ const app = app_state.app();
3158
+ try harness.start(app);
3159
+
3160
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_frame = .{
3161
+ .label = canvas_label,
3162
+ .size = geometry.SizeF.init(400, 300),
3163
+ .scale_factor = 2,
3164
+ .frame_index = 1,
3165
+ .timestamp_ns = 1_000_000,
3166
+ .nonblank = true,
3167
+ } });
3168
+ try std.testing.expect(app_state.installed);
3169
+
3170
+ // The first build materialized only the first window (300pt viewport
3171
+ // at 24pt rows + 2 overscan = 15 rows), never the 400 loaded items.
3172
+ const list_id = canvas.globalWidgetId(.scroll_view, .{ .str = "vfeed" });
3173
+ try std.testing.expectEqual(list_id, app_state.tree.?.root.id);
3174
+ try std.testing.expectEqual(@as(usize, 15), app_state.tree.?.root.children.len);
3175
+ try std.testing.expectEqual(@as(usize, 0), app_state.tree.?.root.layout.virtual_first_index);
3176
+
3177
+ // A wheel scroll with NO on_scroll binding still re-windows the
3178
+ // view: the runtime owns the offset, the scroll observation itself
3179
+ // triggers the re-derivation.
3180
+ var command_buffer: [96]u8 = undefined;
3181
+ var wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 240", .{ canvas_label, list_id });
3182
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3183
+ try std.testing.expectEqual(@as(usize, 8), app_state.tree.?.root.layout.virtual_first_index);
3184
+ try std.testing.expect(findIn(app_state.tree.?.root, .list_item, "Item 8") != null);
3185
+ try std.testing.expect(findIn(app_state.tree.?.root, .list_item, "Item 0") == null);
3186
+ const retained = try harness.runtime.canvasWidgetLayout(1, canvas_label);
3187
+ try std.testing.expectEqual(@as(f32, 240), retained.findById(list_id).?.widget.value);
3188
+
3189
+ // Row identity is the item, not the slot: item 10 was in both
3190
+ // windows and kept its structural id across the shift.
3191
+ // (The id is derived from the list id and the item key alone.)
3192
+ try std.testing.expect(findIn(app_state.tree.?.root, .list_item, "Item 10") != null);
3193
+
3194
+ // Scroll to the end of the loaded 400 items (content 9600, viewport
3195
+ // 300, max offset 9300): the approach-end signal fires ONCE and the
3196
+ // model appends a batch.
3197
+ try std.testing.expectEqual(@as(u32, 0), app_state.model.fetches);
3198
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 9060", .{ canvas_label, list_id });
3199
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3200
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.fetches);
3201
+ try std.testing.expectEqual(@as(usize, 500), app_state.model.loaded);
3202
+
3203
+ // The appended batch grew the extent (12_000), pulling the offset
3204
+ // out of the band — the next small scroll re-arms, no fire.
3205
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 24", .{ canvas_label, list_id });
3206
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3207
+ try std.testing.expectEqual(@as(u32, 1), app_state.model.fetches);
3208
+
3209
+ // Ride to the new end: fires again (offset 9324 + 2376 = 11_700 =
3210
+ // the new max), appends to the 600 cap.
3211
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 2376", .{ canvas_label, list_id });
3212
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3213
+ try std.testing.expectEqual(@as(u32, 2), app_state.model.fetches);
3214
+ try std.testing.expectEqual(@as(usize, 600), app_state.model.loaded);
3215
+
3216
+ // At the cap the model stops appending, so the extent stops
3217
+ // growing — riding the end must NOT dispatch a fetch storm.
3218
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 24", .{ canvas_label, list_id });
3219
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3220
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 2376", .{ canvas_label, list_id });
3221
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3222
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.fetches);
3223
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} -24", .{ canvas_label, list_id });
3224
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3225
+ wheel = try std.fmt.bufPrint(&command_buffer, "widget-wheel {s} {d} 24", .{ canvas_label, list_id });
3226
+ try harness.runtime.dispatchAutomationCommand(app, wheel);
3227
+ try std.testing.expectEqual(@as(u32, 3), app_state.model.fetches);
3228
+
3229
+ // Budget stays viewport-sized throughout: ~19 mounted rows against
3230
+ // 600 loaded items, and the scroll semantics report the full extent.
3231
+ const final_layout = try harness.runtime.canvasWidgetLayout(1, canvas_label);
3232
+ try std.testing.expect(final_layout.nodes.len < 40);
3233
+ const scroll_state = harness.runtime.views[0].canvasWidgetScrollStateById(list_id).?;
3234
+ try std.testing.expectEqual(@as(f32, 600 * virtual_row_extent), scroll_state.content_extent);
3235
+
3236
+ // A window-growing resize converges within ONE rebuild: the first
3237
+ // build pass reads the stale 300pt viewport, the coverage check sees
3238
+ // the fresh 600pt geometry under-covered, and the retry pass builds
3239
+ // the wider window against it.
3240
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_resized = .{
3241
+ .window_id = 1,
3242
+ .label = canvas_label,
3243
+ .frame = geometry.RectF.init(0, 0, 400, 600),
3244
+ .scale_factor = 2,
3245
+ } });
3246
+ const root = app_state.tree.?.root;
3247
+ const first_index = root.layout.virtual_first_index;
3248
+ const mounted = root.children.len;
3249
+ // Offset clamps to the new max (14_400 - 600 = 13_800): visible rows
3250
+ // 575..600 must all be inside the built window.
3251
+ try std.testing.expect(first_index <= 575);
3252
+ try std.testing.expectEqual(@as(usize, 600), first_index + mounted);
3253
+ try std.testing.expect(mounted >= 25);
3254
+ }