@native-sdk/cli 0.0.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +50 -1
  3. package/app.zon +30 -0
  4. package/bin/native.js +156 -0
  5. package/build/app.zig +716 -0
  6. package/build.zig +2593 -0
  7. package/build.zig.zon +24 -0
  8. package/native-sdk.d.ts +615 -0
  9. package/package.json +44 -8
  10. package/skill-data/automation/SKILL.md +248 -0
  11. package/skill-data/core/SKILL.md +249 -0
  12. package/skill-data/core/references/app-model-runtime.md +141 -0
  13. package/skill-data/core/references/bridge-security-native-capabilities.md +230 -0
  14. package/skill-data/core/references/frontend-assets.md +124 -0
  15. package/skill-data/core/references/project-anatomy.md +108 -0
  16. package/skill-data/core/references/web-engines-packaging-debugging.md +199 -0
  17. package/skill-data/native-ui/SKILL.md +1080 -0
  18. package/skills/native-sdk/SKILL.md +33 -0
  19. package/src/app_runner/root.zig +740 -0
  20. package/src/assets/root.zig +20 -0
  21. package/src/automation/protocol.zig +285 -0
  22. package/src/automation/root.zig +13 -0
  23. package/src/automation/server.zig +506 -0
  24. package/src/automation/snapshot.zig +1202 -0
  25. package/src/automation/watcher.zig +165 -0
  26. package/src/bridge/root.zig +507 -0
  27. package/src/debug/root.zig +246 -0
  28. package/src/embed/app_exports.zig +11 -0
  29. package/src/embed/c_api.zig +793 -0
  30. package/src/embed/c_exports.zig +10 -0
  31. package/src/embed/chrome.zig +168 -0
  32. package/src/embed/conversions.zig +359 -0
  33. package/src/embed/host.zig +960 -0
  34. package/src/embed/root.zig +81 -0
  35. package/src/embed/tests.zig +2552 -0
  36. package/src/embed/types.zig +382 -0
  37. package/src/embed/ui_host.zig +289 -0
  38. package/src/extensions/root.zig +197 -0
  39. package/src/frontend/root.zig +48 -0
  40. package/src/js/root.zig +65 -0
  41. package/src/platform/android/NativeSdkActivity.java +1370 -0
  42. package/src/platform/android/android_host.c +696 -0
  43. package/src/platform/android/files.zig +9 -0
  44. package/src/platform/android/native_sdk_app.h +237 -0
  45. package/src/platform/ios/files.zig +8 -0
  46. package/src/platform/ios/native_sdk_app.h +289 -0
  47. package/src/platform/ios/uikit_host.m +2739 -0
  48. package/src/platform/linux/cef_host.cpp +599 -0
  49. package/src/platform/linux/gtk_host.c +5362 -0
  50. package/src/platform/linux/gtk_host.h +265 -0
  51. package/src/platform/linux/root.zig +1519 -0
  52. package/src/platform/macos/appkit_host.h +604 -0
  53. package/src/platform/macos/appkit_host.m +10392 -0
  54. package/src/platform/macos/automation_host.h +14 -0
  55. package/src/platform/macos/automation_host.m +12 -0
  56. package/src/platform/macos/cef_host.mm +3028 -0
  57. package/src/platform/macos/root.zig +2260 -0
  58. package/src/platform/null_platform.zig +2232 -0
  59. package/src/platform/null_platform_tests.zig +670 -0
  60. package/src/platform/policy_values.zig +14 -0
  61. package/src/platform/root.zig +181 -0
  62. package/src/platform/types.zig +2681 -0
  63. package/src/platform/windows/cef_host.cpp +3 -0
  64. package/src/platform/windows/root.zig +1521 -0
  65. package/src/platform/windows/webview2_host.cpp +6230 -0
  66. package/src/primitives/app_dirs/root.zig +440 -0
  67. package/src/primitives/app_manifest/root.zig +109 -0
  68. package/src/primitives/app_manifest/tests.zig +758 -0
  69. package/src/primitives/app_manifest/types.zig +587 -0
  70. package/src/primitives/app_manifest/validation.zig +828 -0
  71. package/src/primitives/assets/root.zig +520 -0
  72. package/src/primitives/canvas/a11y_audit.zig +390 -0
  73. package/src/primitives/canvas/a11y_audit_tests.zig +225 -0
  74. package/src/primitives/canvas/app_icon.zig +1590 -0
  75. package/src/primitives/canvas/chart.zig +392 -0
  76. package/src/primitives/canvas/chart_tests.zig +751 -0
  77. package/src/primitives/canvas/commands.zig +446 -0
  78. package/src/primitives/canvas/drawing.zig +309 -0
  79. package/src/primitives/canvas/equality.zig +316 -0
  80. package/src/primitives/canvas/events.zig +696 -0
  81. package/src/primitives/canvas/font_coverage.zig +118 -0
  82. package/src/primitives/canvas/font_ttf.zig +510 -0
  83. package/src/primitives/canvas/font_ttf_tests.zig +280 -0
  84. package/src/primitives/canvas/fonts/Geist-Regular.ttf +0 -0
  85. package/src/primitives/canvas/fonts/GeistMono-Regular.ttf +0 -0
  86. package/src/primitives/canvas/frame.zig +679 -0
  87. package/src/primitives/canvas/frame_metrics.zig +462 -0
  88. package/src/primitives/canvas/gpu.zig +639 -0
  89. package/src/primitives/canvas/hash.zig +112 -0
  90. package/src/primitives/canvas/icons/alert.svg +1 -0
  91. package/src/primitives/canvas/icons/archive.svg +1 -0
  92. package/src/primitives/canvas/icons/arrow-down.svg +1 -0
  93. package/src/primitives/canvas/icons/arrow-right.svg +1 -0
  94. package/src/primitives/canvas/icons/arrow-up.svg +1 -0
  95. package/src/primitives/canvas/icons/check-circle.svg +1 -0
  96. package/src/primitives/canvas/icons/check.svg +1 -0
  97. package/src/primitives/canvas/icons/chevron-down.svg +1 -0
  98. package/src/primitives/canvas/icons/chevron-left.svg +1 -0
  99. package/src/primitives/canvas/icons/chevron-right.svg +1 -0
  100. package/src/primitives/canvas/icons/chevron-up.svg +1 -0
  101. package/src/primitives/canvas/icons/circle-dot.svg +1 -0
  102. package/src/primitives/canvas/icons/clock.svg +1 -0
  103. package/src/primitives/canvas/icons/copy.svg +1 -0
  104. package/src/primitives/canvas/icons/download.svg +1 -0
  105. package/src/primitives/canvas/icons/edit.svg +1 -0
  106. package/src/primitives/canvas/icons/ellipsis.svg +1 -0
  107. package/src/primitives/canvas/icons/external-link.svg +1 -0
  108. package/src/primitives/canvas/icons/eye.svg +1 -0
  109. package/src/primitives/canvas/icons/file-text.svg +1 -0
  110. package/src/primitives/canvas/icons/folder-open.svg +1 -0
  111. package/src/primitives/canvas/icons/folder.svg +1 -0
  112. package/src/primitives/canvas/icons/git-branch.svg +1 -0
  113. package/src/primitives/canvas/icons/git-merge.svg +1 -0
  114. package/src/primitives/canvas/icons/git-pull-request.svg +1 -0
  115. package/src/primitives/canvas/icons/info.svg +1 -0
  116. package/src/primitives/canvas/icons/menu.svg +1 -0
  117. package/src/primitives/canvas/icons/missing.svg +1 -0
  118. package/src/primitives/canvas/icons/moon.svg +1 -0
  119. package/src/primitives/canvas/icons/music.svg +1 -0
  120. package/src/primitives/canvas/icons/panel-left.svg +1 -0
  121. package/src/primitives/canvas/icons/panel-right.svg +1 -0
  122. package/src/primitives/canvas/icons/pause.svg +1 -0
  123. package/src/primitives/canvas/icons/play.svg +1 -0
  124. package/src/primitives/canvas/icons/plus.svg +1 -0
  125. package/src/primitives/canvas/icons/refresh-cw.svg +1 -0
  126. package/src/primitives/canvas/icons/repeat.svg +1 -0
  127. package/src/primitives/canvas/icons/save.svg +1 -0
  128. package/src/primitives/canvas/icons/search.svg +1 -0
  129. package/src/primitives/canvas/icons/send.svg +1 -0
  130. package/src/primitives/canvas/icons/settings.svg +1 -0
  131. package/src/primitives/canvas/icons/shuffle.svg +1 -0
  132. package/src/primitives/canvas/icons/skip-back.svg +1 -0
  133. package/src/primitives/canvas/icons/skip-forward.svg +1 -0
  134. package/src/primitives/canvas/icons/sun.svg +1 -0
  135. package/src/primitives/canvas/icons/terminal.svg +1 -0
  136. package/src/primitives/canvas/icons/trash.svg +1 -0
  137. package/src/primitives/canvas/icons/volume.svg +1 -0
  138. package/src/primitives/canvas/icons/wrench.svg +1 -0
  139. package/src/primitives/canvas/icons/x-circle.svg +1 -0
  140. package/src/primitives/canvas/icons/x.svg +1 -0
  141. package/src/primitives/canvas/icons.zig +249 -0
  142. package/src/primitives/canvas/layout_audit.zig +744 -0
  143. package/src/primitives/canvas/layout_audit_tests.zig +426 -0
  144. package/src/primitives/canvas/markdown.zig +1031 -0
  145. package/src/primitives/canvas/markdown_hostile_tests.zig +471 -0
  146. package/src/primitives/canvas/markdown_tests.zig +538 -0
  147. package/src/primitives/canvas/plan_key_index.zig +120 -0
  148. package/src/primitives/canvas/png.zig +355 -0
  149. package/src/primitives/canvas/reference.zig +1457 -0
  150. package/src/primitives/canvas/reference_blur.zig +104 -0
  151. package/src/primitives/canvas/reference_memo.zig +322 -0
  152. package/src/primitives/canvas/reference_paths.zig +184 -0
  153. package/src/primitives/canvas/reference_tests.zig +1650 -0
  154. package/src/primitives/canvas/render.zig +747 -0
  155. package/src/primitives/canvas/render_effects.zig +255 -0
  156. package/src/primitives/canvas/render_fingerprints.zig +256 -0
  157. package/src/primitives/canvas/render_generic_resources.zig +376 -0
  158. package/src/primitives/canvas/render_images.zig +247 -0
  159. package/src/primitives/canvas/render_layers.zig +260 -0
  160. package/src/primitives/canvas/render_paths.zig +347 -0
  161. package/src/primitives/canvas/render_resources.zig +51 -0
  162. package/src/primitives/canvas/render_tests.zig +3186 -0
  163. package/src/primitives/canvas/root.zig +744 -0
  164. package/src/primitives/canvas/serialization.zig +1528 -0
  165. package/src/primitives/canvas/svg_icon.zig +636 -0
  166. package/src/primitives/canvas/svg_icon_tests.zig +312 -0
  167. package/src/primitives/canvas/test_support.zig +422 -0
  168. package/src/primitives/canvas/testdata/markdown_document.md +83 -0
  169. package/src/primitives/canvas/tests.zig +30 -0
  170. package/src/primitives/canvas/text.zig +82 -0
  171. package/src/primitives/canvas/text_atlas.zig +408 -0
  172. package/src/primitives/canvas/text_batch_tests.zig +431 -0
  173. package/src/primitives/canvas/text_interaction.zig +615 -0
  174. package/src/primitives/canvas/text_layout.zig +1069 -0
  175. package/src/primitives/canvas/text_layout_cache.zig +281 -0
  176. package/src/primitives/canvas/text_layout_hash.zig +113 -0
  177. package/src/primitives/canvas/text_layout_types.zig +128 -0
  178. package/src/primitives/canvas/text_measure_cache.zig +279 -0
  179. package/src/primitives/canvas/text_metrics.zig +309 -0
  180. package/src/primitives/canvas/text_metrics_tests.zig +262 -0
  181. package/src/primitives/canvas/text_span_tests.zig +608 -0
  182. package/src/primitives/canvas/text_spans.zig +1010 -0
  183. package/src/primitives/canvas/text_tests.zig +1949 -0
  184. package/src/primitives/canvas/themes/geist.zig +470 -0
  185. package/src/primitives/canvas/tokens.zig +1522 -0
  186. package/src/primitives/canvas/ui.zig +2686 -0
  187. package/src/primitives/canvas/ui_markup.zig +3791 -0
  188. package/src/primitives/canvas/ui_markup_binary.zig +522 -0
  189. package/src/primitives/canvas/ui_markup_binary_tests.zig +591 -0
  190. package/src/primitives/canvas/ui_markup_compiled.zig +2565 -0
  191. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1669 -0
  192. package/src/primitives/canvas/ui_markup_contract.zig +1620 -0
  193. package/src/primitives/canvas/ui_markup_contract_tests.zig +953 -0
  194. package/src/primitives/canvas/ui_markup_edit.zig +416 -0
  195. package/src/primitives/canvas/ui_markup_edit_tests.zig +341 -0
  196. package/src/primitives/canvas/ui_markup_expr.zig +1152 -0
  197. package/src/primitives/canvas/ui_markup_expr_tests.zig +779 -0
  198. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +505 -0
  199. package/src/primitives/canvas/ui_markup_reflect.zig +127 -0
  200. package/src/primitives/canvas/ui_markup_tests.zig +1545 -0
  201. package/src/primitives/canvas/ui_markup_view.zig +2352 -0
  202. package/src/primitives/canvas/ui_markup_view_tests.zig +3709 -0
  203. package/src/primitives/canvas/ui_provenance.zig +96 -0
  204. package/src/primitives/canvas/ui_provenance_tests.zig +186 -0
  205. package/src/primitives/canvas/ui_schema.zig +825 -0
  206. package/src/primitives/canvas/ui_schema_tests.zig +128 -0
  207. package/src/primitives/canvas/ui_tests.zig +1432 -0
  208. package/src/primitives/canvas/vector.zig +919 -0
  209. package/src/primitives/canvas/vector_tests.zig +547 -0
  210. package/src/primitives/canvas/virtual_extent_tests.zig +317 -0
  211. package/src/primitives/canvas/virtual_extents.zig +540 -0
  212. package/src/primitives/canvas/widget_access.zig +208 -0
  213. package/src/primitives/canvas/widget_anchored_tests.zig +264 -0
  214. package/src/primitives/canvas/widget_builtin_tests.zig +3160 -0
  215. package/src/primitives/canvas/widget_invalidation.zig +748 -0
  216. package/src/primitives/canvas/widget_layout.zig +2055 -0
  217. package/src/primitives/canvas/widget_layout_tests.zig +2691 -0
  218. package/src/primitives/canvas/widget_metrics.zig +228 -0
  219. package/src/primitives/canvas/widget_render.zig +2534 -0
  220. package/src/primitives/canvas/widget_render_controls.zig +1563 -0
  221. package/src/primitives/canvas/widget_render_scroll.zig +136 -0
  222. package/src/primitives/canvas/widget_render_style.zig +626 -0
  223. package/src/primitives/canvas/widget_render_surfaces.zig +794 -0
  224. package/src/primitives/canvas/widget_routing.zig +475 -0
  225. package/src/primitives/canvas/widget_runtime.zig +307 -0
  226. package/src/primitives/canvas/widget_runtime_tests.zig +3015 -0
  227. package/src/primitives/canvas/widget_semantics.zig +480 -0
  228. package/src/primitives/canvas/widget_semantics_tests.zig +2129 -0
  229. package/src/primitives/canvas/widget_tests.zig +8 -0
  230. package/src/primitives/canvas/widget_text_input.zig +351 -0
  231. package/src/primitives/canvas/widget_text_select.zig +147 -0
  232. package/src/primitives/canvas/widget_tree.zig +232 -0
  233. package/src/primitives/canvas/widgets.zig +1319 -0
  234. package/src/primitives/diagnostics/root.zig +445 -0
  235. package/src/primitives/geometry/root.zig +889 -0
  236. package/src/primitives/json/root.zig +272 -0
  237. package/src/primitives/platform_info/root.zig +450 -0
  238. package/src/primitives/trace/root.zig +569 -0
  239. package/src/root.zig +165 -0
  240. package/src/runtime/api.zig +431 -0
  241. package/src/runtime/async_bridge.zig +49 -0
  242. package/src/runtime/automation_commands.zig +686 -0
  243. package/src/runtime/automation_liveness_tests.zig +140 -0
  244. package/src/runtime/automation_snapshot.zig +246 -0
  245. package/src/runtime/automation_widget_dispatch.zig +617 -0
  246. package/src/runtime/bridge_dispatch_tests.zig +202 -0
  247. package/src/runtime/bridge_payload.zig +194 -0
  248. package/src/runtime/bridge_permission_tests.zig +551 -0
  249. package/src/runtime/bridge_responses.zig +414 -0
  250. package/src/runtime/builtin_bridge.zig +554 -0
  251. package/src/runtime/canvas_budget_edge_tests.zig +415 -0
  252. package/src/runtime/canvas_font_tests.zig +410 -0
  253. package/src/runtime/canvas_fonts.zig +229 -0
  254. package/src/runtime/canvas_frame.zig +1734 -0
  255. package/src/runtime/canvas_frame_animation_tests.zig +609 -0
  256. package/src/runtime/canvas_frame_cache_tests.zig +333 -0
  257. package/src/runtime/canvas_frame_helpers.zig +414 -0
  258. package/src/runtime/canvas_frame_invalidation_tests.zig +544 -0
  259. package/src/runtime/canvas_frame_packet_tests.zig +1353 -0
  260. package/src/runtime/canvas_frame_patch_tests.zig +1051 -0
  261. package/src/runtime/canvas_frame_retained_tests.zig +753 -0
  262. package/src/runtime/canvas_frame_tests.zig +9 -0
  263. package/src/runtime/canvas_frame_text_layout_budget_tests.zig +149 -0
  264. package/src/runtime/canvas_image_tests.zig +362 -0
  265. package/src/runtime/canvas_images.zig +224 -0
  266. package/src/runtime/canvas_limits.zig +317 -0
  267. package/src/runtime/canvas_screenshot_tests.zig +289 -0
  268. package/src/runtime/canvas_widget_accessibility_tests.zig +1494 -0
  269. package/src/runtime/canvas_widget_anchored_tests.zig +678 -0
  270. package/src/runtime/canvas_widget_chart_tests.zig +249 -0
  271. package/src/runtime/canvas_widget_clipboard_tests.zig +399 -0
  272. package/src/runtime/canvas_widget_context_menu.zig +318 -0
  273. package/src/runtime/canvas_widget_context_menu_tests.zig +462 -0
  274. package/src/runtime/canvas_widget_control_tests.zig +2164 -0
  275. package/src/runtime/canvas_widget_disclosure_tests.zig +440 -0
  276. package/src/runtime/canvas_widget_display.zig +677 -0
  277. package/src/runtime/canvas_widget_event_tests.zig +1779 -0
  278. package/src/runtime/canvas_widget_events.zig +1098 -0
  279. package/src/runtime/canvas_widget_floating_tests.zig +695 -0
  280. package/src/runtime/canvas_widget_layout_tests.zig +26 -0
  281. package/src/runtime/canvas_widget_runtime.zig +1335 -0
  282. package/src/runtime/canvas_widget_scroll_driver_tests.zig +582 -0
  283. package/src/runtime/canvas_widget_scroll_drivers.zig +202 -0
  284. package/src/runtime/canvas_widget_scroll_tests.zig +1549 -0
  285. package/src/runtime/canvas_widget_semantics_tests.zig +810 -0
  286. package/src/runtime/canvas_widget_split_tree_tests.zig +1031 -0
  287. package/src/runtime/canvas_widget_state.zig +798 -0
  288. package/src/runtime/canvas_widget_text_tests.zig +2104 -0
  289. package/src/runtime/canvas_widget_window_drag_tests.zig +284 -0
  290. package/src/runtime/clock.zig +231 -0
  291. package/src/runtime/core.zig +927 -0
  292. package/src/runtime/effects.zig +4197 -0
  293. package/src/runtime/effects_audio_tests.zig +690 -0
  294. package/src/runtime/effects_clipboard_tests.zig +317 -0
  295. package/src/runtime/effects_fetch_tests.zig +1031 -0
  296. package/src/runtime/effects_file_tests.zig +407 -0
  297. package/src/runtime/effects_tests.zig +1251 -0
  298. package/src/runtime/flow.zig +1175 -0
  299. package/src/runtime/frame_profile.zig +221 -0
  300. package/src/runtime/gpu_surface_events.zig +639 -0
  301. package/src/runtime/launch_timing.zig +59 -0
  302. package/src/runtime/markdown_app_tests.zig +224 -0
  303. package/src/runtime/native_command_event_tests.zig +431 -0
  304. package/src/runtime/platform_bridge_tests.zig +8 -0
  305. package/src/runtime/platform_config_tests.zig +392 -0
  306. package/src/runtime/root.zig +150 -0
  307. package/src/runtime/runtime_event_tests.zig +1079 -0
  308. package/src/runtime/session_journal.zig +1522 -0
  309. package/src/runtime/session_record.zig +332 -0
  310. package/src/runtime/session_replay.zig +274 -0
  311. package/src/runtime/session_state.zig +30 -0
  312. package/src/runtime/session_tests.zig +399 -0
  313. package/src/runtime/shell_layout.zig +472 -0
  314. package/src/runtime/shell_layout_tests.zig +1246 -0
  315. package/src/runtime/shell_view_tests.zig +604 -0
  316. package/src/runtime/state.zig +110 -0
  317. package/src/runtime/system_services.zig +392 -0
  318. package/src/runtime/test_support.zig +79 -0
  319. package/src/runtime/tests.zig +30 -0
  320. package/src/runtime/ui_app.zig +3290 -0
  321. package/src/runtime/ui_app_huge_model_tests.zig +351 -0
  322. package/src/runtime/ui_app_provenance.zig +370 -0
  323. package/src/runtime/ui_app_tests.zig +3254 -0
  324. package/src/runtime/ui_app_virtual_variable_tests.zig +485 -0
  325. package/src/runtime/ui_app_window_tests.zig +442 -0
  326. package/src/runtime/validation.zig +206 -0
  327. package/src/runtime/view.zig +908 -0
  328. package/src/runtime/view_canvas.zig +850 -0
  329. package/src/runtime/view_widget_control.zig +433 -0
  330. package/src/runtime/view_widget_scroll.zig +360 -0
  331. package/src/runtime/view_widget_text.zig +275 -0
  332. package/src/runtime/view_widget_tree.zig +843 -0
  333. package/src/runtime/webview_view_bridge_tests.zig +664 -0
  334. package/src/runtime/widget_bridge.zig +231 -0
  335. package/src/runtime/window_command_bridge_tests.zig +403 -0
  336. package/src/runtime/window_storage.zig +255 -0
  337. package/src/runtime/window_view_runtime.zig +727 -0
  338. package/src/runtime/window_views.zig +334 -0
  339. package/src/security/root.zig +118 -0
  340. package/src/tooling/android.zig +1172 -0
  341. package/src/tooling/assets.zig +128 -0
  342. package/src/tooling/buildgraph.zig +379 -0
  343. package/src/tooling/cef.zig +671 -0
  344. package/src/tooling/codesign.zig +172 -0
  345. package/src/tooling/components/identity_tests.zig +185 -0
  346. package/src/tooling/components/stepper.zig +113 -0
  347. package/src/tooling/components/timeline.native +27 -0
  348. package/src/tooling/components/timeline_item.zig +131 -0
  349. package/src/tooling/default_icon.icns +0 -0
  350. package/src/tooling/default_icon.png +0 -0
  351. package/src/tooling/dev.zig +172 -0
  352. package/src/tooling/doctor.zig +349 -0
  353. package/src/tooling/eject_components.zig +170 -0
  354. package/src/tooling/embedlib.zig +290 -0
  355. package/src/tooling/ios.zig +528 -0
  356. package/src/tooling/manifest.zig +1939 -0
  357. package/src/tooling/package.zig +2388 -0
  358. package/src/tooling/process_tree.zig +114 -0
  359. package/src/tooling/raw_manifest.zig +193 -0
  360. package/src/tooling/root.zig +22 -0
  361. package/src/tooling/templates.zig +3191 -0
  362. package/src/tooling/toolchain.zig +371 -0
  363. package/src/tooling/verbs.zig +204 -0
  364. package/src/tooling/web_engine.zig +135 -0
  365. package/src/tooling/xcodeproj.zig +462 -0
  366. package/src/window_state/root.zig +507 -0
  367. package/index.js +0 -2
@@ -0,0 +1,2686 @@
1
+ //! Experimental declarative authoring layer over the retained widget tree.
2
+ //!
3
+ //! `Ui(Msg)` builds widget trees without hand-assigned object ids, absolute
4
+ //! frames, or string command dispatch:
5
+ //!
6
+ //! - Identity is structural: each widget id is derived from its parent id,
7
+ //! kind, and key (explicit in `each`, sibling index otherwise), so ids stay
8
+ //! stable across rebuilds and keyed reorders without author bookkeeping.
9
+ //! Structural identity is parent-scoped: a keyed item that moves to a
10
+ //! different parent gets a new id. Items that migrate between containers
11
+ //! (board columns, tab pages) should set `global_key`, which pins identity
12
+ //! to (kind, key) independent of position in the tree.
13
+ //! - Event handlers are typed `Msg` values collected into a handler table,
14
+ //! so dispatch is compiler-checked instead of string-matched.
15
+ //! - Flex layout fields are the authoring default; `frame` is the escape
16
+ //! hatch for absolutely positioned regions.
17
+ //!
18
+ //! Build failures (arena exhaustion) latch on the builder and surface as an
19
+ //! error from `finalize`, keeping view code free of per-node `try`.
20
+
21
+ const std = @import("std");
22
+ const builtin = @import("builtin");
23
+ const font_coverage = @import("font_coverage.zig");
24
+ const geometry = @import("geometry");
25
+ const canvas = @import("root.zig");
26
+ const ui_provenance = @import("ui_provenance.zig");
27
+
28
+ const ObjectId = canvas.ObjectId;
29
+ const Widget = canvas.Widget;
30
+ const WidgetKind = canvas.WidgetKind;
31
+
32
+ const root_id_seed: u64 = 0x5eed_2e70_a11c_e001;
33
+ const global_id_seed: u64 = 0x5eed_2e70_a11c_e002;
34
+ const zero_id_fallback: ObjectId = 0x9e37_79b9_7f4a_7c15;
35
+
36
+ const ui_log = std.log.scoped(.zero_canvas_ui);
37
+
38
+ /// Debug-build diagnostic for `gap` on a stacking container: these kinds
39
+ /// give every child the full content box (`widget_layout.zig` routes them
40
+ /// through `stackChildFrame`), so the gap silently does nothing and the
41
+ /// children land on top of each other. Warn and keep building — shipped
42
+ /// apps already carry the mistake, so it must never fail the build.
43
+ /// Markup views get the same lesson as a validation/compile error
44
+ /// (`ui_markup.stack_container_gap_message`).
45
+ fn warnStackContainerGap(kind: WidgetKind, gap: f32) void {
46
+ if (builtin.mode != .Debug) return;
47
+ if (gap == 0 or !canvas.widgetKindStacksChildren(kind)) return;
48
+ ui_log.warn(
49
+ "gap does nothing on {s}: this container layers its children on top of each other - wrap them in a column (or row) inside it for flow, or drop the gap",
50
+ .{@tagName(kind)},
51
+ );
52
+ }
53
+
54
+ /// Debug-build diagnostic for a set `wrap` on anything but a plain text
55
+ /// leaf. `ElementOptions.wrap` is text-leaf line policy only — rows and
56
+ /// columns never flow-wrap their children (that is the layout system's
57
+ /// design: one axis, no reflow), so the option on a container is silently
58
+ /// inert and has shipped with comments asserting wrapping that never
59
+ /// happened. Warn and keep building — shipped
60
+ /// apps already carry the mistake, so it must never fail the build.
61
+ /// Markup views get the same lesson as a validation error
62
+ /// (`ui_markup.wrap_element_message`).
63
+ fn warnInertWrap(kind: WidgetKind, wrap: ?bool) void {
64
+ if (builtin.mode != .Debug) return;
65
+ if (wrap == null) return;
66
+ // Plain text leaves wrap for real; span paragraphs already wrap by
67
+ // design, so the option is redundant there, not a trap.
68
+ if (kind == .text) return;
69
+ ui_log.warn(
70
+ "wrap does nothing on {s}: only plain text leaves take a line policy - put wrap on the text leaf itself, or size the container so content fits (rows and columns never flow-wrap)",
71
+ .{@tagName(kind)},
72
+ );
73
+ }
74
+
75
+ /// Debug-build diagnostic for the typography rungs of the size register
76
+ /// (`heading`/`display`) on a widget kind that never reads them: only
77
+ /// `.text` leaves resolve those steps to the heading/display typography
78
+ /// tokens, so anywhere else the option is dead data rendered at the
79
+ /// default control step. Zig views warn instead of failing (the option
80
+ /// is inert, not harmful); markup views get the same lesson as a
81
+ /// validation/compile error (`ui_markup.text_size_element_message`).
82
+ fn warnTextSizeKind(kind: WidgetKind, size: canvas.WidgetSize) void {
83
+ if (builtin.mode != .Debug) return;
84
+ if (kind == .text) return;
85
+ if (size != .heading and size != .display) return;
86
+ ui_log.warn(
87
+ "size .{s} does nothing on {s}: heading and display are typography rungs only text leaves resolve - put the size on the text leaf itself, or use the control scale (sm, lg, icon)",
88
+ .{ @tagName(size), @tagName(kind) },
89
+ );
90
+ }
91
+
92
+ /// Debug-build diagnostic for text the bundled face cannot fully
93
+ /// render: the codepoint draws as a tofu box wherever the bundled
94
+ /// outlines are the only glyph source — reference screenshots
95
+ /// (`automate screenshot`), mobile embeds, provider-less measurement.
96
+ /// Markup literals get the same lesson as a validation error; this
97
+ /// diagnostic is the net for DYNAMIC strings (model-derived text
98
+ /// reaches no static check) and Zig-authored literals. Logs the first
99
+ /// uncovered codepoint per text run and keeps building — live macOS
100
+ /// rendering falls back through CoreText, so this must never fail an
101
+ /// app, and it logs at .debug (the `logAxisChildrenOverflow`
102
+ /// precedent) because a .warn inside a test-built view would fail the
103
+ /// whole suite for a rendering nit.
104
+ fn warnUncoveredText(kind: WidgetKind, text: []const u8) void {
105
+ if (builtin.mode != .Debug) return;
106
+ var index: usize = 0;
107
+ while (index < text.len) {
108
+ const len = std.unicode.utf8ByteSequenceLength(text[index]) catch return;
109
+ if (index + len > text.len) return;
110
+ const codepoint = std.unicode.utf8Decode(text[index .. index + len]) catch return;
111
+ if (codepoint >= 0x20 and codepoint != 0x7F and !font_coverage.covers(codepoint)) {
112
+ ui_log.debug(
113
+ "{s} text contains \"{s}\" (U+{X:0>4}), outside the bundled font's coverage - it renders as a tofu box on the reference/screenshot and mobile paths; use a vector icon (icon option, <icon name>) or plain words",
114
+ .{ @tagName(kind), text[index .. index + len], codepoint },
115
+ );
116
+ return;
117
+ }
118
+ index += len;
119
+ }
120
+ }
121
+
122
+ /// Debug-build diagnostic for an explicit icon name that resolves
123
+ /// nowhere — a bound markup name the model produced, an `app:` reference
124
+ /// the app never registered, a Zig `appIcon` typo. The draw path renders
125
+ /// the missing-icon fallback (a slashed circle) in its place, so the
126
+ /// break is VISIBLE; this warning is the other half of that honesty,
127
+ /// naming the value so the fix is one glance. Warn and keep building
128
+ /// (the shipped-app rule); literal markup names were already proven at
129
+ /// build time and never reach here.
130
+ fn warnUnknownIconName(name: []const u8) void {
131
+ if (builtin.mode != .Debug) return;
132
+ if (name.len == 0 or canvas.icons.resolve(name) != null) return;
133
+ ui_log.warn(
134
+ "unknown icon \"{s}\": not a built-in (canvas.icons.known_icon_names) and not registered via canvas.icons.registerAppIcons - the missing-icon fallback (a slashed circle) draws in its place",
135
+ .{name},
136
+ );
137
+ }
138
+
139
+ /// Debug-build diagnostic for `on_dismiss` on a kind the runtime's
140
+ /// dismissal machinery never closes: the handler would sit dead. The
141
+ /// markup validator teaches the same rule as a hard error; the builder
142
+ /// warns and keeps building (the shipped-app rule).
143
+ fn warnDismissHandlerKind(kind: WidgetKind) void {
144
+ if (builtin.mode != .Debug) return;
145
+ if (canvas.widgetKindDismissibleSurface(kind)) return;
146
+ ui_log.warn(
147
+ "on_dismiss never fires on {s}: only dismissible surfaces (dialog, drawer, sheet, popover, menu_surface, dropdown_menu) are closed by Escape/click-outside - put it on the surface element",
148
+ .{@tagName(kind)},
149
+ );
150
+ }
151
+
152
+ /// Debug-build diagnostic for `on_resize` on a kind the runtime never
153
+ /// resizes: only `split` containers dispatch fraction changes, so the
154
+ /// handler would sit dead anywhere else. The markup validator teaches
155
+ /// the same rule as a hard error; the builder warns and keeps building
156
+ /// (the shipped-app rule).
157
+ fn warnResizeHandlerKind(kind: WidgetKind) void {
158
+ if (builtin.mode != .Debug) return;
159
+ if (kind == .split) return;
160
+ ui_log.warn(
161
+ "on_resize never fires on {s}: only split containers dispatch fraction changes - put it on the split element",
162
+ .{@tagName(kind)},
163
+ );
164
+ }
165
+
166
+ pub const UiKey = union(enum) {
167
+ index: usize,
168
+ int: u64,
169
+ str: []const u8,
170
+ };
171
+
172
+ /// Budget for windowed virtual lists per view build (`Ui.virtualList`):
173
+ /// each records its request so the app loop can verify window coverage
174
+ /// after layout and re-derive the view when the runtime scrolls it.
175
+ pub const max_virtual_windows: usize = 8;
176
+
177
+ /// Runtime scroll state for one windowed virtual list, resolved by the
178
+ /// window source during a view build: the CURRENT offset of record
179
+ /// (`widget.value` on the retained node — wheel, kinetic, keyboard, and
180
+ /// native-driver motion all land there) and the content viewport height
181
+ /// the list most recently laid out at.
182
+ pub const VirtualWindowState = struct {
183
+ offset: f32 = 0,
184
+ viewport_extent: f32 = 0,
185
+ /// Whether the offset comes from a MOUNTED list's retained state
186
+ /// (false: a fallback the source synthesized for a list it has no
187
+ /// layout for yet). Uniform windows ignore it; the trailing anchor
188
+ /// needs it to tell "first build" (open at the bottom) from "the
189
+ /// user scrolled to offset 0" (stay at the top).
190
+ mounted: bool = false,
191
+ };
192
+
193
+ /// The window source seam: installed on the `Ui` by the app loop before
194
+ /// each view build (`UiApp` backs it with the retained widget layout),
195
+ /// consulted by `Ui.virtualWindow` per list identity. Returning null
196
+ /// means "no runtime state yet" (first build, list not mounted) and
197
+ /// falls back to offset 0 at the request's fallback viewport.
198
+ pub const VirtualWindowSourceFn = *const fn (context: ?*anyopaque, id: ObjectId) ?VirtualWindowState;
199
+
200
+ /// The extent-table seam of VARIABLE-extent virtual lists: installed by
201
+ /// the app loop next to the window source, it resolves the RETAINED
202
+ /// offset table (estimate prefix sums patched by measured actuals) for
203
+ /// a list identity — the state that makes scrollbar geometry converge
204
+ /// to truth as the user scrolls. Returning null (no source installed,
205
+ /// or the app loop's table budget — one per declarable window — is
206
+ /// exhausted) drops the build to stateless estimate-only math: still
207
+ /// correct within the window, just without cross-frame corrections.
208
+ pub const VirtualExtentSourceFn = *const fn (context: ?*anyopaque, id: ObjectId) ?*canvas.VirtualExtentTable;
209
+
210
+ /// A markup fragment build failure surfaced through the hot-reload seam:
211
+ /// the same file:line teaching shape the single-root markup watch reports,
212
+ /// so a fragment that reloads into a bad binding degrades identically.
213
+ pub const MarkupFragmentDiagnostic = struct {
214
+ line: usize = 0,
215
+ column: usize = 0,
216
+ message: []const u8 = "",
217
+ /// Source file the position refers to; import resolution stamps it so
218
+ /// errors inside imported component files name the right file.
219
+ path: []const u8 = "",
220
+ };
221
+
222
+ /// The app loop's side of the fragment hot-reload seam (Debug dev runs
223
+ /// only). `override` answers a compiled fragment's identity key with the
224
+ /// watch's reloaded document (`*const ui_markup.MarkupDocument` as
225
+ /// `anyopaque` — the engine casts it back; the builder core stays free of
226
+ /// markup imports), or null while the fragment matches its compiled
227
+ /// baseline. `report` carries a reloaded-but-unbuildable fragment's
228
+ /// teaching diagnostic back to the app loop's markup diagnostic channel.
229
+ pub const MarkupFragmentHost = struct {
230
+ context: *anyopaque,
231
+ override: *const fn (context: *anyopaque, key: *const anyopaque) ?*const anyopaque,
232
+ report: *const fn (context: *anyopaque, diagnostic: MarkupFragmentDiagnostic) void,
233
+ };
234
+
235
+ /// One windowed virtual list the current build declared: enough for the
236
+ /// app loop to re-check the window against the freshly laid-out
237
+ /// geometry (a resize or first build can widen the viewport after the
238
+ /// window was computed) and to know which scroll regions require a
239
+ /// view re-derivation when the runtime scrolls them.
240
+ pub const VirtualWindowRecord = struct {
241
+ id: ObjectId = 0,
242
+ item_count: usize = 0,
243
+ item_extent: f32 = 0,
244
+ gap: f32 = 0,
245
+ overscan: usize = 0,
246
+ start_index: usize = 0,
247
+ end_index: usize = 0,
248
+ /// VARIABLE-extent list: the app loop measures this window's
249
+ /// mounted rows after layout and patches the retained offset table
250
+ /// (anchored, so corrections never move visible content).
251
+ variable: bool = false,
252
+ /// Logical index of physical item 0 at build time (prepend-stable
253
+ /// identity for the measure step).
254
+ index_base: u64 = 0,
255
+ };
256
+
257
+ pub const UiHandlerEvent = enum {
258
+ press,
259
+ /// A multi-click press (click_count >= 2 on the release): the
260
+ /// double-click channel. Resolution lives in `msgForPointerClick`:
261
+ /// a double-click release prefers this handler and falls back to
262
+ /// `.press`, so binding it is strictly additive — the first click
263
+ /// of every double-click still dispatches the single-press message
264
+ /// (select, then open/play), the way list selection conventions
265
+ /// expect.
266
+ double_press,
267
+ toggle,
268
+ change,
269
+ submit,
270
+ input,
271
+ scroll,
272
+ context_menu,
273
+ dismiss,
274
+ hold,
275
+ /// Split-fraction changes (divider drag, keyboard adjustment,
276
+ /// assistive increment/decrement), dispatched with the fraction the
277
+ /// runtime already applied — echoing it back into `value` never
278
+ /// fights the split reconcile rule.
279
+ resize,
280
+ /// Approach-the-end of a scroll region (infinite-scroll fetch):
281
+ /// dispatched by the runtime with hysteresis when a user scroll
282
+ /// brings the offset within one viewport of the content end, and
283
+ /// re-armed once the offset retreats past one and a half viewports
284
+ /// (appending items grows the extent, so a fresh batch re-arms the
285
+ /// next approach on its own).
286
+ reach_end,
287
+ /// Approach-the-start counterpart (load-older-history for
288
+ /// tail-anchored transcripts): dispatched with the same hysteresis
289
+ /// when a user scroll brings the offset within one viewport of the
290
+ /// content START, re-armed past one and a half viewports — which
291
+ /// prepending a batch causes on its own, since the offset grows by
292
+ /// the prepended extent to keep the viewport anchored.
293
+ reach_start,
294
+ };
295
+
296
+ /// A color design token referenced by name (the fields of
297
+ /// `canvas.ColorTokens`). Markup style attributes (`background="surface"`)
298
+ /// parse into these; `finalizeWithTokens` resolves them against live
299
+ /// tokens, so themed apps re-resolve on retheme rebuilds.
300
+ pub const ColorTokenName = std.meta.FieldEnum(canvas.ColorTokens);
301
+
302
+ /// A radius design token referenced by name (the fields of
303
+ /// `canvas.RadiusTokens`).
304
+ pub const RadiusTokenName = std.meta.FieldEnum(canvas.RadiusTokens);
305
+
306
+ /// Token references for the style a widget should resolve at finalize
307
+ /// time. Each maps to the matching `WidgetStyle` field and only applies
308
+ /// when the author has not already set that field explicitly
309
+ /// (`border_color` maps to `WidgetStyle.border`; the markup attribute is
310
+ /// `border-color`, keeping bare `border` free for a future width
311
+ /// shorthand).
312
+ pub const StyleTokenRefs = struct {
313
+ background: ?ColorTokenName = null,
314
+ foreground: ?ColorTokenName = null,
315
+ accent: ?ColorTokenName = null,
316
+ accent_foreground: ?ColorTokenName = null,
317
+ border_color: ?ColorTokenName = null,
318
+ focus_ring: ?ColorTokenName = null,
319
+ radius: ?RadiusTokenName = null,
320
+ };
321
+
322
+ fn colorTokenValue(colors: canvas.ColorTokens, ref: ColorTokenName) canvas.Color {
323
+ return switch (ref) {
324
+ inline else => |tag| @field(colors, @tagName(tag)),
325
+ };
326
+ }
327
+
328
+ fn radiusTokenValue(radius: canvas.RadiusTokens, ref: RadiusTokenName) f32 {
329
+ return switch (ref) {
330
+ inline else => |tag| @field(radius, @tagName(tag)),
331
+ };
332
+ }
333
+
334
+ /// Resolve token references into concrete style values, keeping any style
335
+ /// field the author already set explicitly.
336
+ fn applyStyleTokens(style: *canvas.WidgetStyle, refs: StyleTokenRefs, tokens: *const canvas.DesignTokens) void {
337
+ if (refs.background) |ref| {
338
+ if (style.background == null) style.background = colorTokenValue(tokens.colors, ref);
339
+ }
340
+ if (refs.foreground) |ref| {
341
+ if (style.foreground == null) style.foreground = colorTokenValue(tokens.colors, ref);
342
+ }
343
+ if (refs.accent) |ref| {
344
+ if (style.accent == null) style.accent = colorTokenValue(tokens.colors, ref);
345
+ }
346
+ if (refs.accent_foreground) |ref| {
347
+ if (style.accent_foreground == null) style.accent_foreground = colorTokenValue(tokens.colors, ref);
348
+ }
349
+ if (refs.border_color) |ref| {
350
+ if (style.border == null) style.border = colorTokenValue(tokens.colors, ref);
351
+ }
352
+ if (refs.focus_ring) |ref| {
353
+ if (style.focus_ring == null) style.focus_ring = colorTokenValue(tokens.colors, ref);
354
+ }
355
+ if (refs.radius) |ref| {
356
+ if (style.radius == null) style.radius = radiusTokenValue(tokens.radius, ref);
357
+ }
358
+ }
359
+
360
+ pub fn Ui(comptime Msg: type) type {
361
+ return struct {
362
+ const Self = @This();
363
+
364
+ arena: std.mem.Allocator,
365
+ failed: bool = false,
366
+ /// Window source for `virtualWindow` (see `VirtualWindowSourceFn`):
367
+ /// null outside an app loop, where builds fall back to each
368
+ /// request's `viewport_fallback` at offset 0.
369
+ virtual_window_context: ?*anyopaque = null,
370
+ virtual_window_source: ?VirtualWindowSourceFn = null,
371
+ /// Extent-table source for VARIABLE-extent virtual lists (see
372
+ /// `VirtualExtentSourceFn`): null outside an app loop, where
373
+ /// variable windows compute from estimates alone.
374
+ virtual_extent_context: ?*anyopaque = null,
375
+ virtual_extent_source: ?VirtualExtentSourceFn = null,
376
+ /// The windowed virtual lists this build declared (`virtualList`),
377
+ /// for the app loop's coverage check and scroll re-derivation.
378
+ virtual_window_records: [max_virtual_windows]VirtualWindowRecord = [_]VirtualWindowRecord{.{}} ** max_virtual_windows,
379
+ virtual_window_record_count: usize = 0,
380
+ /// Widget provenance collector (write-back's read half): when set,
381
+ /// the markup engines stamp each built node's source, and
382
+ /// `finalize` feeds the sink one record per markup-authored widget
383
+ /// as it assigns structural ids. Null (the default) costs one
384
+ /// branch per node and captures nothing — builder-only apps and
385
+ /// non-automation runs never pay for it.
386
+ provenance_sink: ?ui_provenance.Sink = null,
387
+ /// Context-menu presentation fallback: when the platform has no
388
+ /// native menu presenter (or presenting failed), the app loop sets
389
+ /// this to the widget whose declared menu should present as an
390
+ /// anchored canvas surface instead. `finalize` synthesizes that
391
+ /// surface — a `dropdown_menu` with `menu_item`/`separator`
392
+ /// children built from the SAME declared items — as an anchored
393
+ /// child of the target, and reports the synthesized ids through
394
+ /// `Tree.context_menu_fallback`. 0 (the default) synthesizes
395
+ /// nothing.
396
+ context_menu_fallback_target: ObjectId = 0,
397
+ /// Set by `finalizeNode` when the fallback target was found and a
398
+ /// surface was synthesized; copied onto the returned `Tree`.
399
+ context_menu_fallback_result: ?Tree.ContextMenuFallback = null,
400
+ /// Markup fragment hot-reload seam (Debug dev runs only): set by
401
+ /// the app loop when the runtime's fragment watch is armed, so a
402
+ /// compiled markup fragment built inline in a Zig view can ask
403
+ /// "did my source change on disk?" and build the reloaded
404
+ /// document through the interpreter instead of its comptime
405
+ /// tree. Null everywhere else — release builds never read it,
406
+ /// and the seam stays untyped (`anyopaque` document pointers)
407
+ /// so the builder core never imports the markup engine.
408
+ markup_fragment_host: ?MarkupFragmentHost = null,
409
+
410
+ pub const ElementOptions = struct {
411
+ /// Sibling-scoped identity: the widget id hashes the parent
412
+ /// chain plus this key, so it survives reorders among siblings
413
+ /// but NOT moving to a different parent.
414
+ key: ?UiKey = null,
415
+ /// Parent-independent identity: the widget id hashes only the
416
+ /// kind and this key, so it survives reparenting (e.g. an item
417
+ /// moving between board columns). The author guarantees each
418
+ /// (kind, global_key) pair is unique within the tree.
419
+ global_key: ?UiKey = null,
420
+ frame: geometry.RectF = .{},
421
+ /// Subtree opacity multiplier. 1 is free (no wrap emitted);
422
+ /// values below 1 wrap the widget's commands in an opacity
423
+ /// group; 0 culls painting entirely. Render-only: an
424
+ /// opacity-0 widget still hit-tests at its layout frame, so
425
+ /// pair with `disabled` (or `semantics.hidden`) when fading
426
+ /// out interactive content.
427
+ opacity: f32 = 1,
428
+ /// Render-space affine applied around the widget's emitted
429
+ /// commands (translate for slide, scale comes free). Identity
430
+ /// is free (no wrap emitted). Layout is untouched — siblings
431
+ /// do not reflow — but pointer hit-testing follows the
432
+ /// transform (points are inverse-mapped into widget space),
433
+ /// so a translated widget stays interactive at its rendered
434
+ /// position. Accessibility frames stay at the layout frame.
435
+ /// Pair with `UiApp.Options.animations` for tweening.
436
+ transform: canvas.Affine = .{},
437
+ /// Widget text (text-field contents, initial control labels).
438
+ /// Text-bearing sugar methods (`text`, `button`, ...) override
439
+ /// this with their content argument.
440
+ text: []const u8 = "",
441
+ placeholder: []const u8 = "",
442
+ value: f32 = 0,
443
+ checked: bool = false,
444
+ selected: bool = false,
445
+ /// Disclosure state for tree rows (`role = .treeitem`): null
446
+ /// = a leaf (no disclosure), false = collapsed (Right
447
+ /// expands via `on_toggle`), true = expanded (Left collapses
448
+ /// via `on_toggle`). Model-owned: the view renders child
449
+ /// rows only while expanded.
450
+ expanded: ?bool = null,
451
+ disabled: bool = false,
452
+ /// Image resource reference for image-bearing widgets
453
+ /// (`image`, `icon_button`, `avatar`): a `canvas.ImageId` the
454
+ /// app registered at runtime (`Runtime.registerCanvasImage`,
455
+ /// `fx.registerImageBytes`). 0 — the "no image" sentinel —
456
+ /// keeps the widget on its non-image rendering (an avatar
457
+ /// falls back to initials).
458
+ image: canvas.ImageId = 0,
459
+ /// Vector icon name drawn inside icon-bearing controls
460
+ /// (`button`, `toggle_button`, `icon_button`, `list_item`,
461
+ /// `menu_item`): a built-in registry name
462
+ /// (`canvas.icons.known_icon_names`) or an app icon
463
+ /// registered at boot (`canvas.icons.registerAppIcons`).
464
+ /// Buttons and toggle buttons draw the icon before the label
465
+ /// — icon-only when the label is empty — and list/menu items
466
+ /// draw it as a leading slot, always as ONE hit target that
467
+ /// follows the widget's enabled/disabled tint. Empty = no
468
+ /// icon; unknown names draw nothing (a Debug-build warning
469
+ /// names them).
470
+ icon: []const u8 = "",
471
+ /// Icon slot side on the label-bearing controls: `.leading`
472
+ /// (default) draws the icon before the label, `.trailing`
473
+ /// after it — the next-page chevron. Icon-only controls
474
+ /// center the glyph regardless.
475
+ icon_placement: canvas.WidgetIconPlacement = .leading,
476
+ /// Source-driven focus request: when this turns on for the
477
+ /// element (it mounts with the flag set, or the value flips
478
+ /// false→true), the runtime moves keyboard focus to it on
479
+ /// the rebuild that applies it — the TEA way to focus the
480
+ /// editor on note-create or give a keyboard-first app its
481
+ /// first focus. Edge-triggered: holding it true never
482
+ /// re-steals focus from the user. Only focusable widgets
483
+ /// (interactive controls) can take it.
484
+ autofocus: bool = false,
485
+ variant: canvas.WidgetVariant = .default,
486
+ size: canvas.WidgetSize = .default,
487
+ /// Definite width: the widget is exactly this wide (the value
488
+ /// becomes both the min and max bound), so intrinsic content
489
+ /// can neither shrink nor silently overflow the box. 0 keeps
490
+ /// intrinsic sizing. `resizable` treats it as the initial
491
+ /// width only (the drag handle keeps resizing past it).
492
+ width: f32 = 0,
493
+ /// Definite height; same contract as `width`.
494
+ height: f32 = 0,
495
+ /// Width floor WITHOUT the definite-max side of `width`:
496
+ /// the widget may grow past it but never shrink below.
497
+ /// Split panes use it to constrain the divider drag (the
498
+ /// clamp band derives from both panes' floors).
499
+ min_width: f32 = 0,
500
+ grow: f32 = 0,
501
+ gap: f32 = 0,
502
+ padding: f32 = 0,
503
+ main: canvas.WidgetMainAlignment = .start,
504
+ cross: canvas.WidgetCrossAlignment = .stretch,
505
+ /// Line policy for `text` leaves. `true`: word-wrap through
506
+ /// the span paragraph machinery (a single-span paragraph),
507
+ /// wrapping at the width the widget receives and reserving
508
+ /// its real wrapped height in columns. `false` and unset:
509
+ /// honest single-line — the content paints as ONE line
510
+ /// (measurement is single-line either way; paint agrees),
511
+ /// and content that does not fit the frame follows
512
+ /// `overflow` (trailing ellipsis by default), so a
513
+ /// width-constrained title never paints a second line over
514
+ /// the row below.
515
+ wrap: ?bool = null,
516
+ /// Single-line overflow policy for `text` leaves whose
517
+ /// content does not fit the frame: `.ellipsis` (default)
518
+ /// elides the tail behind a trailing U+2026 measured with
519
+ /// the same seam paint uses; `.clip` is the deliberate
520
+ /// hard-cut for fixed-format content (a duration column)
521
+ /// where a partial glyph beats losing the format. Wrapped
522
+ /// paragraphs (`wrap = true`) ignore it.
523
+ overflow: canvas.TextOverflow = .ellipsis,
524
+ /// Horizontal alignment of the widget's text content within
525
+ /// its box: `.text` leaves (plain and wrapped/paragraph),
526
+ /// status bars, and surface titles consume it. Controls that
527
+ /// own their label placement (buttons, badges) ignore it.
528
+ text_alignment: canvas.TextAlign = .start,
529
+ /// Fixed column count for `grid` containers. 0 (the default)
530
+ /// keeps the derived near-square column count.
531
+ columns: usize = 0,
532
+ virtualized: bool = false,
533
+ virtual_item_extent: f32 = 0,
534
+ /// Overscan rows built and laid out beyond the visible range
535
+ /// on each side of a virtualized container (scroll slack
536
+ /// before the next window rebuild lands).
537
+ virtual_overscan: usize = 0,
538
+ /// TOTAL item count for a WINDOWED virtual list (see
539
+ /// `Widget.layout.virtual_item_count`): children are the
540
+ /// built window, content extent and semantics derive from
541
+ /// this count, and the runtime owns the scroll offset.
542
+ /// Prefer the `virtualList` sugar, which stamps this
543
+ /// together with the window's first index and offset.
544
+ virtual_item_count: usize = 0,
545
+ /// Virtual index of the first child in a windowed virtual
546
+ /// list (see `Widget.layout.virtual_first_index`).
547
+ virtual_first_index: usize = 0,
548
+ /// VARIABLE-extent windowed virtual list plumbing (see
549
+ /// `Widget.layout.virtual_anchor_index` /
550
+ /// `virtual_anchor_extent` / `virtual_total_extent`).
551
+ /// Prefer the `virtualList` sugar, which computes all three
552
+ /// from the window's offset table.
553
+ virtual_anchor_index: usize = 0,
554
+ virtual_anchor_extent: f32 = 0,
555
+ virtual_total_extent: f32 = 0,
556
+ /// Marks the element as a WINDOW-drag surface (the hidden
557
+ /// titlebar pattern): pressing its own background — or plain
558
+ /// text/icons inside it — moves the window, and double-click
559
+ /// zooms per the OS convention. Interactive children stay
560
+ /// live: the press fall-through walk claims a button inside
561
+ /// the region before the drag does. macOS-only today;
562
+ /// platforms without the channel treat the press as dead
563
+ /// space.
564
+ window_drag: bool = false,
565
+ /// Edge behavior for scroll containers (`scroll`,
566
+ /// `virtualList`): `.default` follows the
567
+ /// `ScrollPhysics.overscroll` design token — off unless a
568
+ /// theme flips it, so scrolling pins at the content edges
569
+ /// with a clean stop. `.rubber_band` lets THIS region bounce
570
+ /// past its edges (engine physics and the native OS scroller
571
+ /// both honor it); `.none` pins it regardless of the token.
572
+ /// Meaningless on non-scroll elements.
573
+ overscroll: canvas.WidgetOverscroll = .default,
574
+ /// Layout-tween duration in milliseconds for `split`
575
+ /// (markup `resize-duration`): nonzero makes the split's
576
+ /// declared `value` a TARGET — a rebuild that moves it no
577
+ /// longer snaps the panes; the runtime eases the rendered
578
+ /// fraction toward it over this duration, one step per
579
+ /// presented frame on the recorded frame clock, reflowing
580
+ /// both panes exactly as a divider drag would and noting
581
+ /// the same `on_resize` echoes. 0 (the default) keeps the
582
+ /// classic snap. Reduced-motion appearances snap inside
583
+ /// the runtime — apps declare nothing extra.
584
+ resize_duration: u32 = 0,
585
+ /// Easing of the split layout tween (markup
586
+ /// `resize-easing`): a `canvas.Easing` member. Only
587
+ /// meaningful with a nonzero `resize_duration` — the
588
+ /// markup validator rejects easing without a duration as
589
+ /// silently-inert data.
590
+ resize_easing: canvas.Easing = .standard,
591
+ /// Enter-from fraction for a freshly MOUNTED split (markup
592
+ /// `resize-origin`): with a nonzero `resize_duration`, the
593
+ /// split's first layout slides its pane boundary to this
594
+ /// fraction (children keep the declared value's pose) and
595
+ /// the runtime eases it to the value from there — a pane
596
+ /// that mounts mid-reveal slides in instead of popping.
597
+ /// Negative (the default) declares no origin. Only
598
+ /// meaningful with a nonzero `resize_duration`.
599
+ resize_origin: f32 = -1,
600
+ style: canvas.WidgetStyle = .{},
601
+ /// Named token references resolved against design tokens in
602
+ /// `finalizeWithTokens`; explicit `style` values win.
603
+ style_tokens: StyleTokenRefs = .{},
604
+ semantics: canvas.WidgetSemantics = .{},
605
+ /// Anchored floating placement: setting this makes the element
606
+ /// a FLOATING surface positioned against its PARENT's resolved
607
+ /// frame (below/above with auto-flip at the window edges), not
608
+ /// the parent's flow — it consumes no parent space, paints in
609
+ /// a late window-level z-pass above the whole tree, and
610
+ /// escapes every ancestor scroll/clip region. The sanctioned
611
+ /// picker shape: a `stack` wraps the trigger, and the anchored
612
+ /// `dropdown_menu` (rendered only while the model's open flag
613
+ /// is set) is the trigger's sibling inside it. Pair with
614
+ /// `on_dismiss` so Escape/click-outside close model-side.
615
+ anchor: ?canvas.WidgetAnchorPlacement = null,
616
+ /// Horizontal alignment against the anchor (`anchor` only):
617
+ /// `start`/`end` align edges, `stretch` also widens the
618
+ /// surface to at least the anchor's width.
619
+ anchor_alignment: canvas.WidgetAnchorAlignment = .start,
620
+ /// Gap in points between anchor edge and surface (`anchor`
621
+ /// only).
622
+ anchor_offset: f32 = 4,
623
+ on_press: ?Msg = null,
624
+ /// Double-click Msg (builder-only): dispatched on a release
625
+ /// whose click count reached 2, in place of `on_press` for
626
+ /// that release. The FIRST click of the double still
627
+ /// dispatches `on_press` on its own release, so the natural
628
+ /// pairing is select-on-press + act-on-double-press (a list
629
+ /// row that selects on click and opens/plays on double
630
+ /// click). Like `on_press`, binding it makes the element a
631
+ /// hit target and press claimer.
632
+ on_double_press: ?Msg = null,
633
+ on_toggle: ?Msg = null,
634
+ on_change: ?Msg = null,
635
+ on_submit: ?Msg = null,
636
+ /// Dismissal Msg for dismissible surfaces (dialog, drawer,
637
+ /// sheet, popover, menu_surface, dropdown_menu): dispatched
638
+ /// when the user dismisses the surface — Escape, a click
639
+ /// outside it, an automation/accessibility dismiss — so the
640
+ /// MODEL owns the close (clear the open flag in update). The
641
+ /// engine hides the surface immediately as an optimistic
642
+ /// echo; the source tree is truth again on the next rebuild.
643
+ on_dismiss: ?Msg = null,
644
+ /// Approach-end Msg for scroll containers (the
645
+ /// infinite-scroll fetch signal): dispatched when a user
646
+ /// scroll brings the offset within one viewport of the
647
+ /// content end, with hysteresis — it fires once per
648
+ /// approach and re-arms only after the offset retreats (or
649
+ /// the content grows, which appending a batch does), so a
650
+ /// user riding the end of the list never dispatches a
651
+ /// fetch storm. Pair with an `update` that appends a batch;
652
+ /// the runtime never calls into the model itself.
653
+ on_reach_end: ?Msg = null,
654
+ /// Approach-START Msg for scroll containers — the
655
+ /// load-older-history signal for tail-anchored transcripts:
656
+ /// dispatched when a user scroll brings the offset within
657
+ /// one viewport of the content start, with the same
658
+ /// hysteresis contract as `on_reach_end` (fires once per
659
+ /// approach; re-arms past one and a half viewports, which
660
+ /// prepending a batch causes on its own because the offset
661
+ /// grows by the prepended extent to keep the viewport
662
+ /// anchored). Builder-only for now, like the windowed
663
+ /// virtual list itself.
664
+ on_reach_start: ?Msg = null,
665
+ /// Press-and-hold Msg: a pointer held down on this element
666
+ /// for ~350 ms dispatches it (the release then presses
667
+ /// nothing), while a quick click dispatches `on_press` as
668
+ /// usual — the SwiftUI Menu + primaryAction shape. A
669
+ /// secondary click (right/ctrl-click) with no context menu on
670
+ /// the route dispatches it immediately, the desktop
671
+ /// alternative. Like `on_press`, binding it makes the element
672
+ /// a hit target and press claimer.
673
+ on_hold: ?Msg = null,
674
+ /// Message constructor for text edits: called with each
675
+ /// `TextInputEvent` on text-entry widgets. Pair with `inputMsg`.
676
+ on_input: ?InputMsgFn = null,
677
+ /// Message constructor for value changes carrying the new value
678
+ /// (slider steps, accessibility set-value). Pair with `valueMsg`.
679
+ on_value: ?ValueMsgFn = null,
680
+ /// Message constructor for split-fraction changes on a
681
+ /// `split` container: called with the new first-pane
682
+ /// fraction after every user resize — divider drag,
683
+ /// keyboard adjustment on the focused divider, assistive
684
+ /// increment/decrement. Pair with `valueMsg`. The delivered
685
+ /// fraction is the value the runtime already applied, so
686
+ /// echoing it back into `value` on the next rebuild never
687
+ /// fights the split reconcile rule.
688
+ on_resize: ?ValueMsgFn = null,
689
+ /// Message constructor for link presses inside a `paragraph`:
690
+ /// called at build time with each link span's payload, so a
691
+ /// click on the link hotspot dispatches the resulting message
692
+ /// through the ordinary press handler table. Pair with
693
+ /// `linkMsg`.
694
+ on_link: ?LinkMsgFn = null,
695
+ /// Message constructor for scroll offset changes on a scroll
696
+ /// container: called with the post-scroll `ScrollState`
697
+ /// (offset, viewport and content extents) after every
698
+ /// user-driven scroll — wheel, kinetic steps, keyboard, and
699
+ /// accessibility scroll actions. Pair with `scrollMsg`. The
700
+ /// delivered offset is the value the runtime already applied,
701
+ /// so echoing it back into `value` on the next rebuild never
702
+ /// fights the scroll reconcile rule.
703
+ on_scroll: ?ScrollMsgFn = null,
704
+ /// Context menu for this widget: right/ctrl-click (or a touch
705
+ /// long-press) presents these items through the platform's
706
+ /// native menu (macOS `NSMenu`); selecting one dispatches its
707
+ /// `msg`. Deepest declaring widget on the hit route wins. On
708
+ /// hosts without a native presenter the SAME items present as
709
+ /// an anchored canvas surface (the app loop's fallback) — one
710
+ /// authored menu, platform-appropriate presentation. Markup
711
+ /// authors declare this with a `<context-menu>` child element.
712
+ context_menu: []const ContextMenuItem = &.{},
713
+ };
714
+
715
+ /// One `ElementOptions.context_menu` entry: the chrome-menu item
716
+ /// shape with a typed message instead of a command string.
717
+ pub const ContextMenuItem = struct {
718
+ label: []const u8 = "",
719
+ msg: ?Msg = null,
720
+ enabled: bool = true,
721
+ separator: bool = false,
722
+ };
723
+
724
+ pub const InputMsgFn = *const fn (edit: canvas.TextInputEvent) Msg;
725
+ pub const ValueMsgFn = *const fn (value: f32) Msg;
726
+ pub const LinkMsgFn = *const fn (link: []const u8) Msg;
727
+ pub const ScrollMsgFn = *const fn (scroll: canvas.ScrollState) Msg;
728
+
729
+ pub const Node = struct {
730
+ widget: Widget = .{ .kind = .stack },
731
+ key: ?UiKey = null,
732
+ global_key: ?UiKey = null,
733
+ /// Deferred `ElementOptions.wrap`: text content may be
734
+ /// assigned after `el` returns (builder sugar and the markup
735
+ /// engines both do), so the single-span conversion (true)
736
+ /// and the no-wrap stamp (false) happen in `finalizeNode`,
737
+ /// when the text is final.
738
+ wrap: ?bool = null,
739
+ style_tokens: StyleTokenRefs = .{},
740
+ on_press: ?Msg = null,
741
+ on_double_press: ?Msg = null,
742
+ on_toggle: ?Msg = null,
743
+ on_change: ?Msg = null,
744
+ on_submit: ?Msg = null,
745
+ on_dismiss: ?Msg = null,
746
+ on_hold: ?Msg = null,
747
+ on_reach_end: ?Msg = null,
748
+ on_reach_start: ?Msg = null,
749
+ on_input: ?InputMsgFn = null,
750
+ on_value: ?ValueMsgFn = null,
751
+ on_resize: ?ValueMsgFn = null,
752
+ on_scroll: ?ScrollMsgFn = null,
753
+ context_menu: []const ContextMenuItem = &.{},
754
+ nodes: []const Node = &.{},
755
+ /// Markup authoring provenance, stamped by the markup engines
756
+ /// when the builder carries a `provenance_sink`; null for
757
+ /// builder-authored (Zig) nodes, which is itself the honest
758
+ /// answer write-back tooling reports for them.
759
+ source: ?*const ui_provenance.NodeSource = null,
760
+ };
761
+
762
+ pub const Handler = struct {
763
+ id: ObjectId,
764
+ event: UiHandlerEvent,
765
+ action: Action,
766
+
767
+ pub const Action = union(enum) {
768
+ message: Msg,
769
+ input: InputMsgFn,
770
+ value: ValueMsgFn,
771
+ scroll: ScrollMsgFn,
772
+ /// Per-item context-menu messages, indexed like the
773
+ /// widget's `context_menu` items (null = inert entry:
774
+ /// separator or msg-less item).
775
+ context_menu: []const ?Msg,
776
+ };
777
+ };
778
+
779
+ /// Comptime message constructor for `on_input`: `inputMsg(.draft)`
780
+ /// yields a function building `Msg{ .draft = edit }`.
781
+ pub fn inputMsg(comptime tag: std.meta.Tag(Msg)) InputMsgFn {
782
+ return struct {
783
+ fn make(edit: canvas.TextInputEvent) Msg {
784
+ return @unionInit(Msg, @tagName(tag), edit);
785
+ }
786
+ }.make;
787
+ }
788
+
789
+ /// Comptime message constructor for `on_value`: `valueMsg(.confidence)`
790
+ /// yields a function building `Msg{ .confidence = value }`.
791
+ pub fn valueMsg(comptime tag: std.meta.Tag(Msg)) ValueMsgFn {
792
+ return struct {
793
+ fn make(value: f32) Msg {
794
+ return @unionInit(Msg, @tagName(tag), value);
795
+ }
796
+ }.make;
797
+ }
798
+
799
+ /// Comptime message constructor for `on_scroll`:
800
+ /// `scrollMsg(.activity_scrolled)` yields a function building
801
+ /// `Msg{ .activity_scrolled = scroll }` from the post-scroll
802
+ /// `canvas.ScrollState`.
803
+ pub fn scrollMsg(comptime tag: std.meta.Tag(Msg)) ScrollMsgFn {
804
+ return struct {
805
+ fn make(scroll_state: canvas.ScrollState) Msg {
806
+ return @unionInit(Msg, @tagName(tag), scroll_state);
807
+ }
808
+ }.make;
809
+ }
810
+
811
+ /// Comptime message constructor for `on_link`: `linkMsg(.open_url)`
812
+ /// yields a function building `Msg{ .open_url = link }`. The link
813
+ /// slice lives in the view arena (or the caller's markdown source),
814
+ /// valid while the tree's handler table is.
815
+ pub fn linkMsg(comptime tag: std.meta.Tag(Msg)) LinkMsgFn {
816
+ return struct {
817
+ fn make(link: []const u8) Msg {
818
+ return @unionInit(Msg, @tagName(tag), link);
819
+ }
820
+ }.make;
821
+ }
822
+
823
+ pub const Tree = struct {
824
+ root: Widget,
825
+ handlers: []const Handler,
826
+ /// Non-null when this build synthesized the anchored
827
+ /// context-menu fallback surface (see
828
+ /// `Ui.context_menu_fallback_target`): the app loop uses the
829
+ /// ids to route item presses through `msgForContextMenu` —
830
+ /// the SAME handler entry native selections resolve — and to
831
+ /// close its open state on dismissal.
832
+ context_menu_fallback: ?ContextMenuFallback = null,
833
+
834
+ /// The synthesized context-menu fallback surface's identity.
835
+ pub const ContextMenuFallback = struct {
836
+ /// The widget whose declared `context_menu` presents.
837
+ target_id: ObjectId,
838
+ /// The synthesized anchored `dropdown_menu` surface.
839
+ surface_id: ObjectId,
840
+ /// Synthesized `menu_item` ids, index-aligned with the
841
+ /// target's `context_menu` items; separators hold 0.
842
+ item_ids: []const ObjectId,
843
+
844
+ /// The declared-item index a synthesized menu item
845
+ /// dispatches, or null for ids outside this surface.
846
+ pub fn itemIndex(self: ContextMenuFallback, id: ObjectId) ?usize {
847
+ if (id == 0) return null;
848
+ for (self.item_ids, 0..) |item_id, index| {
849
+ if (item_id == id) return index;
850
+ }
851
+ return null;
852
+ }
853
+ };
854
+
855
+ pub fn msgFor(self: Tree, id: ObjectId, event: UiHandlerEvent) ?Msg {
856
+ for (self.handlers) |handler| {
857
+ if (handler.id == id and handler.event == event and handler.action == .message) {
858
+ return handler.action.message;
859
+ }
860
+ }
861
+ return null;
862
+ }
863
+
864
+ /// Typed dispatch for text edits: builds the message through the
865
+ /// widget's `on_input` constructor.
866
+ pub fn msgForTextEdit(self: Tree, id: ObjectId, edit: canvas.TextInputEvent) ?Msg {
867
+ for (self.handlers) |handler| {
868
+ if (handler.id == id and handler.event == .input and handler.action == .input) {
869
+ return handler.action.input(edit);
870
+ }
871
+ }
872
+ return null;
873
+ }
874
+
875
+ /// Typed dispatch for value changes: builds the message through
876
+ /// the widget's `on_value` constructor.
877
+ pub fn msgForValue(self: Tree, id: ObjectId, value: f32) ?Msg {
878
+ for (self.handlers) |handler| {
879
+ if (handler.id == id and handler.event == .change and handler.action == .value) {
880
+ return handler.action.value(value);
881
+ }
882
+ }
883
+ return null;
884
+ }
885
+
886
+ /// Typed dispatch for a slider's applied value change (a
887
+ /// pointer rail click or scrub drag): the widget's
888
+ /// `on_value` constructor when bound, else its plain
889
+ /// `on_change` Msg — the same resolution order the keyboard
890
+ /// path's set_value intent uses, so both input families
891
+ /// reach the same handler.
892
+ pub fn msgForChange(self: Tree, id: ObjectId, value: f32) ?Msg {
893
+ if (self.msgForValue(id, value)) |msg| return msg;
894
+ return self.msgFor(id, .change);
895
+ }
896
+
897
+ /// Typed dispatch for split-fraction changes: builds the
898
+ /// message through the split's `on_resize` constructor.
899
+ pub fn msgForResize(self: Tree, id: ObjectId, fraction: f32) ?Msg {
900
+ for (self.handlers) |handler| {
901
+ if (handler.id == id and handler.event == .resize and handler.action == .value) {
902
+ return handler.action.value(fraction);
903
+ }
904
+ }
905
+ return null;
906
+ }
907
+
908
+ /// Typed dispatch for scroll offset changes: builds the message
909
+ /// through the widget's `on_scroll` constructor.
910
+ pub fn msgForScroll(self: Tree, id: ObjectId, scroll_state: canvas.ScrollState) ?Msg {
911
+ for (self.handlers) |handler| {
912
+ if (handler.id == id and handler.event == .scroll and handler.action == .scroll) {
913
+ return handler.action.scroll(scroll_state);
914
+ }
915
+ }
916
+ return null;
917
+ }
918
+
919
+ /// Typed dispatch for a dismissed floating surface: the
920
+ /// surface's `on_dismiss` message.
921
+ pub fn msgForDismiss(self: Tree, id: ObjectId) ?Msg {
922
+ return self.msgFor(id, .dismiss);
923
+ }
924
+
925
+ /// Typed dispatch for a press-and-hold (or menu-less secondary
926
+ /// click): the widget's `on_hold` message.
927
+ pub fn msgForHold(self: Tree, id: ObjectId) ?Msg {
928
+ return self.msgFor(id, .hold);
929
+ }
930
+
931
+ /// Typed dispatch for an approach-end signal on a scroll
932
+ /// container: the widget's `on_reach_end` message. The
933
+ /// hysteresis (fire once per approach, re-arm on retreat or
934
+ /// content growth) lives with the dispatcher (`UiApp`).
935
+ pub fn msgForReachEnd(self: Tree, id: ObjectId) ?Msg {
936
+ return self.msgFor(id, .reach_end);
937
+ }
938
+
939
+ /// Typed dispatch for an approach-START signal (load older
940
+ /// history): the widget's `on_reach_start` message, with the
941
+ /// same dispatcher-owned hysteresis as reach-end.
942
+ pub fn msgForReachStart(self: Tree, id: ObjectId) ?Msg {
943
+ return self.msgFor(id, .reach_start);
944
+ }
945
+
946
+ /// Whether the widget binds an `on_hold` handler (the UiApp
947
+ /// hold-timer arms only for these).
948
+ pub fn hasHoldHandler(self: Tree, id: ObjectId) bool {
949
+ for (self.handlers) |handler| {
950
+ if (handler.id == id and handler.event == .hold) return true;
951
+ }
952
+ return false;
953
+ }
954
+
955
+ /// Typed dispatch for a selected context-menu item: the message
956
+ /// declared for the widget's `context_menu[item_index]`.
957
+ pub fn msgForContextMenu(self: Tree, id: ObjectId, item_index: usize) ?Msg {
958
+ for (self.handlers) |handler| {
959
+ if (handler.id == id and handler.event == .context_menu and handler.action == .context_menu) {
960
+ const msgs = handler.action.context_menu;
961
+ if (item_index >= msgs.len) return null;
962
+ return msgs[item_index];
963
+ }
964
+ }
965
+ return null;
966
+ }
967
+
968
+ pub fn findWidget(self: Tree, id: ObjectId) ?Widget {
969
+ return findWidgetIn(self.root, id);
970
+ }
971
+
972
+ /// Typed dispatch for pointer events: a released press over a
973
+ /// widget resolves through the engine's semantic intent model
974
+ /// (press, then toggle, then select) to the matching handler.
975
+ pub fn msgForPointer(self: Tree, target_id: ObjectId, phase: canvas.WidgetPointerPhase) ?Msg {
976
+ if (phase != .up) return null;
977
+ const widget = self.findWidget(target_id) orelse return null;
978
+ const semantic_actions = [_]canvas.WidgetSemanticAction{ .press, .toggle, .select };
979
+ for (semantic_actions) |action| {
980
+ const intent = canvas.widgetSemanticControlIntent(widget, action) orelse continue;
981
+ if (self.msgForIntent(target_id, intent)) |msg| return msg;
982
+ }
983
+ return null;
984
+ }
985
+
986
+ /// `msgForPointer` with the pointer's click count: a release
987
+ /// whose count reached 2 prefers the widget's `on_double_press`
988
+ /// handler and falls back to the ordinary press resolution
989
+ /// (so a double-click on a widget without the double channel
990
+ /// behaves exactly like two single clicks). This is the
991
+ /// dispatcher the runtime pointer path uses; the two-argument
992
+ /// form stays the single-click entry point.
993
+ pub fn msgForPointerClick(self: Tree, target_id: ObjectId, phase: canvas.WidgetPointerPhase, click_count: u8) ?Msg {
994
+ if (phase == .up and click_count >= 2) {
995
+ if (self.msgFor(target_id, .double_press)) |msg| return msg;
996
+ }
997
+ return self.msgForPointer(target_id, phase);
998
+ }
999
+
1000
+ /// Typed dispatch for keyboard events: engine control intents
1001
+ /// (activation keys, slider steps) plus enter-to-submit on text
1002
+ /// entry widgets.
1003
+ pub fn msgForKeyboard(self: Tree, target_id: ObjectId, keyboard: canvas.WidgetKeyboardEvent) ?Msg {
1004
+ const widget = self.findWidget(target_id) orelse return null;
1005
+ // A list row prefers a bound submit handler on plain
1006
+ // Enter: Enter is the row's PRIMARY action (open the
1007
+ // record, play the track — the desktop list convention),
1008
+ // while Space keeps the select activation below. Only
1009
+ // rows that bind `on_submit` take this branch; everything
1010
+ // else resolves exactly as before.
1011
+ if (widget.kind == .list_item and isSubmitKeyboard(widget, keyboard)) {
1012
+ if (self.msgFor(target_id, .submit)) |msg| return msg;
1013
+ }
1014
+ if (canvas.widgetKeyboardControlIntent(widget, keyboard)) |intent| {
1015
+ if (self.msgForIntent(target_id, intent)) |msg| return msg;
1016
+ }
1017
+ if (isSubmitKeyboard(widget, keyboard)) {
1018
+ if (self.msgFor(target_id, .submit)) |msg| return msg;
1019
+ }
1020
+ if (isTextEntryWidget(widget) and !widget.state.disabled) {
1021
+ // The textarea newline mapping resolves BEFORE the
1022
+ // generic key mapping (which has no Enter case), so
1023
+ // the model's `on_input` hears the same newline the
1024
+ // runtime applied to the retained text.
1025
+ const edit = canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse keyboard.textEditEvent();
1026
+ if (edit) |text_edit| {
1027
+ if (self.msgForTextEdit(target_id, text_edit)) |msg| return msg;
1028
+ }
1029
+ }
1030
+ return null;
1031
+ }
1032
+
1033
+ fn msgForIntent(self: Tree, id: ObjectId, intent: canvas.WidgetControlIntent) ?Msg {
1034
+ return switch (intent.kind) {
1035
+ .press => self.msgFor(id, .press),
1036
+ .toggle => self.msgFor(id, .toggle),
1037
+ .select => self.msgFor(id, .press),
1038
+ .set_value => blk: {
1039
+ if (intent.value) |value| {
1040
+ if (self.msgForValue(id, value)) |msg| break :blk msg;
1041
+ }
1042
+ break :blk self.msgFor(id, .change);
1043
+ },
1044
+ .scroll_by, .scroll_to_start, .scroll_to_end => null,
1045
+ };
1046
+ }
1047
+ };
1048
+
1049
+ pub fn init(arena: std.mem.Allocator) Self {
1050
+ return .{ .arena = arena };
1051
+ }
1052
+
1053
+ pub fn el(self: *Self, kind: WidgetKind, options: ElementOptions, children: anytype) Node {
1054
+ if (options.on_dismiss != null) warnDismissHandlerKind(kind);
1055
+ if (options.on_resize != null) warnResizeHandlerKind(kind);
1056
+ return .{
1057
+ .widget = widgetFromOptions(kind, options),
1058
+ .key = options.key,
1059
+ .global_key = options.global_key,
1060
+ .wrap = options.wrap,
1061
+ .style_tokens = options.style_tokens,
1062
+ .on_press = options.on_press,
1063
+ .on_double_press = options.on_double_press,
1064
+ .on_toggle = options.on_toggle,
1065
+ .on_change = options.on_change,
1066
+ .on_submit = options.on_submit,
1067
+ .on_dismiss = options.on_dismiss,
1068
+ .on_hold = options.on_hold,
1069
+ .on_reach_end = options.on_reach_end,
1070
+ .on_reach_start = options.on_reach_start,
1071
+ .on_input = options.on_input,
1072
+ .on_value = options.on_value,
1073
+ .on_resize = options.on_resize,
1074
+ .on_scroll = options.on_scroll,
1075
+ .context_menu = self.dupeContextMenuItems(options.context_menu),
1076
+ .nodes = self.childNodes(children),
1077
+ };
1078
+ }
1079
+
1080
+ /// Lower built `<context-menu>` child nodes into declared items:
1081
+ /// a `menu_item` node becomes one item (its text run is the
1082
+ /// label, its `on_press` the selection Msg, `disabled` flips
1083
+ /// enabled) and a `separator` node keeps its slot as a divider.
1084
+ /// Both markup engines build the menu's children through the
1085
+ /// ordinary element path — structure tags, interpolation, and
1086
+ /// message typing all apply — and lower the result here, so the
1087
+ /// item shape is stated once.
1088
+ pub fn contextMenuItemsFromNodes(self: *Self, nodes: []const Node) []const ContextMenuItem {
1089
+ if (nodes.len == 0) return &.{};
1090
+ const items = self.arena.alloc(ContextMenuItem, nodes.len) catch {
1091
+ self.failed = true;
1092
+ return &.{};
1093
+ };
1094
+ for (nodes, 0..) |node, index| {
1095
+ items[index] = if (node.widget.kind == .separator)
1096
+ .{ .separator = true }
1097
+ else
1098
+ .{
1099
+ .label = node.widget.text,
1100
+ .msg = node.on_press,
1101
+ .enabled = !node.widget.state.disabled,
1102
+ };
1103
+ }
1104
+ return items;
1105
+ }
1106
+
1107
+ /// Copy rather than alias: callers pass slices of literals that do
1108
+ /// not outlive the expression (same rule as `childNodes`).
1109
+ fn dupeContextMenuItems(self: *Self, items: []const ContextMenuItem) []const ContextMenuItem {
1110
+ if (items.len == 0) return &.{};
1111
+ const copy = self.arena.alloc(ContextMenuItem, items.len) catch {
1112
+ self.failed = true;
1113
+ return &.{};
1114
+ };
1115
+ @memcpy(copy, items);
1116
+ return copy;
1117
+ }
1118
+
1119
+ pub fn row(self: *Self, options: ElementOptions, children: anytype) Node {
1120
+ return self.el(.row, options, children);
1121
+ }
1122
+
1123
+ pub fn column(self: *Self, options: ElementOptions, children: anytype) Node {
1124
+ return self.el(.column, options, children);
1125
+ }
1126
+
1127
+ pub fn stack(self: *Self, options: ElementOptions, children: anytype) Node {
1128
+ return self.el(.stack, options, children);
1129
+ }
1130
+
1131
+ pub fn panel(self: *Self, options: ElementOptions, children: anytype) Node {
1132
+ return self.el(.panel, options, children);
1133
+ }
1134
+
1135
+ pub fn scroll(self: *Self, options: ElementOptions, children: anytype) Node {
1136
+ return self.el(.scroll_view, options, children);
1137
+ }
1138
+
1139
+ pub fn list(self: *Self, options: ElementOptions, children: anytype) Node {
1140
+ return self.el(.list, options, children);
1141
+ }
1142
+
1143
+ /// Options shared by `virtualWindow` and `virtualList` — declare
1144
+ /// them once, pass the same value to both calls.
1145
+ pub const VirtualListOptions = struct {
1146
+ /// Stable list identity: becomes the element's `global_key`
1147
+ /// (so the scroll region's structural id survives layout
1148
+ /// refactors) and the identity the runtime window source
1149
+ /// resolves scroll state by. Unique per (scroll_view,
1150
+ /// global_key) pair within the tree.
1151
+ id: []const u8,
1152
+ /// TOTAL number of items the MODEL holds right now — the
1153
+ /// model owns the data; the runtime only ever sees the
1154
+ /// count, the fixed extent, and the built window.
1155
+ item_count: usize,
1156
+ /// Fixed per-item extent in points — the v1 contract:
1157
+ /// uniform row heights, so the visible index range, the
1158
+ /// content extent, and the scrollbar all derive from
1159
+ /// arithmetic instead of measuring 100k unbuilt rows.
1160
+ item_extent: f32,
1161
+ /// Vertical gap between rows (part of the row stride).
1162
+ gap: f32 = 0,
1163
+ /// Rows built beyond the visible range on each side: scroll
1164
+ /// slack until the next window rebuild lands.
1165
+ overscan: usize = 4,
1166
+ /// Viewport height assumed when no runtime scroll state
1167
+ /// exists for the list yet. Bare builds (plain `finalize`
1168
+ /// tests, previews) use it directly; under `UiApp` the
1169
+ /// installed window source falls back to the canvas height
1170
+ /// instead, so apps normally leave it 0.
1171
+ viewport_fallback: f32 = 0,
1172
+ width: f32 = 0,
1173
+ height: f32 = 0,
1174
+ min_width: f32 = 0,
1175
+ grow: f32 = 0,
1176
+ padding: f32 = 0,
1177
+ style: canvas.WidgetStyle = .{},
1178
+ style_tokens: StyleTokenRefs = .{},
1179
+ /// Container semantics; role defaults to `list`, and the
1180
+ /// layout pass stamps each built row's absolute
1181
+ /// `list_item_index` against the declared count.
1182
+ semantics: canvas.WidgetSemantics = .{},
1183
+ /// Optional scroll observation (`scrollMsg` constructor).
1184
+ /// NOT required for windowing: the runtime re-derives the
1185
+ /// view on scroll for every mounted virtual list on its
1186
+ /// own; bind this only when the model wants the offset.
1187
+ on_scroll: ?ScrollMsgFn = null,
1188
+ /// The infinite-scroll fetch signal (see
1189
+ /// `ElementOptions.on_reach_end`).
1190
+ on_reach_end: ?Msg = null,
1191
+ /// The load-older-history signal (see
1192
+ /// `ElementOptions.on_reach_start`) — the tail-anchored
1193
+ /// transcript's counterpart to `on_reach_end`.
1194
+ on_reach_start: ?Msg = null,
1195
+ /// VARIABLE-extent rows: a cheap per-item extent ESTIMATE
1196
+ /// (called with `extent_context` and the item's LOGICAL
1197
+ /// index, `index_base + physical`). Setting it selects the
1198
+ /// variable contract: the window derives from an offset
1199
+ /// table of estimate prefix sums that the engine patches
1200
+ /// with measured actuals for mounted rows, rows lay out at
1201
+ /// their intrinsic heights, and `item_extent` becomes the
1202
+ /// fallback estimate only (it may be 0). Estimates should
1203
+ /// come from model facts (line counts, attachment
1204
+ /// presence) — never from layout; rough is fine, the
1205
+ /// measured corrections converge the geometry and the
1206
+ /// engine anchors the viewport so corrections never move
1207
+ /// visible content.
1208
+ extent_estimate: ?canvas.VirtualExtentEstimateFn = null,
1209
+ extent_context: ?*const anyopaque = null,
1210
+ /// Logical index of physical item 0. DECREASE it by the
1211
+ /// prepended count when loading older history (chat
1212
+ /// transcripts keyed by sequence number): logical item
1213
+ /// identity — row keys, measured extents, the viewport
1214
+ /// anchor — survives the prepend, and the engine grows the
1215
+ /// scroll offset by the prepended extent so the user keeps
1216
+ /// looking at the same rows. Increase it when the head is
1217
+ /// truncated (bounded transcripts compacting old rows).
1218
+ index_base: u64 = 0,
1219
+ /// Which end the list anchors to. `.trailing` is the chat
1220
+ /// contract: the first build opens at the bottom, and while
1221
+ /// the user sits at the bottom an appended batch keeps the
1222
+ /// list pinned there (scrolled away, appends never yank the
1223
+ /// viewport). Uniform lists may use it too — `item_extent`
1224
+ /// doubles as the estimate.
1225
+ anchor: VirtualListAnchor = .leading,
1226
+ /// Edge behavior of the list's scroll region (see
1227
+ /// `ElementOptions.overscroll`): `.default` follows the
1228
+ /// `ScrollPhysics.overscroll` token — off unless a theme
1229
+ /// flips it — and `.rubber_band` lets this list bounce past
1230
+ /// its edges.
1231
+ overscroll: canvas.WidgetOverscroll = .default,
1232
+ };
1233
+
1234
+ /// Anchoring contract of a windowed virtual list (see
1235
+ /// `VirtualListOptions.anchor`).
1236
+ pub const VirtualListAnchor = enum { leading, trailing };
1237
+
1238
+ /// The DATA-WINDOW seam of the windowed virtual list: resolve
1239
+ /// which item range this build should materialize. The runtime
1240
+ /// owns the viewport math — the installed window source supplies
1241
+ /// the retained scroll offset and viewport for the list identity,
1242
+ /// and the shared `canvas.virtualListRange` turns them into the
1243
+ /// visible index range plus overscan. The MODEL owns the data:
1244
+ /// read `range.start_index..range.end_index`, build one keyed
1245
+ /// node per item, and hand both to `virtualList`. No callbacks
1246
+ /// into the model, no engine-owned copies of the items — the
1247
+ /// range is plain data the view reads during build, the same
1248
+ /// direction of flow as the chrome and appearance channels.
1249
+ pub fn virtualWindow(self: *Self, options: VirtualListOptions) canvas.VirtualListRange {
1250
+ const id = globalWidgetId(.scroll_view, .{ .str = options.id });
1251
+ const resolved: ?VirtualWindowState = blk: {
1252
+ if (self.virtual_window_source) |source| {
1253
+ if (source(self.virtual_window_context, id)) |value| break :blk value;
1254
+ }
1255
+ break :blk null;
1256
+ };
1257
+ if (virtualOptionsVariable(options)) return self.virtualWindowVariable(options, id, resolved);
1258
+ const state: VirtualWindowState = resolved orelse .{ .offset = 0, .viewport_extent = options.viewport_fallback };
1259
+ return canvas.virtualListRange(.{
1260
+ .item_count = options.item_count,
1261
+ .item_extent = options.item_extent,
1262
+ .item_gap = options.gap,
1263
+ .viewport_extent = state.viewport_extent,
1264
+ .scroll_offset = state.offset,
1265
+ .overscan = options.overscan,
1266
+ });
1267
+ }
1268
+
1269
+ /// Whether the options select the VARIABLE-extent contract: an
1270
+ /// estimate fn does, and so does tail anchoring alone (uniform
1271
+ /// trailing lists ride the same offset table with `item_extent`
1272
+ /// as a constant estimate — the was-at-bottom check needs the
1273
+ /// retained previous total).
1274
+ fn virtualOptionsVariable(options: VirtualListOptions) bool {
1275
+ return options.extent_estimate != null or options.anchor == .trailing;
1276
+ }
1277
+
1278
+ /// A user sitting within this many points of the bottom counts
1279
+ /// as "at the bottom" for the trailing anchor's stick-on-append
1280
+ /// rule (sub-point drift from measured corrections must not
1281
+ /// unstick a pinned transcript).
1282
+ const trailing_stick_slop: f32 = 1.0;
1283
+
1284
+ /// The variable-extent window computation: resolve the retained
1285
+ /// offset table (app loop) or fall back to stateless estimates
1286
+ /// (bare builds), consume the table's anchor-preserving offset
1287
+ /// delta so corrections and geometry land atomically, apply the
1288
+ /// trailing anchor, and derive the window from per-item offsets.
1289
+ fn virtualWindowVariable(self: *Self, options: VirtualListOptions, id: ObjectId, resolved: ?VirtualWindowState) canvas.VirtualListRange {
1290
+ const state: VirtualWindowState = resolved orelse .{ .offset = 0, .viewport_extent = options.viewport_fallback, .mounted = false };
1291
+ const viewport = state.viewport_extent;
1292
+ var offset: f32 = state.offset;
1293
+ const table: ?*canvas.VirtualExtentTable = blk: {
1294
+ if (self.virtual_extent_source) |source| break :blk source(self.virtual_extent_context, id);
1295
+ break :blk null;
1296
+ };
1297
+ var range_options = canvas.VirtualVariableRangeOptions{
1298
+ .item_count = options.item_count,
1299
+ .gap = options.gap,
1300
+ .viewport_extent = viewport,
1301
+ .scroll_offset = 0,
1302
+ .overscan = options.overscan,
1303
+ .index_base = options.index_base,
1304
+ .estimate_context = options.extent_context,
1305
+ .estimate_fn = options.extent_estimate,
1306
+ .uniform_estimate = options.item_extent,
1307
+ };
1308
+ if (table) |retained| {
1309
+ _ = retained.sync(.{
1310
+ .id = id,
1311
+ .item_count = options.item_count,
1312
+ .index_base = options.index_base,
1313
+ .gap = options.gap,
1314
+ .estimate_context = options.extent_context,
1315
+ .estimate_fn = options.extent_estimate,
1316
+ .uniform_estimate = options.item_extent,
1317
+ });
1318
+ // Corrections and prepends land here, together with the
1319
+ // patched offsets below — the anchoring invariant.
1320
+ offset += retained.takePendingOffsetDelta();
1321
+ const total = retained.totalExtent();
1322
+ if (options.anchor == .trailing) {
1323
+ if (!state.mounted) {
1324
+ offset = @max(0, total - viewport);
1325
+ } else if (retained.last_build_total >= 0) {
1326
+ // Was-at-the-bottom re-pin: the RETAINED offset
1327
+ // is compared against the geometry it was
1328
+ // scrolled under (last build's total), so both
1329
+ // appends and measured corrections keep a
1330
+ // pinned transcript pinned — while a viewport
1331
+ // scrolled away is never yanked.
1332
+ const old_max = @max(0, retained.last_build_total - retained.last_build_viewport);
1333
+ if (state.offset >= old_max - trailing_stick_slop) offset = @max(0, total - viewport);
1334
+ }
1335
+ }
1336
+ retained.last_build_total = total;
1337
+ retained.last_build_viewport = viewport;
1338
+ } else if (options.anchor == .trailing and !state.mounted) {
1339
+ // Stateless first build of a trailing list: open at the
1340
+ // estimated bottom (one extra estimate pass — bare-build
1341
+ // pricing only; app loops always install a table).
1342
+ const probe = canvas.virtualVariableListRange(range_options, null);
1343
+ offset = @max(0, probe.content_extent - viewport);
1344
+ }
1345
+ range_options.scroll_offset = offset;
1346
+ const variable = canvas.virtualVariableListRange(range_options, table);
1347
+ return .{
1348
+ .start_index = variable.start_index,
1349
+ .end_index = variable.end_index,
1350
+ .first_visible_index = variable.first_visible_index,
1351
+ .last_visible_index = variable.last_visible_index,
1352
+ // 0 marks the variable contract for `virtualList` (rows
1353
+ // stack at intrinsic heights; the table prices the rest).
1354
+ .item_extent = 0,
1355
+ .item_gap = @max(0, options.gap),
1356
+ .scroll_offset = variable.scroll_offset,
1357
+ .layout_offset = variable.layout_offset,
1358
+ .content_extent = variable.content_extent,
1359
+ .before_extent = variable.before_extent,
1360
+ .after_extent = variable.after_extent,
1361
+ .anchor_extent = variable.anchor_extent,
1362
+ };
1363
+ }
1364
+
1365
+ /// A WINDOWED virtual list: a runtime-scrolled scroll region
1366
+ /// representing `item_count` items of which only `children` —
1367
+ /// the rows for the `window` returned by `virtualWindow`, one
1368
+ /// keyed node per item — exist in the tree. The runtime owns
1369
+ /// the scroll offset (wheel, kinetic, keyboard, and the native
1370
+ /// scroll driver, whose scrollbar spans the full virtual
1371
+ /// extent); the layout pass places each built row at its
1372
+ /// absolute virtual position; and per-item identity rides the
1373
+ /// row keys, so engine-owned row state survives scrolling away
1374
+ /// and back. Budgets stay viewport-sized: the widget-node cost
1375
+ /// is the window, never the dataset.
1376
+ pub fn virtualList(self: *Self, options: VirtualListOptions, window: canvas.VirtualListRange, children: anytype) Node {
1377
+ var semantics = options.semantics;
1378
+ if (semantics.role == .none) semantics.role = .list;
1379
+ const variable = virtualOptionsVariable(options);
1380
+ const node = self.el(.scroll_view, .{
1381
+ .global_key = .{ .str = options.id },
1382
+ // Mirror the runtime offset into the source so the flex
1383
+ // pass lays the window out at the offset the window was
1384
+ // computed for — the same value the scroll reconcile
1385
+ // keeps, so source and runtime never fight. (For a
1386
+ // variable list this is also the CORRECTION channel: an
1387
+ // anchor-preserving offset shift stamps a changed
1388
+ // source value, which the reconcile treats as the
1389
+ // programmatic scroll it is.)
1390
+ .value = window.layout_offset,
1391
+ .width = options.width,
1392
+ .height = options.height,
1393
+ .min_width = options.min_width,
1394
+ .grow = options.grow,
1395
+ .padding = options.padding,
1396
+ .gap = options.gap,
1397
+ .virtualized = true,
1398
+ .virtual_item_extent = if (variable) 0 else options.item_extent,
1399
+ .virtual_overscan = options.overscan,
1400
+ .virtual_item_count = options.item_count,
1401
+ .virtual_first_index = window.start_index,
1402
+ .virtual_anchor_index = if (variable) window.first_visible_index else 0,
1403
+ .virtual_anchor_extent = if (variable) window.anchor_extent else 0,
1404
+ .virtual_total_extent = if (variable) window.content_extent else 0,
1405
+ .style = options.style,
1406
+ .style_tokens = options.style_tokens,
1407
+ .semantics = semantics,
1408
+ .overscroll = options.overscroll,
1409
+ .on_scroll = options.on_scroll,
1410
+ .on_reach_end = options.on_reach_end,
1411
+ .on_reach_start = options.on_reach_start,
1412
+ }, children);
1413
+ self.recordVirtualWindow(.{
1414
+ .id = globalWidgetId(.scroll_view, .{ .str = options.id }),
1415
+ .item_count = options.item_count,
1416
+ .item_extent = options.item_extent,
1417
+ .gap = options.gap,
1418
+ .overscan = options.overscan,
1419
+ .start_index = window.start_index,
1420
+ .end_index = window.start_index + node.nodes.len,
1421
+ .variable = variable,
1422
+ .index_base = options.index_base,
1423
+ });
1424
+ return node;
1425
+ }
1426
+
1427
+ fn recordVirtualWindow(self: *Self, record: VirtualWindowRecord) void {
1428
+ if (self.virtual_window_record_count >= self.virtual_window_records.len) {
1429
+ if (builtin.mode == .Debug) {
1430
+ ui_log.warn(
1431
+ "more than {d} virtual lists in one build (canvas.ui_builder.max_virtual_windows) - the excess scrolls but skips the app loop's window coverage check",
1432
+ .{max_virtual_windows},
1433
+ );
1434
+ }
1435
+ return;
1436
+ }
1437
+ self.virtual_window_records[self.virtual_window_record_count] = record;
1438
+ self.virtual_window_record_count += 1;
1439
+ }
1440
+
1441
+ /// The declared virtual windows of this build (`virtualList`
1442
+ /// calls), for the app loop.
1443
+ pub fn virtualWindows(self: *const Self) []const VirtualWindowRecord {
1444
+ return self.virtual_window_records[0..self.virtual_window_record_count];
1445
+ }
1446
+
1447
+ /// Two-pane horizontal splitter. Exactly two children (the
1448
+ /// panes); `finalize` synthesizes the draggable divider between
1449
+ /// them. `value` is the model-owned first-pane fraction (0 lays
1450
+ /// out at 0.5); bind `on_resize = valueMsg(.tag)` and echo the
1451
+ /// fraction back through `value` for the controlled pattern —
1452
+ /// an unbound split keeps its divider position across rebuilds
1453
+ /// through the source-wins reconcile, but pane content lays out
1454
+ /// at the declared fraction until the model echoes.
1455
+ ///
1456
+ /// With a nonzero `resize_duration` the declared `value` is a
1457
+ /// TARGET instead: a rebuild that moves it eases the rendered
1458
+ /// fraction there over that many milliseconds (`resize_easing`
1459
+ /// names the curve) instead of snapping — the declarative twin
1460
+ /// of `UiApp.Options.layout_tweens`, and the shape markup's
1461
+ /// `resize-duration`/`resize-easing` lower to. Reduced motion
1462
+ /// snaps inside the runtime.
1463
+ pub fn split(self: *Self, options: ElementOptions, children: anytype) Node {
1464
+ return self.el(.split, options, children);
1465
+ }
1466
+
1467
+ /// Disclosure-tree container: descendant rows carrying
1468
+ /// `role = .treeitem` (at any nesting depth) form one roving
1469
+ /// keyboard focus set with the ARIA tree keymap — Up/Down walk
1470
+ /// visible rows (selection follows focus through each row's
1471
+ /// `on_press`), Left collapses or moves to the parent row,
1472
+ /// Right expands or moves to the first child row, Home/End jump
1473
+ /// to the edges. Expansion is model-owned: expandable rows set
1474
+ /// `expanded` and bind `on_toggle`.
1475
+ pub fn tree(self: *Self, options: ElementOptions, children: anytype) Node {
1476
+ return self.el(.tree, options, children);
1477
+ }
1478
+
1479
+ /// The engine renders a status bar's own `text`; it does not lay out
1480
+ /// status bar children, so the builder models it as a text leaf.
1481
+ pub fn statusBar(self: *Self, options: ElementOptions, status_text: []const u8) Node {
1482
+ var node = self.el(.status_bar, options, .{});
1483
+ node.widget.text = status_text;
1484
+ return node;
1485
+ }
1486
+
1487
+ pub fn text(self: *Self, options: ElementOptions, content: []const u8) Node {
1488
+ var node = self.el(.text, options, .{});
1489
+ node.widget.text = content;
1490
+ return node;
1491
+ }
1492
+
1493
+ /// A paragraph of inline styled spans (mixed weight/italic/mono/
1494
+ /// color/underline/strikethrough/link runs in one wrapped text
1495
+ /// block). The spans' bytes are concatenated into an arena buffer
1496
+ /// (`widget.text`, the semantics label) and every stored span is
1497
+ /// re-sliced into it, so retained-state copies rebase rather than
1498
+ /// duplicate. Each link span also grows a hit-area child with
1499
+ /// `role = link` semantics; with `options.on_link` set, pressing
1500
+ /// it dispatches `on_link(span.link)` through the handler table.
1501
+ pub fn paragraph(self: *Self, options: ElementOptions, spans: []const canvas.TextSpan) Node {
1502
+ var node = self.el(.text, options, .{});
1503
+
1504
+ var text_len: usize = 0;
1505
+ for (spans) |span| text_len += span.text.len;
1506
+ const text_bytes = self.arena.alloc(u8, text_len) catch {
1507
+ self.failed = true;
1508
+ return node;
1509
+ };
1510
+ const stored = self.arena.dupe(canvas.TextSpan, spans) catch {
1511
+ self.failed = true;
1512
+ return node;
1513
+ };
1514
+ var offset: usize = 0;
1515
+ for (stored) |*span| {
1516
+ @memcpy(text_bytes[offset .. offset + span.text.len], span.text);
1517
+ span.text = text_bytes[offset .. offset + span.text.len];
1518
+ offset += span.text.len;
1519
+ }
1520
+ node.widget.text = text_bytes;
1521
+ node.widget.spans = stored;
1522
+
1523
+ const link_count = canvas.text_spans.textSpanLinkCount(stored);
1524
+ if (link_count == 0) return node;
1525
+ const children = self.arena.alloc(Node, link_count) catch {
1526
+ self.failed = true;
1527
+ return node;
1528
+ };
1529
+ var child_index: usize = 0;
1530
+ for (stored) |span| {
1531
+ if (span.link.len == 0) continue;
1532
+ children[child_index] = self.el(.text, .{
1533
+ .semantics = .{
1534
+ .role = .link,
1535
+ .label = span.text,
1536
+ .focusable = true,
1537
+ },
1538
+ .on_press = if (options.on_link) |make| make(span.link) else null,
1539
+ }, .{});
1540
+ child_index += 1;
1541
+ }
1542
+ node.nodes = children;
1543
+ return node;
1544
+ }
1545
+
1546
+ pub fn button(self: *Self, options: ElementOptions, label: []const u8) Node {
1547
+ var node = self.el(.button, options, .{});
1548
+ node.widget.text = label;
1549
+ return node;
1550
+ }
1551
+
1552
+ pub fn listItem(self: *Self, options: ElementOptions, label: []const u8) Node {
1553
+ var node = self.el(.list_item, options, .{});
1554
+ node.widget.text = label;
1555
+ return node;
1556
+ }
1557
+
1558
+ pub fn checkbox(self: *Self, options: ElementOptions) Node {
1559
+ return self.el(.checkbox, options, .{});
1560
+ }
1561
+
1562
+ /// house-style avatar: a pill-clipped image with an initials
1563
+ /// fallback. With `options.image` set to a registered ImageId the
1564
+ /// engine clips the image to the avatar circle (`cover` fit);
1565
+ /// with no image (0) it renders `initials` centered — so an app
1566
+ /// shows initials while the image is loading and keeps them when
1567
+ /// the fetch or decode failed, by only writing the id into its
1568
+ /// model on successful registration (`fx.registerImageBytes`).
1569
+ pub fn avatar(self: *Self, options: ElementOptions, initials: []const u8) Node {
1570
+ var node = self.el(.avatar, options, .{});
1571
+ node.widget.text = initials;
1572
+ node.widget.image_fit = .cover;
1573
+ return node;
1574
+ }
1575
+
1576
+ /// An image leaf drawing the registered ImageId in
1577
+ /// `options.image` (nothing renders while the id is 0 or
1578
+ /// unregistered).
1579
+ pub fn image(self: *Self, options: ElementOptions) Node {
1580
+ return self.el(.image, options, .{});
1581
+ }
1582
+
1583
+ /// A built-in vector icon leaf: `name` is one of
1584
+ /// `canvas.icons.known_icon_names` (compile error otherwise), so
1585
+ /// icon references never rot. Size comes from `options.size` /
1586
+ /// explicit width and height (square by default), tint from the
1587
+ /// `foreground` style token (`currentColor` in the SVG source).
1588
+ pub fn icon(self: *Self, options: ElementOptions, comptime name: []const u8) Node {
1589
+ comptime {
1590
+ if (canvas.icons.find(name) == null) {
1591
+ @compileError("unknown built-in icon \"" ++ name ++ "\" - see canvas.icons.known_icon_names");
1592
+ }
1593
+ }
1594
+ var node = self.el(.icon, options, .{});
1595
+ node.widget.text = name;
1596
+ return node;
1597
+ }
1598
+
1599
+ /// An icon leaf rendering an APP-REGISTERED vector icon: `name`
1600
+ /// must be registered at boot via `canvas.icons.registerAppIcons`
1601
+ /// (comptime-parse your SVG with `canvas.svg_icon.parseComptime`).
1602
+ /// No compile-time check is possible for runtime registrations —
1603
+ /// an unknown name draws the missing-icon fallback (a slashed
1604
+ /// circle), with a Debug-build warning naming the value. For
1605
+ /// built-in names prefer `icon`, which compile-checks the name.
1606
+ pub fn appIcon(self: *Self, options: ElementOptions, name: []const u8) Node {
1607
+ // The EXPLICIT icon channel (`Widget.icon`), not `text`: the
1608
+ // draw path then owns the honest failure mode above, instead
1609
+ // of the historical glyph rendering spelling the raw name in
1610
+ // text glyphs.
1611
+ var with_icon = options;
1612
+ with_icon.icon = name;
1613
+ return self.el(.icon, with_icon, .{});
1614
+ }
1615
+
1616
+ /// An icon leaf rendering a literal glyph (the pre-vector-icon
1617
+ /// behavior, e.g. an emoji or dingbat character): kept for text
1618
+ /// glyphs; prefer `icon` for the built-in vector set.
1619
+ pub fn iconGlyph(self: *Self, options: ElementOptions, glyph: []const u8) Node {
1620
+ var node = self.el(.icon, options, .{});
1621
+ node.widget.text = glyph;
1622
+ return node;
1623
+ }
1624
+
1625
+ pub fn textField(self: *Self, options: ElementOptions) Node {
1626
+ return self.el(.text_field, options, .{});
1627
+ }
1628
+
1629
+ pub fn separator(self: *Self, options: ElementOptions) Node {
1630
+ return self.el(.separator, options, .{});
1631
+ }
1632
+
1633
+ /// Flexible empty space between siblings.
1634
+ pub fn spacer(self: *Self, grow: f32) Node {
1635
+ return self.el(.stack, .{ .grow = grow }, .{});
1636
+ }
1637
+
1638
+ pub const ChartOptions = struct {
1639
+ key: ?UiKey = null,
1640
+ global_key: ?UiKey = null,
1641
+ /// Definite plot width/height (same contract as
1642
+ /// `ElementOptions.width`/`height`); 0 keeps the intrinsic
1643
+ /// sparkline-sized default (160x48), and `grow` flexes.
1644
+ width: f32 = 0,
1645
+ height: f32 = 0,
1646
+ grow: f32 = 0,
1647
+ padding: f32 = 0,
1648
+ /// Explicit y domain; null derives each side from the data
1649
+ /// (bar series force 0 into a derived domain — bars always
1650
+ /// have an honest zero baseline).
1651
+ y_min: ?f32 = null,
1652
+ y_max: ?f32 = null,
1653
+ /// Horizontal token-hairline gridlines at even divisions
1654
+ /// (0 = none; gridlines are opt-in, never default).
1655
+ grid_lines: u8 = 0,
1656
+ /// Hairline at the baseline (zero clamped into the domain).
1657
+ baseline: bool = false,
1658
+ /// Line stroke width override (default 1.5).
1659
+ stroke_width: ?f32 = null,
1660
+ /// Category labels for the x axis, one per sample index
1661
+ /// (label i names sample i). Empty = no x axis; the renderer
1662
+ /// reserves a gutter below the plot and thins the labels to
1663
+ /// fit the width. Dropped when any series downsamples — the
1664
+ /// bucketed indices no longer name the labeled samples.
1665
+ x_labels: []const []const u8 = &.{},
1666
+ /// Numeric y tick labels (opt-in): domain min, max, and each
1667
+ /// gridline value in a measured gutter left of the plot,
1668
+ /// muted, deterministically formatted.
1669
+ y_labels: bool = false,
1670
+ /// Pointer-hover point details (opt-in): hovering snaps to
1671
+ /// the nearest sample and floats a card with its label and
1672
+ /// every series' value. Interaction-only chrome — static
1673
+ /// renders never show it. Presses still fall through.
1674
+ hover_details: bool = false,
1675
+ /// Role defaults to `chart`; an empty label gets a generated
1676
+ /// series summary ("chart: line cpu 60 pts last 0.42; ...")
1677
+ /// so automation can assert on the data without pixels, and
1678
+ /// `semantics.value` reports the first series' latest point.
1679
+ semantics: canvas.WidgetSemantics = .{},
1680
+ };
1681
+
1682
+ /// A data chart leaf: line (with optional area fill),
1683
+ /// bar, and band series over uniform x steps, drawn through the
1684
+ /// vector path pipeline with token-driven colors. Series are
1685
+ /// copied into the build arena and DOWNSAMPLED deterministically
1686
+ /// to `canvas.max_chart_points_per_series` points (index-bucket
1687
+ /// min/max, spikes preserved), so a 10k-point star-history series
1688
+ /// renders within the path budget instead of erroring. Axis tick
1689
+ /// labels are opt-in (`x_labels`/`y_labels`, drawn muted in
1690
+ /// reserved gutters) and hover details opt in per chart. Presses
1691
+ /// fall through like text; with `hover_details` the chart is a
1692
+ /// hover target only.
1693
+ pub fn chart(self: *Self, options: ChartOptions, series: []const canvas.ChartSeries) Node {
1694
+ var node = self.el(.chart, .{
1695
+ .key = options.key,
1696
+ .global_key = options.global_key,
1697
+ .width = options.width,
1698
+ .height = options.height,
1699
+ .grow = options.grow,
1700
+ .padding = options.padding,
1701
+ .style = .{ .stroke_width = options.stroke_width },
1702
+ .semantics = options.semantics,
1703
+ }, .{});
1704
+ const stored = self.arena.alloc(canvas.ChartSeries, series.len) catch {
1705
+ self.failed = true;
1706
+ return node;
1707
+ };
1708
+ var downsampled = false;
1709
+ for (series, stored) |source, *entry| {
1710
+ entry.* = source;
1711
+ entry.values = self.downsampledChartCopy(source.values);
1712
+ entry.low = if (source.kind == .band) self.downsampledChartCopy(source.low) else &.{};
1713
+ if (entry.values.len != source.values.len) downsampled = true;
1714
+ }
1715
+ node.widget.chart = .{
1716
+ .series = stored,
1717
+ .y_min = options.y_min,
1718
+ .y_max = options.y_max,
1719
+ .grid_lines = options.grid_lines,
1720
+ .baseline = options.baseline,
1721
+ // Downsampling re-buckets sample indices, so per-sample
1722
+ // category labels would name the wrong points: drop them
1723
+ // (silence over a lie) — value-scale y labels survive.
1724
+ .x_labels = if (downsampled) &.{} else options.x_labels,
1725
+ .y_labels = options.y_labels,
1726
+ .hover_details = options.hover_details,
1727
+ };
1728
+ if (node.widget.semantics.label.len == 0) {
1729
+ node.widget.semantics.label = self.chartSummary(series);
1730
+ }
1731
+ return node;
1732
+ }
1733
+
1734
+ fn downsampledChartCopy(self: *Self, values: []const f32) []const f32 {
1735
+ if (values.len == 0) return &.{};
1736
+ const output = self.arena.alloc(f32, canvas.downsampledChartLen(values.len)) catch {
1737
+ self.failed = true;
1738
+ return &.{};
1739
+ };
1740
+ return canvas.downsampleChartValues(values, output);
1741
+ }
1742
+
1743
+ /// The generated semantics summary describes the SOURCE series
1744
+ /// (pre-downsampling counts and the true latest values), so
1745
+ /// automation asserts on the data the app handed over.
1746
+ fn chartSummary(self: *Self, series: []const canvas.ChartSeries) []const u8 {
1747
+ var summary: []const u8 = "chart:";
1748
+ for (series, 0..) |entry, index| {
1749
+ const name = if (entry.label.len > 0) entry.label else @tagName(entry.kind);
1750
+ const joiner: []const u8 = if (index == 0) " " else "; ";
1751
+ summary = if (entry.values.len > 0)
1752
+ self.fmt("{s}{s}{s} {d} pts last {d:.2}", .{ summary, joiner, name, entry.values.len, entry.values[entry.values.len - 1] })
1753
+ else
1754
+ self.fmt("{s}{s}{s} empty", .{ summary, joiner, name });
1755
+ }
1756
+ return summary;
1757
+ }
1758
+
1759
+ pub const InputGroupOptions = struct {
1760
+ key: ?UiKey = null,
1761
+ global_key: ?UiKey = null,
1762
+ /// Definite group width/height (same contract as
1763
+ /// `ElementOptions.width`/`height`); 0 sizes from the entry's
1764
+ /// intrinsic height plus the actions row, and `grow` flexes.
1765
+ width: f32 = 0,
1766
+ height: f32 = 0,
1767
+ min_width: f32 = 0,
1768
+ grow: f32 = 0,
1769
+ /// Group semantics; role defaults to `group` so the whole
1770
+ /// field announces as one named unit while the entry and the
1771
+ /// accessory controls stay individually reachable.
1772
+ semantics: canvas.WidgetSemantics = .{},
1773
+ };
1774
+
1775
+ pub const InputGroupActionsOptions = struct {
1776
+ key: ?UiKey = null,
1777
+ global_key: ?UiKey = null,
1778
+ gap: f32 = 6,
1779
+ };
1780
+
1781
+ /// Composer-grade grouped input (the house input-group): ONE
1782
+ /// bordered field wrapping a multi-line text entry plus an
1783
+ /// optional accessory row of controls inside the same border —
1784
+ /// the reference composer shape (attach bottom-left, send
1785
+ /// bottom-right). The group wears text-input chrome and the
1786
+ /// focus ring whenever focus is on any descendant; the entry's
1787
+ /// own chrome (fill, border, focus ring) dissolves (the notes
1788
+ /// editor-pane treatment) unless the author styled it
1789
+ /// explicitly, so the group reads as one field. The entry comes
1790
+ /// FIRST (document order is focus order); build the accessory
1791
+ /// row with `inputGroupActions`.
1792
+ pub fn inputGroup(self: *Self, options: InputGroupOptions, entry: Node, actions: ?Node) Node {
1793
+ var semantics = options.semantics;
1794
+ if (semantics.role == .none) semantics.role = .group;
1795
+ var entry_node = entry;
1796
+ dissolveInputGroupEntryChrome(&entry_node);
1797
+ // The entry absorbs the group's height: an explicitly sized
1798
+ // group grows its text entry, never a gap under the actions.
1799
+ if (entry_node.widget.layout.grow == 0) entry_node.widget.layout.grow = 1;
1800
+ const child_count: usize = if (actions == null) 1 else 2;
1801
+ const nodes = self.arena.alloc(Node, child_count) catch {
1802
+ self.failed = true;
1803
+ return self.el(.input_group, .{ .semantics = semantics }, .{});
1804
+ };
1805
+ nodes[0] = entry_node;
1806
+ if (actions) |actions_node| nodes[1] = actions_node;
1807
+ return self.el(.input_group, .{
1808
+ .key = options.key,
1809
+ .global_key = options.global_key,
1810
+ .width = options.width,
1811
+ .height = options.height,
1812
+ .min_width = options.min_width,
1813
+ .grow = options.grow,
1814
+ .semantics = semantics,
1815
+ }, .{nodes[0..child_count]});
1816
+ }
1817
+
1818
+ /// The input-group's accessory row: leading/trailing controls on
1819
+ /// one bottom row INSIDE the group's border (put a
1820
+ /// `spacer(1)` between the leading and trailing controls). Insets
1821
+ /// keep ghost/icon buttons optically inside the field's own text
1822
+ /// inset without double-padding the seam.
1823
+ pub fn inputGroupActions(self: *Self, options: InputGroupActionsOptions, children: anytype) Node {
1824
+ var node = self.el(.row, .{
1825
+ .key = options.key,
1826
+ .global_key = options.global_key,
1827
+ .gap = options.gap,
1828
+ .cross = .center,
1829
+ }, children);
1830
+ node.widget.layout.padding = .{ .top = 4, .left = 8, .right = 8, .bottom = 8 };
1831
+ return node;
1832
+ }
1833
+
1834
+ /// Dissolve the entry's control chrome into the group (the notes
1835
+ /// editor-pane treatment, structural here): transparent fill,
1836
+ /// border, and focus ring — the GROUP draws that chrome — unless
1837
+ /// the author styled the field explicitly (style tokens included),
1838
+ /// in which case the explicit choice wins.
1839
+ fn dissolveInputGroupEntryChrome(node: *Node) void {
1840
+ const transparent = canvas.Color.rgba8(0, 0, 0, 0);
1841
+ if (node.widget.style.background == null and node.style_tokens.background == null) {
1842
+ node.widget.style.background = transparent;
1843
+ }
1844
+ if (node.widget.style.border == null and node.style_tokens.border_color == null) {
1845
+ node.widget.style.border = transparent;
1846
+ }
1847
+ if (node.widget.style.focus_ring == null and node.style_tokens.focus_ring == null) {
1848
+ node.widget.style.focus_ring = transparent;
1849
+ }
1850
+ }
1851
+
1852
+ /// Visual state of a stepper step, derived from its index against
1853
+ /// `StepperOptions.active`.
1854
+ pub const StepState = enum { completed, active, pending };
1855
+
1856
+ pub const StepperStep = struct {
1857
+ /// Step label ("Work", "Review · round 2").
1858
+ label: []const u8,
1859
+ };
1860
+
1861
+ pub const StepperOptions = struct {
1862
+ /// Index of the active step: earlier steps render completed
1863
+ /// (check indicator), later ones pending. An index past the
1864
+ /// last step renders every step completed.
1865
+ active: usize = 0,
1866
+ key: ?UiKey = null,
1867
+ global_key: ?UiKey = null,
1868
+ grow: f32 = 0,
1869
+ /// Row semantics; role defaults to `list` (each step is a
1870
+ /// `listitem` carrying its label, state, and position).
1871
+ semantics: canvas.WidgetSemantics = .{},
1872
+ };
1873
+
1874
+ pub fn stepState(active: usize, index: usize) StepState {
1875
+ if (index < active) return .completed;
1876
+ if (index == active) return .active;
1877
+ return .pending;
1878
+ }
1879
+
1880
+ /// Stage stepper (the house stepper conventions: item + indicator +
1881
+ /// title joined by separators): a horizontal row of steps whose
1882
+ /// completed/active/pending states derive from `options.active`.
1883
+ /// Indicators are badges — a check for completed steps, the step
1884
+ /// number otherwise — and hairline separators connect the steps.
1885
+ /// Display-only: driving `active` belongs to the app model.
1886
+ pub fn stepper(self: *Self, options: StepperOptions, steps: []const StepperStep) Node {
1887
+ var semantics = options.semantics;
1888
+ if (semantics.role == .none) semantics.role = .list;
1889
+ const node_count = if (steps.len == 0) 0 else steps.len * 2 - 1;
1890
+ const nodes = self.arena.alloc(Node, node_count) catch {
1891
+ self.failed = true;
1892
+ return self.el(.row, .{ .semantics = semantics }, .{});
1893
+ };
1894
+ for (steps, 0..) |step, index| {
1895
+ nodes[index * 2] = self.stepperStepNode(options.active, index, steps.len, step);
1896
+ if (index + 1 < steps.len) {
1897
+ // The connector between steps: a bare separator inside
1898
+ // a row renders as a hairline across the space it grows
1899
+ // into.
1900
+ nodes[index * 2 + 1] = self.el(.separator, .{ .grow = 1 }, .{});
1901
+ }
1902
+ }
1903
+ return self.el(.row, .{
1904
+ .key = options.key,
1905
+ .global_key = options.global_key,
1906
+ .gap = 8,
1907
+ .cross = .center,
1908
+ .grow = options.grow,
1909
+ .semantics = semantics,
1910
+ }, .{nodes});
1911
+ }
1912
+
1913
+ fn stepperStepNode(self: *Self, active: usize, index: usize, count: usize, step: StepperStep) Node {
1914
+ const state = stepState(active, index);
1915
+ // Completed steps wear the vector `check` icon — the ✓ text
1916
+ // glyph is outside the bundled face's coverage and rendered
1917
+ // as tofu on the reference/screenshot paths.
1918
+ const indicator = self.el(.badge, .{
1919
+ .variant = if (state == .pending) canvas.WidgetVariant.outline else .primary,
1920
+ .icon = if (state == .completed) "check" else "",
1921
+ .text = if (state == .completed) "" else self.fmt("{d}", .{index + 1}),
1922
+ }, .{});
1923
+ const label: Node = switch (state) {
1924
+ .active => self.paragraph(.{}, &.{.{ .text = step.label, .weight = .bold }}),
1925
+ .completed => self.text(.{}, step.label),
1926
+ .pending => self.text(.{ .style_tokens = .{ .foreground = .text_muted } }, step.label),
1927
+ };
1928
+ return self.el(.row, .{
1929
+ .key = .{ .int = @intCast(index) },
1930
+ .gap = 6,
1931
+ .cross = .center,
1932
+ .selected = state == .active,
1933
+ .semantics = .{
1934
+ .role = .listitem,
1935
+ .label = self.fmt("{s} ({s})", .{ step.label, @tagName(state) }),
1936
+ .list_item_index = @intCast(index),
1937
+ .list_item_count = @intCast(count),
1938
+ },
1939
+ }, .{ indicator, label });
1940
+ }
1941
+
1942
+ pub const TimelineOptions = struct {
1943
+ key: ?UiKey = null,
1944
+ global_key: ?UiKey = null,
1945
+ gap: f32 = 0,
1946
+ grow: f32 = 0,
1947
+ /// Column semantics; role defaults to `list`.
1948
+ semantics: canvas.WidgetSemantics = .{},
1949
+ };
1950
+
1951
+ /// Timeline/ledger list (the house timeline conventions: item +
1952
+ /// indicator + separator + title/description/meta): a column of
1953
+ /// `timelineItem` nodes.
1954
+ pub fn timeline(self: *Self, options: TimelineOptions, items: anytype) Node {
1955
+ var semantics = options.semantics;
1956
+ if (semantics.role == .none) semantics.role = .list;
1957
+ return self.el(.column, .{
1958
+ .key = options.key,
1959
+ .global_key = options.global_key,
1960
+ .gap = options.gap,
1961
+ .grow = options.grow,
1962
+ .semantics = semantics,
1963
+ }, items);
1964
+ }
1965
+
1966
+ pub const TimelineItemOptions = struct {
1967
+ key: ?UiKey = null,
1968
+ global_key: ?UiKey = null,
1969
+ /// Indicator badge text ("3"); empty (with no `icon`) renders
1970
+ /// a small dot. Prefer `icon` for symbols — text glyphs
1971
+ /// outside the bundled face render as tofu on the
1972
+ /// reference/screenshot paths.
1973
+ indicator: []const u8 = "",
1974
+ /// Vector icon indicator (registry name, e.g. "check"):
1975
+ /// drawn inside the badge with the variant's tint. Wins the
1976
+ /// badge's content slot alongside `indicator` text.
1977
+ icon: []const u8 = "",
1978
+ /// Indicator color variant — map run outcomes here (primary
1979
+ /// for done, destructive for errors, outline for stopped, ...).
1980
+ variant: canvas.WidgetVariant = .outline,
1981
+ title: []const u8,
1982
+ /// Wrapped muted preview under the title (step summary).
1983
+ description: []const u8 = "",
1984
+ /// Muted trailing meta line ("claude · sonnet · 1m 12s").
1985
+ meta: []const u8 = "",
1986
+ /// Hairline connector from the indicator toward the next item;
1987
+ /// authors clear it on the last item.
1988
+ connector: bool = true,
1989
+ /// Whole-item press: adds a trailing chevron and binds the
1990
+ /// press to the item's root, focusable with role `listitem`.
1991
+ /// A click anywhere on the item dispatches — presses on the
1992
+ /// title/description/meta text fall through to the root
1993
+ /// (dragging still selects the text).
1994
+ on_press: ?Msg = null,
1995
+ selected: bool = false,
1996
+ };
1997
+
1998
+ /// One timeline/ledger item: leading status indicator (plus
1999
+ /// connector), a title/description/meta content column, and — when
2000
+ /// pressable — a trailing chevron with `on_press` bound to the
2001
+ /// item's root (presses on the content fall through to it).
2002
+ pub fn timelineItem(self: *Self, options: TimelineItemOptions) Node {
2003
+ const dot = options.indicator.len == 0 and options.icon.len == 0;
2004
+ const indicator = self.el(.badge, .{
2005
+ .variant = options.variant,
2006
+ .text = options.indicator,
2007
+ .icon = options.icon,
2008
+ .width = if (dot) 10 else 0,
2009
+ .height = if (dot) 10 else 0,
2010
+ }, .{});
2011
+ const lead = if (options.connector)
2012
+ self.el(.column, .{ .cross = .center, .gap = 4 }, .{
2013
+ indicator,
2014
+ self.el(.separator, .{ .grow = 1, .width = 1 }, .{}),
2015
+ })
2016
+ else
2017
+ self.el(.column, .{ .cross = .center }, .{indicator});
2018
+
2019
+ const content_nodes = self.arena.alloc(Node, 3) catch {
2020
+ self.failed = true;
2021
+ return self.el(.stack, .{}, .{});
2022
+ };
2023
+ content_nodes[0] = self.paragraph(.{}, &.{.{ .text = options.title, .weight = .bold }});
2024
+ var content_len: usize = 1;
2025
+ if (options.description.len > 0) {
2026
+ content_nodes[content_len] = self.text(.{ .wrap = true, .style_tokens = .{ .foreground = .text_muted } }, options.description);
2027
+ content_len += 1;
2028
+ }
2029
+ if (options.meta.len > 0) {
2030
+ content_nodes[content_len] = self.paragraph(.{}, &.{.{ .text = options.meta, .color = .text_muted, .scale = 0.9 }});
2031
+ content_len += 1;
2032
+ }
2033
+ const content = self.el(.column, .{ .grow = 1, .gap = 2 }, .{content_nodes[0..content_len]});
2034
+
2035
+ const item_semantics = canvas.WidgetSemantics{
2036
+ .role = .listitem,
2037
+ .label = options.title,
2038
+ .focusable = options.on_press != null,
2039
+ };
2040
+ const row_children = self.arena.alloc(Node, 3) catch {
2041
+ self.failed = true;
2042
+ return self.el(.stack, .{}, .{});
2043
+ };
2044
+ row_children[0] = lead;
2045
+ row_children[1] = content;
2046
+ var row_len: usize = 2;
2047
+ if (options.on_press != null) {
2048
+ row_children[row_len] = self.text(.{ .style_tokens = .{ .foreground = .text_muted } }, "›");
2049
+ row_len += 1;
2050
+ }
2051
+ const row_node = self.el(.row, .{ .gap = 10, .padding = 8 }, .{row_children[0..row_len]});
2052
+
2053
+ // The press binds to the item's root: a bound handler makes
2054
+ // the stack a hit target, and presses on the plain
2055
+ // title/description/meta text fall through to it (dragging
2056
+ // still selects the text). No overlay, no duplicated
2057
+ // handlers.
2058
+ return self.el(.stack, .{
2059
+ .key = options.key,
2060
+ .global_key = options.global_key,
2061
+ .selected = options.selected,
2062
+ .semantics = item_semantics,
2063
+ .on_press = options.on_press,
2064
+ }, .{row_node});
2065
+ }
2066
+
2067
+ pub const NavOptions = struct {
2068
+ /// Index of the visible page; out-of-range clamps to the last
2069
+ /// page. The app model owns this value (push = increment or
2070
+ /// append, pop = decrement) — TEA, no hidden navigation state.
2071
+ active: usize = 0,
2072
+ /// Keep inactive pages mounted but hidden: they stay laid out
2073
+ /// and keep engine-owned state (scroll offsets, text edits)
2074
+ /// across swaps, while being excluded from rendering,
2075
+ /// hit-testing, focus traversal, and semantics. Off (default)
2076
+ /// mounts only the active page — cheapest, but engine-owned
2077
+ /// state of unmounted pages is dropped and the app model must
2078
+ /// re-derive anything it wants restored.
2079
+ retain: bool = false,
2080
+ key: ?UiKey = null,
2081
+ global_key: ?UiKey = null,
2082
+ grow: f32 = 0,
2083
+ /// Layout floor for the nav's box, mirroring
2084
+ /// `ElementOptions.min_width`. Split panes clamp against their
2085
+ /// pane ROOT's `min_size`, and a chat/detail pane commonly
2086
+ /// roots in `ui.nav` — this lets the pane declare its own
2087
+ /// floor instead of the app stamping
2088
+ /// `widget.layout.min_size.width` post-build.
2089
+ min_width: f32 = 0,
2090
+ /// Container semantics; role defaults to `group`.
2091
+ semantics: canvas.WidgetSemantics = .{},
2092
+ };
2093
+
2094
+ /// Within-pane navigation stack: shows one of `pages` (index-keyed
2095
+ /// by stack position, so page identity — and with it scroll/text
2096
+ /// state reconciliation — is stable across swaps). v1 swaps
2097
+ /// instantly; there is no built-in push/pop animation. Focus does
2098
+ /// not transfer automatically: move it from `update` when changing
2099
+ /// pages if the focused widget lives on the outgoing page (hidden
2100
+ /// and unmounted pages drop out of focus traversal on their own).
2101
+ pub fn nav(self: *Self, options: NavOptions, pages: anytype) Node {
2102
+ var semantics = options.semantics;
2103
+ if (semantics.role == .none) semantics.role = .group;
2104
+ const page_nodes = self.childNodes(pages);
2105
+ if (page_nodes.len == 0) {
2106
+ return self.el(.stack, .{
2107
+ .key = options.key,
2108
+ .global_key = options.global_key,
2109
+ .grow = options.grow,
2110
+ .min_width = options.min_width,
2111
+ .semantics = semantics,
2112
+ }, .{});
2113
+ }
2114
+ const active = @min(options.active, page_nodes.len - 1);
2115
+ const mounted_len = if (options.retain) page_nodes.len else 1;
2116
+ const mounted = self.arena.alloc(Node, mounted_len) catch {
2117
+ self.failed = true;
2118
+ return self.el(.stack, .{ .semantics = semantics }, .{});
2119
+ };
2120
+ for (mounted, 0..) |*slot, offset| {
2121
+ const index = if (options.retain) offset else active;
2122
+ slot.* = page_nodes[index];
2123
+ // Page identity is its stack position unless the author
2124
+ // keyed it: distinct pages must never share a structural id
2125
+ // or engine state would bleed between them.
2126
+ if (slot.key == null) slot.key = .{ .int = @intCast(index) };
2127
+ if (index != active) slot.widget.semantics.hidden = true;
2128
+ }
2129
+ return self.el(.stack, .{
2130
+ .key = options.key,
2131
+ .global_key = options.global_key,
2132
+ .grow = options.grow,
2133
+ .min_width = options.min_width,
2134
+ .semantics = semantics,
2135
+ }, .{mounted[0..mounted_len]});
2136
+ }
2137
+
2138
+ /// Keyed list projection: one node per item, keyed by `key_fn` unless
2139
+ /// the item view assigned its own key.
2140
+ pub fn each(self: *Self, items: anytype, comptime key_fn: anytype, comptime view_fn: anytype) []const Node {
2141
+ const nodes = self.arena.alloc(Node, items.len) catch {
2142
+ self.failed = true;
2143
+ return &.{};
2144
+ };
2145
+ for (items, 0..) |*item, index| {
2146
+ var node = view_fn(self, item);
2147
+ if (node.key == null) node.key = key_fn(item);
2148
+ nodes[index] = node;
2149
+ }
2150
+ return nodes;
2151
+ }
2152
+
2153
+ /// Keyed list projection with caller context, for item views that
2154
+ /// need surrounding state (Zig has no closures to capture it).
2155
+ pub fn eachCtx(self: *Self, context: anytype, items: anytype, comptime key_fn: anytype, comptime view_fn: anytype) []const Node {
2156
+ const nodes = self.arena.alloc(Node, items.len) catch {
2157
+ self.failed = true;
2158
+ return &.{};
2159
+ };
2160
+ for (items, 0..) |*item, index| {
2161
+ var node = view_fn(self, context, item);
2162
+ if (node.key == null) node.key = key_fn(item);
2163
+ nodes[index] = node;
2164
+ }
2165
+ return nodes;
2166
+ }
2167
+
2168
+ /// Arena-allocated formatted text for widget content.
2169
+ pub fn fmt(self: *Self, comptime format: []const u8, args: anytype) []const u8 {
2170
+ return std.fmt.allocPrint(self.arena, format, args) catch {
2171
+ self.failed = true;
2172
+ return "";
2173
+ };
2174
+ }
2175
+
2176
+ /// Assign structural ids, materialize widget children, and collect
2177
+ /// the typed handler table. Container sizing is measured by the
2178
+ /// engine's `intrinsicWidgetSize` at layout time. Style token
2179
+ /// references resolve against the default tokens; themed apps use
2180
+ /// `finalizeWithTokens`.
2181
+ pub fn finalize(self: *Self, node: Node) error{OutOfMemory}!Tree {
2182
+ return self.finalizeWithTokens(node, .{});
2183
+ }
2184
+
2185
+ /// `finalize` against live design tokens: node `style_tokens`
2186
+ /// references (markup `background="surface"`, `radius="md"`, ...)
2187
+ /// resolve into concrete `widget.style` values here, unless the
2188
+ /// author already set the style field explicitly. `UiApp` calls
2189
+ /// this with `effectiveTokens()` on every rebuild, so token refs
2190
+ /// re-resolve when the theme changes.
2191
+ pub fn finalizeWithTokens(self: *Self, node: Node, tokens: canvas.DesignTokens) error{OutOfMemory}!Tree {
2192
+ if (self.failed) return error.OutOfMemory;
2193
+ const handler_capacity = countHandlers(node);
2194
+ const handlers = try self.arena.alloc(Handler, handler_capacity);
2195
+ var handler_len: usize = 0;
2196
+ const root_key = node.key orelse UiKey{ .index = 0 };
2197
+ var key_trail = ui_provenance.KeyTrail{};
2198
+ const root = try self.finalizeNode(node, root_id_seed, root_key, handlers, &handler_len, &tokens, &key_trail);
2199
+ return .{
2200
+ .root = root,
2201
+ .handlers = handlers[0..handler_len],
2202
+ .context_menu_fallback = self.context_menu_fallback_result,
2203
+ };
2204
+ }
2205
+
2206
+ fn finalizeNode(
2207
+ self: *Self,
2208
+ node: Node,
2209
+ parent_id: ObjectId,
2210
+ key: UiKey,
2211
+ handlers: []Handler,
2212
+ handler_len: *usize,
2213
+ tokens: *const canvas.DesignTokens,
2214
+ key_trail: *ui_provenance.KeyTrail,
2215
+ ) error{OutOfMemory}!Widget {
2216
+ var widget = node.widget;
2217
+ warnUncoveredText(widget.kind, widget.text);
2218
+ warnUncoveredText(widget.kind, widget.placeholder);
2219
+ warnInertWrap(widget.kind, node.wrap);
2220
+ warnTextSizeKind(widget.kind, widget.size);
2221
+ applyStyleTokens(&widget.style, node.style_tokens, tokens);
2222
+ // Opt-in text wrapping reuses the span paragraph machinery: a
2223
+ // wrapped text leaf becomes a single-span paragraph over its
2224
+ // own bytes (the span invariant: span text subslices
2225
+ // `widget.text`), so wrapping, intrinsic sizing, wrapped
2226
+ // height reservation, and rendering are all the existing span
2227
+ // path — no forked text pipeline.
2228
+ if (node.wrap == true and widget.kind == .text and widget.spans.len == 0 and widget.text.len > 0) {
2229
+ const spans = try self.arena.alloc(canvas.TextSpan, 1);
2230
+ spans[0] = .{ .text = widget.text };
2231
+ widget.spans = spans;
2232
+ }
2233
+ // An explicit `wrap = false` records the author's single-line
2234
+ // choice. Plain leaves paint one line (TextWrap.none) either
2235
+ // way, matching the single-line measurement both layout paths
2236
+ // already perform; overflow policy (`overflow`, trailing
2237
+ // ellipsis by default) decides what happens past the frame.
2238
+ // Span paragraphs keep wrapping.
2239
+ if (node.wrap == false and widget.kind == .text and widget.spans.len == 0) {
2240
+ widget.text_no_wrap = true;
2241
+ }
2242
+ widget.id = if (node.global_key) |global_key|
2243
+ structuralId(global_id_seed, widget.kind, global_key)
2244
+ else
2245
+ structuralId(parent_id, widget.kind, key);
2246
+ // Provenance record (write-back's read half): this is the one
2247
+ // point where the markup-stamped source and the just-assigned
2248
+ // structural id are both in hand. Explicit keys (loop item
2249
+ // identity, author key=/global-key=) join the trail so the
2250
+ // record says WHICH iteration of a for-body this widget is;
2251
+ // auto index keys carry position, not identity, and stay out.
2252
+ const trail_pushed = if (self.provenance_sink != null and (node.global_key != null or node.key != null))
2253
+ key_trail.push(provenanceKey(node.global_key orelse key))
2254
+ else
2255
+ false;
2256
+ defer if (trail_pushed) key_trail.pop();
2257
+ if (self.provenance_sink) |sink| {
2258
+ if (node.source) |source| {
2259
+ sink.record(widget.id, source, key_trail.items(), key_trail.truncated);
2260
+ }
2261
+ }
2262
+ // Typed handlers imply the matching accessibility actions, the
2263
+ // same way a stringly `command` does for engine-owned dispatch.
2264
+ if (node.on_press != null) widget.semantics.actions.press = true;
2265
+ // A double-press handler makes the element pressable too:
2266
+ // the double-click's first release must land somewhere, and
2267
+ // an element that acts on double click without claiming
2268
+ // presses would be unreachable by pointer at all.
2269
+ if (node.on_double_press != null) widget.semantics.actions.press = true;
2270
+ if (node.on_toggle != null) widget.semantics.actions.toggle = true;
2271
+ // A hold handler makes the element pressable (hit target +
2272
+ // press claimer), like on_press: the hold gesture starts as a
2273
+ // press, and the classic list-row shape (press to open, hold
2274
+ // for the menu) pairs the two on one element.
2275
+ if (node.on_hold != null) widget.semantics.actions.press = true;
2276
+ if (node.on_input != null) widget.semantics.actions.set_text = true;
2277
+ if (widget.kind == .slider and (node.on_value != null or node.on_change != null)) {
2278
+ widget.semantics.actions.increment = true;
2279
+ widget.semantics.actions.decrement = true;
2280
+ }
2281
+ if (widget.kind == .split and node.nodes.len == 2) {
2282
+ // Synthesize the draggable divider between the two panes.
2283
+ // Both markup engines build through this finalize, so the
2284
+ // handle exists everywhere a split does. Pane keys keep
2285
+ // their author-facing indices (0 and 1) so their
2286
+ // structural ids never depend on the synthesized child;
2287
+ // panes clip their content so the drag's optimistic echo
2288
+ // (and a pane narrower than its content) never paints
2289
+ // into the neighbor.
2290
+ const child_widgets = try self.arena.alloc(Widget, 3);
2291
+ child_widgets[0] = try self.finalizeNode(node.nodes[0], widget.id, node.nodes[0].key orelse UiKey{ .index = 0 }, handlers, handler_len, tokens, key_trail);
2292
+ child_widgets[1] = splitDividerWidget(widget);
2293
+ child_widgets[2] = try self.finalizeNode(node.nodes[1], widget.id, node.nodes[1].key orelse UiKey{ .index = 1 }, handlers, handler_len, tokens, key_trail);
2294
+ child_widgets[0].layout.clip_content = true;
2295
+ child_widgets[2].layout.clip_content = true;
2296
+ widget.children = child_widgets;
2297
+ } else if (node.nodes.len > 0) {
2298
+ const child_widgets = try self.arena.alloc(Widget, node.nodes.len);
2299
+ for (node.nodes, 0..) |child, index| {
2300
+ const child_key = child.key orelse UiKey{ .index = index };
2301
+ child_widgets[index] = try self.finalizeNode(child, widget.id, child_key, handlers, handler_len, tokens, key_trail);
2302
+ }
2303
+ widget.children = child_widgets;
2304
+ }
2305
+ appendHandler(handlers, handler_len, widget.id, .press, node.on_press);
2306
+ appendHandler(handlers, handler_len, widget.id, .double_press, node.on_double_press);
2307
+ appendHandler(handlers, handler_len, widget.id, .toggle, node.on_toggle);
2308
+ appendHandler(handlers, handler_len, widget.id, .change, node.on_change);
2309
+ appendHandler(handlers, handler_len, widget.id, .submit, node.on_submit);
2310
+ appendHandler(handlers, handler_len, widget.id, .dismiss, node.on_dismiss);
2311
+ appendHandler(handlers, handler_len, widget.id, .hold, node.on_hold);
2312
+ appendHandler(handlers, handler_len, widget.id, .reach_end, node.on_reach_end);
2313
+ appendHandler(handlers, handler_len, widget.id, .reach_start, node.on_reach_start);
2314
+ if (node.on_input) |make| {
2315
+ handlers[handler_len.*] = .{ .id = widget.id, .event = .input, .action = .{ .input = make } };
2316
+ handler_len.* += 1;
2317
+ }
2318
+ if (node.on_value) |make| {
2319
+ handlers[handler_len.*] = .{ .id = widget.id, .event = .change, .action = .{ .value = make } };
2320
+ handler_len.* += 1;
2321
+ }
2322
+ if (node.on_resize) |make| {
2323
+ handlers[handler_len.*] = .{ .id = widget.id, .event = .resize, .action = .{ .value = make } };
2324
+ handler_len.* += 1;
2325
+ }
2326
+ if (node.on_scroll) |make| {
2327
+ handlers[handler_len.*] = .{ .id = widget.id, .event = .scroll, .action = .{ .scroll = make } };
2328
+ handler_len.* += 1;
2329
+ }
2330
+ if (node.context_menu.len > 0) {
2331
+ // Split the declared items: labels ride the widget (the
2332
+ // runtime builds the platform request from them), messages
2333
+ // land in the handler table keyed by item index.
2334
+ const items = try self.arena.alloc(canvas.WidgetContextMenuItem, node.context_menu.len);
2335
+ const msgs = try self.arena.alloc(?Msg, node.context_menu.len);
2336
+ for (node.context_menu, 0..) |item, index| {
2337
+ items[index] = .{
2338
+ .label = item.label,
2339
+ .enabled = item.enabled,
2340
+ .separator = item.separator,
2341
+ };
2342
+ msgs[index] = item.msg;
2343
+ }
2344
+ widget.context_menu = items;
2345
+ handlers[handler_len.*] = .{ .id = widget.id, .event = .context_menu, .action = .{ .context_menu = msgs } };
2346
+ handler_len.* += 1;
2347
+ // The presentation fallback: on a host without a native
2348
+ // menu presenter the app loop names the widget whose
2349
+ // declared menu is open, and finalize mounts that menu as
2350
+ // an anchored canvas surface — the same items, presented
2351
+ // with the anchored-surface machinery (Escape/outside
2352
+ // dismissal, late z-pass) instead of the OS menu.
2353
+ if (widget.id == self.context_menu_fallback_target) {
2354
+ try self.appendContextMenuFallbackSurface(&widget, node.context_menu);
2355
+ }
2356
+ }
2357
+ return widget;
2358
+ }
2359
+
2360
+ /// Synthesize the anchored context-menu fallback surface as a
2361
+ /// child of `widget`: a `dropdown_menu` floating below the target
2362
+ /// with one `menu_item` per declared item (`separator`s keep
2363
+ /// their slots). Items carry press semantics but no handler
2364
+ /// entries — the app loop maps their presses through the
2365
+ /// target's existing `.context_menu` handler, the same entry a
2366
+ /// native selection resolves.
2367
+ fn appendContextMenuFallbackSurface(self: *Self, widget: *Widget, declared: []const ContextMenuItem) error{OutOfMemory}!void {
2368
+ if (declared.len == 0) return;
2369
+ const surface_id = structuralId(widget.id, .dropdown_menu, UiKey{ .str = "context-menu" });
2370
+ const item_widgets = try self.arena.alloc(Widget, declared.len);
2371
+ const item_ids = try self.arena.alloc(ObjectId, declared.len);
2372
+ for (declared, 0..) |item, index| {
2373
+ if (item.separator) {
2374
+ item_widgets[index] = .{
2375
+ .kind = .separator,
2376
+ .id = structuralId(surface_id, .separator, UiKey{ .int = @intCast(index) }),
2377
+ };
2378
+ item_ids[index] = 0;
2379
+ continue;
2380
+ }
2381
+ var item_widget = Widget{
2382
+ .kind = .menu_item,
2383
+ .id = structuralId(surface_id, .menu_item, UiKey{ .int = @intCast(index) }),
2384
+ .text = item.label,
2385
+ .state = .{ .disabled = !item.enabled },
2386
+ };
2387
+ item_widget.semantics.actions.press = item.enabled;
2388
+ item_widgets[index] = item_widget;
2389
+ item_ids[index] = item_widget.id;
2390
+ }
2391
+ var surface = Widget{
2392
+ .kind = .dropdown_menu,
2393
+ .id = surface_id,
2394
+ .semantics = .{ .label = "Context menu" },
2395
+ .children = item_widgets,
2396
+ };
2397
+ surface.layout.anchor = .{ .placement = .below, .alignment = .start };
2398
+ const children = try self.arena.alloc(Widget, widget.children.len + 1);
2399
+ @memcpy(children[0..widget.children.len], widget.children);
2400
+ children[widget.children.len] = surface;
2401
+ widget.children = children;
2402
+ self.context_menu_fallback_result = .{
2403
+ .target_id = widget.id,
2404
+ .surface_id = surface_id,
2405
+ .item_ids = item_ids,
2406
+ };
2407
+ }
2408
+
2409
+ fn appendHandler(handlers: []Handler, handler_len: *usize, id: ObjectId, event: UiHandlerEvent, msg: ?Msg) void {
2410
+ const value = msg orelse return;
2411
+ handlers[handler_len.*] = .{ .id = id, .event = event, .action = .{ .message = value } };
2412
+ handler_len.* += 1;
2413
+ }
2414
+
2415
+ fn countHandlers(node: Node) usize {
2416
+ var total: usize = 0;
2417
+ if (node.on_press != null) total += 1;
2418
+ if (node.on_double_press != null) total += 1;
2419
+ if (node.on_toggle != null) total += 1;
2420
+ if (node.on_change != null) total += 1;
2421
+ if (node.on_submit != null) total += 1;
2422
+ if (node.on_dismiss != null) total += 1;
2423
+ if (node.on_hold != null) total += 1;
2424
+ if (node.on_reach_end != null) total += 1;
2425
+ if (node.on_reach_start != null) total += 1;
2426
+ if (node.on_input != null) total += 1;
2427
+ if (node.on_value != null) total += 1;
2428
+ if (node.on_resize != null) total += 1;
2429
+ if (node.on_scroll != null) total += 1;
2430
+ if (node.context_menu.len > 0) total += 1;
2431
+ for (node.nodes) |child| total += countHandlers(child);
2432
+ return total;
2433
+ }
2434
+
2435
+ fn childNodes(self: *Self, children: anytype) []const Node {
2436
+ const Children = @TypeOf(children);
2437
+ if (Children == Node) {
2438
+ const nodes = self.arena.alloc(Node, 1) catch {
2439
+ self.failed = true;
2440
+ return &.{};
2441
+ };
2442
+ nodes[0] = children;
2443
+ return nodes;
2444
+ }
2445
+ if (Children == []const Node or Children == []Node) {
2446
+ // Copy rather than alias: callers may pass slices of locals
2447
+ // that would not outlive finalize.
2448
+ if (children.len == 0) return &.{};
2449
+ const nodes = self.arena.alloc(Node, children.len) catch {
2450
+ self.failed = true;
2451
+ return &.{};
2452
+ };
2453
+ @memcpy(nodes, children);
2454
+ return nodes;
2455
+ }
2456
+ const info = @typeInfo(Children);
2457
+ if (info != .@"struct" or !info.@"struct".is_tuple) {
2458
+ @compileError("children must be a Node, a []const Node, or a tuple of those");
2459
+ }
2460
+ var total: usize = 0;
2461
+ inline for (children) |child| {
2462
+ total += if (@TypeOf(child) == Node) 1 else child.len;
2463
+ }
2464
+ if (total == 0) return &.{};
2465
+ const nodes = self.arena.alloc(Node, total) catch {
2466
+ self.failed = true;
2467
+ return &.{};
2468
+ };
2469
+ var index: usize = 0;
2470
+ inline for (children) |child| {
2471
+ if (@TypeOf(child) == Node) {
2472
+ nodes[index] = child;
2473
+ index += 1;
2474
+ } else {
2475
+ for (child) |entry| {
2476
+ nodes[index] = entry;
2477
+ index += 1;
2478
+ }
2479
+ }
2480
+ }
2481
+ return nodes;
2482
+ }
2483
+
2484
+ /// The ergonomic per-kind layout defaults
2485
+ /// (`canvas.widgetKindDefaultLayout`): a bare `.card` carries
2486
+ /// the house content padding, a bare `.tabs` hugs its triggers
2487
+ /// like a TabsList. Only padding/gap (and a non-stretch cross
2488
+ /// default) apply, each ONLY when the author left that field at
2489
+ /// zero — per field, so an explicit trigger gap keeps the
2490
+ /// TabsList hug (dropping it leaves triggers flush against the
2491
+ /// container's rounded corners) and explicit padding keeps the
2492
+ /// default gap. Explicit spacing always wins for its own field.
2493
+ fn applyKindDefaultLayout(kind: WidgetKind, options: ElementOptions, layout: *canvas.WidgetLayoutStyle) void {
2494
+ const defaults = canvas.widgetKindDefaultLayout(kind, options.size) orelse return;
2495
+ if (options.padding == 0) layout.padding = defaults.padding;
2496
+ if (options.gap == 0) layout.gap = defaults.gap;
2497
+ if (layout.cross_alignment == .stretch and defaults.cross_alignment != .stretch) {
2498
+ layout.cross_alignment = defaults.cross_alignment;
2499
+ }
2500
+ }
2501
+
2502
+ fn widgetFromOptions(kind: WidgetKind, options: ElementOptions) Widget {
2503
+ warnStackContainerGap(kind, options.gap);
2504
+ warnUnknownIconName(options.icon);
2505
+ var widget: Widget = .{
2506
+ .kind = kind,
2507
+ .frame = options.frame,
2508
+ .opacity = options.opacity,
2509
+ .transform = options.transform,
2510
+ .text = options.text,
2511
+ .placeholder = options.placeholder,
2512
+ .icon = options.icon,
2513
+ .icon_placement = options.icon_placement,
2514
+ .text_alignment = options.text_alignment,
2515
+ .text_overflow = options.overflow,
2516
+ .autofocus = options.autofocus,
2517
+ .image_id = options.image,
2518
+ .value = options.value,
2519
+ .variant = options.variant,
2520
+ .size = options.size,
2521
+ .state = .{
2522
+ .selected = options.checked or options.selected,
2523
+ .expanded = options.expanded,
2524
+ .disabled = options.disabled,
2525
+ },
2526
+ .layout = .{
2527
+ .padding = .{
2528
+ .top = options.padding,
2529
+ .right = options.padding,
2530
+ .bottom = options.padding,
2531
+ .left = options.padding,
2532
+ },
2533
+ .gap = options.gap,
2534
+ .grow = options.grow,
2535
+ .main_alignment = options.main,
2536
+ .cross_alignment = options.cross,
2537
+ .columns = options.columns,
2538
+ .anchor = if (options.anchor) |placement| .{
2539
+ .placement = placement,
2540
+ .alignment = options.anchor_alignment,
2541
+ .offset = options.anchor_offset,
2542
+ } else null,
2543
+ .virtualized = options.virtualized,
2544
+ .virtual_item_extent = options.virtual_item_extent,
2545
+ .virtual_overscan = options.virtual_overscan,
2546
+ .virtual_item_count = options.virtual_item_count,
2547
+ .virtual_first_index = options.virtual_first_index,
2548
+ .virtual_anchor_index = options.virtual_anchor_index,
2549
+ .virtual_anchor_extent = options.virtual_anchor_extent,
2550
+ .virtual_total_extent = options.virtual_total_extent,
2551
+ .min_size = .{ .width = @max(options.width, options.min_width), .height = options.height },
2552
+ // Explicit sizes are definite (min AND max). Resizable
2553
+ // is the exception: width documents the initial width
2554
+ // and the engine's drag handle keeps writing larger
2555
+ // frames past it.
2556
+ .max_size = if (kind == .resizable) .{} else .{ .width = options.width, .height = options.height },
2557
+ },
2558
+ .style = options.style,
2559
+ .semantics = options.semantics,
2560
+ .window_drag = options.window_drag,
2561
+ .overscroll = options.overscroll,
2562
+ .resize_duration_ms = options.resize_duration,
2563
+ .resize_easing = options.resize_easing,
2564
+ .resize_origin = options.resize_origin,
2565
+ };
2566
+ applyKindDefaultLayout(kind, options, &widget.layout);
2567
+ return widget;
2568
+ }
2569
+
2570
+ /// The synthesized drag handle between a split's panes: the ARIA
2571
+ /// separator, focusable, mirroring the split's disabled state.
2572
+ /// Its `value` is stamped with the EFFECTIVE fraction by the
2573
+ /// layout pass; the authored value seeds keyboard steps before
2574
+ /// the first layout.
2575
+ fn splitDividerWidget(split_widget: Widget) Widget {
2576
+ return .{
2577
+ .kind = .split_divider,
2578
+ .id = structuralId(split_widget.id, .split_divider, UiKey{ .str = "divider" }),
2579
+ .value = split_widget.value,
2580
+ .state = .{ .disabled = split_widget.state.disabled },
2581
+ .semantics = .{ .label = "Split divider" },
2582
+ };
2583
+ }
2584
+ };
2585
+ }
2586
+
2587
+ /// The structural id a widget with `global_key` gets, computable without
2588
+ /// the parent chain: the seam the app loop uses to resolve a windowed
2589
+ /// virtual list's retained scroll state by its declared identity.
2590
+ pub fn globalWidgetId(kind: WidgetKind, key: UiKey) ObjectId {
2591
+ return structuralId(global_id_seed, kind, key);
2592
+ }
2593
+
2594
+ pub fn uiKey(value: anytype) UiKey {
2595
+ const Value = @TypeOf(value);
2596
+ return switch (@typeInfo(Value)) {
2597
+ .int, .comptime_int => .{ .int = @intCast(value) },
2598
+ .pointer => .{ .str = value },
2599
+ else => @compileError("uiKey supports integers and byte slices"),
2600
+ };
2601
+ }
2602
+
2603
+ /// Per-item key for the Nth node a multi-child `for` body emits. Slot 0
2604
+ /// keeps the plain item key, so single-node items (the common case, and
2605
+ /// every pre-multi-child document) produce byte-identical structural ids.
2606
+ /// Later slots append a 0x1f-separated slot suffix: the same item key
2607
+ /// still groups the fragment, while same-kind siblings within one item
2608
+ /// stay distinct. Both markup engines share this, keeping their ids in
2609
+ /// parity.
2610
+ pub fn forSlotKey(arena: std.mem.Allocator, base: UiKey, slot: usize) error{OutOfMemory}!UiKey {
2611
+ if (slot == 0) return base;
2612
+ return switch (base) {
2613
+ .index => |value| .{ .str = try std.fmt.allocPrint(arena, "{d}\x1f{d}", .{ value, slot }) },
2614
+ .int => |value| .{ .str = try std.fmt.allocPrint(arena, "{d}\x1f{d}", .{ value, slot }) },
2615
+ .str => |value| .{ .str = try std.fmt.allocPrint(arena, "{s}\x1f{d}", .{ value, slot }) },
2616
+ };
2617
+ }
2618
+
2619
+ /// `UiKey` in the provenance module's std-only mirror, for sink records.
2620
+ fn provenanceKey(key: UiKey) ui_provenance.Key {
2621
+ return switch (key) {
2622
+ .index => |value| .{ .index = value },
2623
+ .int => |value| .{ .int = value },
2624
+ .str => |value| .{ .str = value },
2625
+ };
2626
+ }
2627
+
2628
+ fn findWidgetIn(widget: Widget, id: ObjectId) ?Widget {
2629
+ if (widget.id == id) return widget;
2630
+ for (widget.children) |child| {
2631
+ if (findWidgetIn(child, id)) |found| return found;
2632
+ }
2633
+ return null;
2634
+ }
2635
+
2636
+ fn isTextEntryWidget(widget: Widget) bool {
2637
+ // The one text-entry kind set, shared with the ui-app key-fallback
2638
+ // gate (`canvas.isWidgetTextEntry`) — one definition is what makes
2639
+ // the "typing must stay typing" rule structural instead of assumed.
2640
+ return canvas.isWidgetTextEntry(widget);
2641
+ }
2642
+
2643
+ fn isSubmitKeyboard(widget: Widget, keyboard: canvas.WidgetKeyboardEvent) bool {
2644
+ if (widget.state.disabled or keyboard.phase != .key_down) return false;
2645
+ if (!std.ascii.eqlIgnoreCase(keyboard.key, "enter")) return false;
2646
+ return switch (widget.kind) {
2647
+ // Single-line entry: plain Enter submits.
2648
+ .text_field, .search_field, .input, .combobox => !keyboard.modifiers.hasNavigationModifier(),
2649
+ // Multi-line entry: Enter edits (newline), so submit rides the
2650
+ // primary chord — cmd+Enter on macOS, ctrl+Enter elsewhere.
2651
+ // Shift/alt variants stay free for apps.
2652
+ .textarea => keyboard.modifiers.hasCommandModifier() and !keyboard.modifiers.alt and !keyboard.modifiers.shift,
2653
+ // List rows: plain Enter is the row's primary action when the
2654
+ // app binds `on_submit` (play the track, open the record); the
2655
+ // select activation keeps Space. `msgForKeyboard` resolves the
2656
+ // preference — this predicate only says Enter QUALIFIES.
2657
+ .list_item => !keyboard.modifiers.hasNavigationModifier(),
2658
+ else => false,
2659
+ };
2660
+ }
2661
+
2662
+ fn structuralId(parent_id: ObjectId, kind: WidgetKind, key: UiKey) ObjectId {
2663
+ var hasher = std.hash.Wyhash.init(parent_id);
2664
+ // The kind's STABLE code, never its ordinal: reordering `WidgetKind`
2665
+ // must never renumber retained ids, automation targets, or journal
2666
+ // anchors. The id algorithm (seed, code, key-tag discipline) is part
2667
+ // of the versioned document schema (`ui_schema.schema_version`).
2668
+ const kind_code: u16 = canvas.widgetKindCode(kind);
2669
+ hasher.update(std.mem.asBytes(&kind_code));
2670
+ switch (key) {
2671
+ .index => |index| {
2672
+ hasher.update(&[_]u8{0});
2673
+ hasher.update(std.mem.asBytes(&@as(u64, index)));
2674
+ },
2675
+ .int => |value| {
2676
+ hasher.update(&[_]u8{1});
2677
+ hasher.update(std.mem.asBytes(&value));
2678
+ },
2679
+ .str => |value| {
2680
+ hasher.update(&[_]u8{2});
2681
+ hasher.update(value);
2682
+ },
2683
+ }
2684
+ const value = hasher.final();
2685
+ return if (value == 0) zero_id_fallback else value;
2686
+ }