@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,1031 @@
1
+ //! `native_sdk.markdown` — a GitHub-flavored-markdown subset mapped onto
2
+ //! the widget tree + inline span model.
3
+ //!
4
+ //! `Markdown(Msg).view(ui, source, options)` returns an ordinary builder
5
+ //! node usable inside any hand-written `view` fn: blocks become the same
6
+ //! widgets an author would compose by hand (columns, rows, panels,
7
+ //! checkboxes, separators) and inline styling becomes span paragraphs, so
8
+ //! layout, theming, semantics, and hit-testing all come from the existing
9
+ //! engine.
10
+ //!
11
+ //! Supported blocks: `#`/`##`/`###` headings (deeper levels clamp to h3),
12
+ //! paragraphs, bullet/ordered/task lists (nesting up to
13
+ //! `max_markdown_list_depth` by two-space indent), fenced code blocks,
14
+ //! `>` blockquotes, horizontal rules, GFM pipe tables (header row +
15
+ //! delimiter row + body rows onto `table`/`data_row`/`data_cell` widgets;
16
+ //! `:---`/`:--:`/`---:` delimiter cells set per-column start/center/end
17
+ //! text alignment, header cells render bold, and every cell runs the full
18
+ //! inline span grammar including links), and `<details>`/`<summary>`.
19
+ //! Supported inlines: `**bold**`/`__bold__`, `*italic*`/`_italic_`,
20
+ //! `` `code` ``, `~~strikethrough~~`, `[text](url)` links, `<url>`
21
+ //! autolinks, bare `http(s)://` URLs at word boundaries (GFM-style
22
+ //! autolink extension, trailing punctuation trimmed), `#123` issue
23
+ //! references (opt-in via `Options.issue_link_base`, since resolving a
24
+ //! ref needs repo context), and `![alt](url)` images (rendered as their
25
+ //! alt text).
26
+ //!
27
+ //! Deliberately unsupported in v1 (rendered as plain paragraph text, never
28
+ //! a build failure): setext headings, indented code blocks, backslash
29
+ //! escapes (except `\|` inside table rows, which GFM needs to put a pipe
30
+ //! in a cell), reference-style links, raw HTML other than
31
+ //! details/summary, and footnotes. Malformed input degrades to literal
32
+ //! text — a pipe block whose delimiter row is missing or does not match
33
+ //! the header's column count renders as plain paragraphs, and tables
34
+ //! wider than `max_markdown_table_columns` degrade the same way rather
35
+ //! than silently dropping columns.
36
+ //!
37
+ //! State model (Elm-style, no hidden state):
38
+ //! - Task-list checkboxes render as disabled checkboxes — display only.
39
+ //! - `<details>` blocks are collapsible through the CALLER's model: pass
40
+ //! `details_expanded` (flags indexed by details-block order in the
41
+ //! document) and `on_details` (a Msg constructor receiving that index).
42
+ //! The recommended wiring is a bounded bool array in the model that
43
+ //! `update` toggles on the details message:
44
+ //!
45
+ //! ```zig
46
+ //! const Msg = union(enum) { open_url: []const u8, toggle_details: usize };
47
+ //! // model.details_expanded: [8]bool = .{false} ** 8;
48
+ //! markdown.view(ui, source, .{
49
+ //! .on_link = Ui.linkMsg(.open_url),
50
+ //! .on_details = Md.detailsMsg(.toggle_details),
51
+ //! .details_expanded = &model.details_expanded,
52
+ //! });
53
+ //! ```
54
+ //!
55
+ //! Std-only, allocator-explicit: every allocation goes through the
56
+ //! builder's arena, and node/span buffers are capacity-bounded; documents
57
+ //! that exceed a capacity truncate deterministically.
58
+
59
+ const std = @import("std");
60
+ const geometry = @import("geometry");
61
+ const canvas = @import("root.zig");
62
+ const text_spans = @import("text_spans.zig");
63
+ const ui_builder = @import("ui.zig");
64
+
65
+ const TextSpan = text_spans.TextSpan;
66
+
67
+ /// Capacity conventions (`canvas_limits` style): blocks per container,
68
+ /// list nesting depth, and details blocks per document. Overflow keeps
69
+ /// the tree valid and drops trailing content.
70
+ pub const max_markdown_blocks_per_container: usize = 64;
71
+ pub const max_markdown_list_items_per_list: usize = 64;
72
+ pub const max_markdown_list_depth: usize = 4;
73
+ pub const max_markdown_details_per_document: usize = 16;
74
+ pub const max_markdown_table_columns: usize = 8;
75
+ /// Rows per table including the header; trailing rows drop deterministically.
76
+ pub const max_markdown_table_rows: usize = 64;
77
+ /// Joined bytes per paragraph or blockquote (consecutive source lines
78
+ /// collapse into one text widget). Sized generously past real GitHub
79
+ /// prose — paragraphs beyond a couple of KiB are pathological input —
80
+ /// and well under the runtime's per-view widget-text budget, so a
81
+ /// hostile megabyte-long "paragraph" truncates deterministically here
82
+ /// instead of ballooning the build arena. The block's remaining lines
83
+ /// are still consumed, so parsing resumes at the next block.
84
+ pub const max_markdown_paragraph_bytes: usize = 8192;
85
+
86
+ /// Heading scales relative to the body typography token (GitHub's em
87
+ /// ladder), applied through the span `scale` channel so heading pixel
88
+ /// sizes stay derived from live tokens.
89
+ pub const heading_scales = [_]f32{ 2.0, 1.5, 1.25 };
90
+
91
+ pub fn Markdown(comptime Msg: type) type {
92
+ return struct {
93
+ pub const Ui = ui_builder.Ui(Msg);
94
+ const Node = Ui.Node;
95
+
96
+ pub const Options = struct {
97
+ /// Msg constructor for link presses (pair with `Ui.linkMsg`).
98
+ /// Null renders links styled but inert.
99
+ on_link: ?Ui.LinkMsgFn = null,
100
+ /// Msg constructor for `<details>` summary presses; receives
101
+ /// the details block's document-order index. Pair with
102
+ /// `detailsMsg`. Null renders summaries inert.
103
+ on_details: ?*const fn (index: usize) Msg = null,
104
+ /// Expanded flags for `<details>` blocks in document order;
105
+ /// blocks beyond the slice render collapsed.
106
+ details_expanded: []const bool = &.{},
107
+ /// Non-null turns `#123` issue references at word boundaries
108
+ /// (issue-tracker-client semantics: not preceded by a word
109
+ /// byte, `/`, or `&`; digits end at a word boundary) into
110
+ /// link spans whose target is this prefix followed by the
111
+ /// number — an app scheme (`"ghissue://"`) or a web base
112
+ /// (`"https://github.com/owner/repo/issues/"`). The press
113
+ /// dispatches through `on_link` like any other link. Null
114
+ /// keeps refs as plain text (they need repo context to
115
+ /// resolve, so there is no default).
116
+ issue_link_base: ?[]const u8 = null,
117
+ };
118
+
119
+ /// Comptime message constructor for `on_details`:
120
+ /// `detailsMsg(.toggle_details)` yields a function building
121
+ /// `Msg{ .toggle_details = index }`.
122
+ pub fn detailsMsg(comptime tag: std.meta.Tag(Msg)) *const fn (index: usize) Msg {
123
+ return struct {
124
+ fn make(index: usize) Msg {
125
+ return @unionInit(Msg, @tagName(tag), index);
126
+ }
127
+ }.make;
128
+ }
129
+
130
+ /// Map a markdown source into a widget subtree. Never fails: arena
131
+ /// exhaustion latches on the builder (surfacing from `finalize`,
132
+ /// the existing convention) and malformed markdown degrades to
133
+ /// plain text.
134
+ pub fn view(ui: *Ui, source: []const u8, options: Options) Node {
135
+ var builder = Builder{ .ui = ui, .options = options };
136
+ var lines = LineIterator{ .source = source };
137
+ const blocks = builder.parseBlocks(&lines, .document);
138
+ return ui.column(.{ .gap = 12 }, blocks);
139
+ }
140
+
141
+ const BlockScope = enum {
142
+ document,
143
+ details,
144
+ };
145
+
146
+ const Builder = struct {
147
+ ui: *Ui,
148
+ options: Options,
149
+ details_count: usize = 0,
150
+
151
+ fn allocNodes(self: *Builder) []Node {
152
+ return self.ui.arena.alloc(Node, max_markdown_blocks_per_container) catch {
153
+ self.ui.failed = true;
154
+ return &.{};
155
+ };
156
+ }
157
+
158
+ fn parseBlocks(self: *Builder, lines: *LineIterator, scope: BlockScope) []const Node {
159
+ const nodes = self.allocNodes();
160
+ if (nodes.len == 0) return &.{};
161
+ var len: usize = 0;
162
+
163
+ while (lines.peek()) |line| {
164
+ const trimmed = std.mem.trim(u8, line, " \t");
165
+ if (scope == .details and std.ascii.startsWithIgnoreCase(trimmed, "</details>")) {
166
+ _ = lines.next();
167
+ break;
168
+ }
169
+ if (trimmed.len == 0) {
170
+ _ = lines.next();
171
+ continue;
172
+ }
173
+ const node = self.parseBlock(lines) orelse continue;
174
+ if (len >= nodes.len) break;
175
+ nodes[len] = node;
176
+ len += 1;
177
+ }
178
+ return nodes[0..len];
179
+ }
180
+
181
+ fn parseBlock(self: *Builder, lines: *LineIterator) ?Node {
182
+ const line = lines.peek() orelse return null;
183
+ const trimmed = std.mem.trim(u8, line, " \t");
184
+
185
+ if (std.mem.startsWith(u8, trimmed, "```")) return self.parseCodeFence(lines);
186
+ if (headingLevel(trimmed)) |level| {
187
+ _ = lines.next();
188
+ return self.heading(level, std.mem.trim(u8, trimmed[level..], " \t#"));
189
+ }
190
+ if (isHorizontalRule(trimmed)) {
191
+ _ = lines.next();
192
+ return self.ui.separator(.{});
193
+ }
194
+ if (std.mem.startsWith(u8, trimmed, ">")) return self.parseBlockquote(lines);
195
+ if (listMarker(line)) |_| return self.parseList(lines, 0, 0);
196
+ if (std.ascii.startsWithIgnoreCase(trimmed, "<details")) return self.parseDetails(lines);
197
+ if (isTableStart(lines)) return self.parseTable(lines);
198
+ return self.parseParagraph(lines);
199
+ }
200
+
201
+ // ------------------------------------------------------ blocks
202
+
203
+ fn heading(self: *Builder, level: usize, content: []const u8) Node {
204
+ const scale = heading_scales[@min(level, heading_scales.len) - 1];
205
+ var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
206
+ const parsed = self.parseInline(content, .{ .weight = .bold, .scale = scale }, &spans);
207
+ return self.ui.paragraph(.{ .on_link = self.options.on_link }, parsed);
208
+ }
209
+
210
+ fn parseParagraph(self: *Builder, lines: *LineIterator) ?Node {
211
+ const text = self.collectJoined(lines, .paragraph);
212
+ if (text.len == 0) return null;
213
+ return self.paragraphNode(text, .{});
214
+ }
215
+
216
+ const JoinKind = enum { paragraph, blockquote };
217
+
218
+ /// The next joined piece of a paragraph or blockquote at
219
+ /// `lines`' current position, or null when the block ends
220
+ /// there. `joined_len` is the text joined so far (the
221
+ /// paragraph break rules only apply once the block has
222
+ /// content). Tables interrupt paragraphs (GFM): a header
223
+ /// line followed by a matching delimiter row starts a table.
224
+ fn joinPiece(lines: *LineIterator, kind: JoinKind, joined_len: usize) ?[]const u8 {
225
+ const line = lines.peek() orelse return null;
226
+ const trimmed = std.mem.trim(u8, line, " \t");
227
+ switch (kind) {
228
+ .blockquote => {
229
+ if (!std.mem.startsWith(u8, trimmed, ">")) return null;
230
+ var inner = trimmed[1..];
231
+ if (std.mem.startsWith(u8, inner, " ")) inner = inner[1..];
232
+ return std.mem.trim(u8, inner, " \t");
233
+ },
234
+ .paragraph => {
235
+ if (trimmed.len == 0) return null;
236
+ if (joined_len > 0 and (startsNewBlock(line) or isTableStart(lines))) return null;
237
+ return trimmed;
238
+ },
239
+ }
240
+ }
241
+
242
+ /// Join a block's consecutive lines with single spaces into
243
+ /// ONE arena allocation. Measuring first keeps hostile input
244
+ /// linear: re-joining per line is quadratic in both time and
245
+ /// arena memory (a megabyte-long single paragraph used to
246
+ /// demand gigabytes). Joined text truncates deterministically
247
+ /// at `max_markdown_paragraph_bytes`; the block's remaining
248
+ /// lines are still consumed either way.
249
+ fn collectJoined(self: *Builder, lines: *LineIterator, kind: JoinKind) []const u8 {
250
+ // Pass 1: measure the block's extent and joined size.
251
+ var probe = lines.*;
252
+ var total: usize = 0;
253
+ while (joinPiece(&probe, kind, total)) |piece| {
254
+ _ = probe.next();
255
+ if (total > 0) total += 1;
256
+ total += piece.len;
257
+ }
258
+ if (total == 0) {
259
+ lines.* = probe;
260
+ return &.{};
261
+ }
262
+
263
+ const out = self.ui.arena.alloc(u8, @min(total, max_markdown_paragraph_bytes)) catch {
264
+ self.ui.failed = true;
265
+ lines.* = probe;
266
+ return &.{};
267
+ };
268
+
269
+ // Pass 2: identical walk, copying until the cap.
270
+ var len: usize = 0;
271
+ var joined: usize = 0;
272
+ while (joinPiece(lines, kind, joined)) |piece| {
273
+ _ = lines.next();
274
+ if (joined > 0 and len < out.len) {
275
+ out[len] = ' ';
276
+ len += 1;
277
+ }
278
+ if (joined > 0) joined += 1;
279
+ joined += piece.len;
280
+ const take = @min(piece.len, out.len - len);
281
+ @memcpy(out[len..][0..take], piece[0..take]);
282
+ len += take;
283
+ }
284
+ return out[0..len];
285
+ }
286
+
287
+ fn paragraphNode(self: *Builder, text: []const u8, base: TextSpan) Node {
288
+ var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
289
+ const parsed = self.parseInline(text, base, &spans);
290
+ return self.ui.paragraph(.{ .on_link = self.options.on_link }, parsed);
291
+ }
292
+
293
+ fn parseCodeFence(self: *Builder, lines: *LineIterator) ?Node {
294
+ _ = lines.next(); // opening fence (info string ignored)
295
+ const start = lines.index;
296
+ var end = start;
297
+ while (lines.next()) |line| {
298
+ if (std.mem.startsWith(u8, std.mem.trim(u8, line, " \t"), "```")) break;
299
+ end = lines.index;
300
+ }
301
+ const code = std.mem.trimEnd(u8, lines.source[start..@min(end, lines.source.len)], "\n");
302
+ const code_span = [_]TextSpan{.{ .text = code, .monospace = true }};
303
+ return self.ui.el(.panel, .{
304
+ .padding = 12,
305
+ .style_tokens = .{ .background = .surface_subtle },
306
+ }, .{
307
+ self.ui.paragraph(.{}, &code_span),
308
+ });
309
+ }
310
+
311
+ fn parseBlockquote(self: *Builder, lines: *LineIterator) ?Node {
312
+ const text = self.collectJoined(lines, .blockquote);
313
+ if (text.len == 0) return null;
314
+ return self.ui.row(.{ .gap = 10 }, .{
315
+ self.ui.el(.separator, .{ .frame = geometry.RectF.init(0, 0, 3, 0) }, .{}),
316
+ self.paragraphWithOptions(text, .{ .grow = 1, .style_tokens = .{ .foreground = .text_muted } }),
317
+ });
318
+ }
319
+
320
+ fn paragraphWithOptions(self: *Builder, text: []const u8, options_in: Ui.ElementOptions) Node {
321
+ var options = options_in;
322
+ options.on_link = self.options.on_link;
323
+ var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
324
+ const parsed = self.parseInline(text, .{}, &spans);
325
+ return self.ui.paragraph(options, parsed);
326
+ }
327
+
328
+ fn parseList(self: *Builder, lines: *LineIterator, indent: usize, depth: usize) ?Node {
329
+ const items = self.ui.arena.alloc(Node, max_markdown_list_items_per_list) catch {
330
+ self.ui.failed = true;
331
+ return null;
332
+ };
333
+ var len: usize = 0;
334
+
335
+ while (lines.peek()) |line| {
336
+ const marker = listMarker(line) orelse break;
337
+ if (marker.indent < indent) break;
338
+ if (marker.indent > indent) {
339
+ // Deeper marker: a nested list under the previous item.
340
+ if (len == 0 or depth + 1 >= max_markdown_list_depth) {
341
+ _ = lines.next();
342
+ continue;
343
+ }
344
+ const nested = self.parseList(lines, marker.indent, depth + 1) orelse continue;
345
+ items[len - 1] = self.ui.column(.{ .gap = 4 }, .{ items[len - 1], nested });
346
+ continue;
347
+ }
348
+ _ = lines.next();
349
+ if (len >= items.len) continue;
350
+ items[len] = self.listItemNode(marker, depth);
351
+ len += 1;
352
+ }
353
+ if (len == 0) return null;
354
+ return self.ui.column(.{ .gap = 4 }, .{items[0..len]});
355
+ }
356
+
357
+ fn listItemNode(self: *Builder, marker: ListMarker, depth: usize) Node {
358
+ const content = self.paragraphWithOptions(marker.content, .{ .grow = 1 });
359
+ const lead: Node = switch (marker.kind) {
360
+ .bullet => self.ui.text(.{}, "•"),
361
+ .ordered => self.ui.text(.{}, marker.label),
362
+ .task => self.ui.checkbox(.{
363
+ .checked = marker.checked,
364
+ .disabled = true,
365
+ .semantics = .{ .label = marker.content },
366
+ }),
367
+ };
368
+ if (depth == 0) return self.ui.row(.{ .gap = 8 }, .{ lead, content });
369
+ const indent = self.ui.el(.stack, .{ .width = @as(f32, @floatFromInt(depth)) * 16 }, .{});
370
+ return self.ui.row(.{ .gap = 8 }, .{ indent, lead, content });
371
+ }
372
+
373
+ fn parseDetails(self: *Builder, lines: *LineIterator) ?Node {
374
+ _ = lines.next(); // <details ...>
375
+ const ordinal = self.details_count;
376
+ if (ordinal >= max_markdown_details_per_document) {
377
+ self.skipDetails(lines);
378
+ return null;
379
+ }
380
+ self.details_count += 1;
381
+ const expanded = ordinal < self.options.details_expanded.len and self.options.details_expanded[ordinal];
382
+
383
+ var summary: []const u8 = "Details";
384
+ if (lines.peek()) |line| {
385
+ const trimmed = std.mem.trim(u8, line, " \t");
386
+ if (std.ascii.startsWithIgnoreCase(trimmed, "<summary>")) {
387
+ _ = lines.next();
388
+ summary = trimmed["<summary>".len..];
389
+ if (std.ascii.indexOfIgnoreCase(summary, "</summary>")) |close| {
390
+ summary = summary[0..close];
391
+ }
392
+ summary = std.mem.trim(u8, summary, " \t");
393
+ }
394
+ }
395
+
396
+ var header = self.ui.listItem(.{
397
+ .key = .{ .int = @intCast(ordinal) },
398
+ .on_press = if (self.options.on_details) |make| make(ordinal) else null,
399
+ }, self.ui.fmt("{s} {s}", .{ if (expanded) "▾" else "▸", summary }));
400
+ header.widget.state.expanded = expanded;
401
+
402
+ if (!expanded) {
403
+ self.skipDetails(lines);
404
+ return self.ui.column(.{ .gap = 4 }, .{header});
405
+ }
406
+ const blocks = self.parseBlocks(lines, .details);
407
+ const body = self.ui.column(.{ .gap = 12, .padding = 8 }, blocks);
408
+ return self.ui.column(.{ .gap = 4 }, .{ header, body });
409
+ }
410
+
411
+ /// GFM pipe table: the caller (`isTableStart`) has verified a
412
+ /// header row followed by a delimiter row with a matching
413
+ /// column count. Body rows run until a blank line or a line
414
+ /// without a pipe; short rows pad with empty cells and long
415
+ /// rows drop trailing cells (GFM semantics). Rows past
416
+ /// `max_markdown_table_rows` drop deterministically.
417
+ fn parseTable(self: *Builder, lines: *LineIterator) ?Node {
418
+ const header_line = lines.next() orelse return null;
419
+ const header = splitTableRow(header_line) orelse return null;
420
+ const delimiter_line = lines.next() orelse return null;
421
+ const alignments = tableDelimiterAlignments(delimiter_line) orelse return null;
422
+ if (alignments.len != header.len) return null;
423
+
424
+ const rows = self.ui.arena.alloc(Node, max_markdown_table_rows) catch {
425
+ self.ui.failed = true;
426
+ return null;
427
+ };
428
+ rows[0] = self.tableRowNode(header, alignments, true);
429
+ var len: usize = 1;
430
+ while (lines.peek()) |line| {
431
+ const trimmed = std.mem.trim(u8, line, " \t");
432
+ if (trimmed.len == 0) break;
433
+ if (std.mem.indexOfScalar(u8, trimmed, '|') == null) break;
434
+ const row = splitTableRow(line) orelse break;
435
+ _ = lines.next();
436
+ if (len >= rows.len) continue;
437
+ rows[len] = self.tableRowNode(row, alignments, false);
438
+ len += 1;
439
+ }
440
+ return self.ui.el(.table, .{}, .{rows[0..len]});
441
+ }
442
+
443
+ fn tableRowNode(self: *Builder, row: TableRow, alignments: TableAlignments, is_header: bool) Node {
444
+ const cells = self.ui.arena.alloc(Node, alignments.len) catch {
445
+ self.ui.failed = true;
446
+ return self.ui.el(.data_row, .{}, .{});
447
+ };
448
+ for (cells, 0..) |*cell, column| {
449
+ const content = if (column < row.len) row.cells[column] else "";
450
+ cell.* = self.tableCellNode(content, alignments.columns[column], is_header);
451
+ }
452
+ return self.ui.el(.data_row, .{}, .{cells});
453
+ }
454
+
455
+ /// One cell: a `data_cell` widget carrying inline spans (the
456
+ /// full inline grammar, links included), per-column text
457
+ /// alignment from the delimiter row, and bold header styling.
458
+ fn tableCellNode(self: *Builder, content: []const u8, alignment: canvas.TextAlign, is_header: bool) Node {
459
+ const text = self.unescapeTablePipes(content);
460
+ const base: TextSpan = if (is_header) .{ .weight = .bold } else .{};
461
+ var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
462
+ const parsed = self.parseInline(text, base, &spans);
463
+ var cell = self.ui.paragraph(.{
464
+ .grow = 1,
465
+ .padding = 8,
466
+ .on_link = self.options.on_link,
467
+ }, parsed);
468
+ cell.widget.kind = .data_cell;
469
+ cell.widget.text_alignment = alignment;
470
+ return cell;
471
+ }
472
+
473
+ /// `\|` is the one backslash escape tables need (a literal
474
+ /// pipe inside a cell); everything else keeps the mapper's
475
+ /// no-escapes policy.
476
+ fn unescapeTablePipes(self: *Builder, text: []const u8) []const u8 {
477
+ if (std.mem.indexOf(u8, text, "\\|") == null) return text;
478
+ const out = self.ui.arena.alloc(u8, text.len) catch {
479
+ self.ui.failed = true;
480
+ return text;
481
+ };
482
+ var len: usize = 0;
483
+ var index: usize = 0;
484
+ while (index < text.len) : (index += 1) {
485
+ if (text[index] == '\\' and index + 1 < text.len and text[index + 1] == '|') continue;
486
+ out[len] = text[index];
487
+ len += 1;
488
+ }
489
+ return out[0..len];
490
+ }
491
+
492
+ fn skipDetails(self: *Builder, lines: *LineIterator) void {
493
+ _ = self;
494
+ var depth: usize = 1;
495
+ while (lines.next()) |line| {
496
+ const trimmed = std.mem.trim(u8, line, " \t");
497
+ if (std.ascii.startsWithIgnoreCase(trimmed, "<details")) depth += 1;
498
+ if (std.ascii.startsWithIgnoreCase(trimmed, "</details>")) {
499
+ depth -= 1;
500
+ if (depth == 0) return;
501
+ }
502
+ }
503
+ }
504
+
505
+ // ----------------------------------------------------- inlines
506
+
507
+ /// Scan inline markdown into spans carrying `base` styling
508
+ /// (headings pass bold + scale). Delimiters without a closer,
509
+ /// and any construct this subset does not model, fall through
510
+ /// as literal text. Span-capacity overflow appends the rest of
511
+ /// the text as one unstyled span.
512
+ fn parseInline(self: *Builder, text: []const u8, base: TextSpan, spans: *[text_spans.max_text_spans_per_paragraph]TextSpan) []const TextSpan {
513
+ var len: usize = 0;
514
+ var bold = false;
515
+ var italic = false;
516
+ var strike = false;
517
+ var literal_start: usize = 0;
518
+ var index: usize = 0;
519
+ var scan_cache = ScanCache{};
520
+
521
+ while (index < text.len) {
522
+ if (len + 2 >= spans.len) break;
523
+ const rest = text[index..];
524
+
525
+ if (rest[0] == '`') {
526
+ if (std.mem.indexOfScalar(u8, rest[1..], '`')) |close| {
527
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
528
+ appendSpan(spans, &len, spanWith(base, .{ .text = rest[1 .. 1 + close], .monospace = true }));
529
+ index += close + 2;
530
+ literal_start = index;
531
+ continue;
532
+ }
533
+ } else if (std.mem.startsWith(u8, rest, "**") or std.mem.startsWith(u8, rest, "__")) {
534
+ const delim = rest[0..2];
535
+ if (bold or hasCloser(rest[2..], delim)) {
536
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
537
+ bold = !bold;
538
+ index += 2;
539
+ literal_start = index;
540
+ continue;
541
+ }
542
+ } else if (std.mem.startsWith(u8, rest, "~~")) {
543
+ if (strike or hasCloser(rest[2..], "~~")) {
544
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
545
+ strike = !strike;
546
+ index += 2;
547
+ literal_start = index;
548
+ continue;
549
+ }
550
+ } else if (rest[0] == '*' or rest[0] == '_') {
551
+ const delim = rest[0..1];
552
+ const boundary_ok = rest[0] == '*' or index == 0 or !isWordByte(text[index - 1]);
553
+ const emphasis_ok = if (italic)
554
+ true
555
+ else
556
+ rest.len > 1 and !isInlineSpace(rest[1]) and hasCloser(rest[1..], delim);
557
+ if (boundary_ok and emphasis_ok) {
558
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
559
+ italic = !italic;
560
+ index += 1;
561
+ literal_start = index;
562
+ continue;
563
+ }
564
+ } else if (rest[0] == '[') {
565
+ if (parseLinkAt(text, index, &scan_cache)) |link| {
566
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
567
+ appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
568
+ index += link.consumed;
569
+ literal_start = index;
570
+ continue;
571
+ }
572
+ } else if (rest[0] == '!' and rest.len > 1 and rest[1] == '[') {
573
+ if (parseLinkAt(text, index + 1, &scan_cache)) |image| {
574
+ // Images render as their alt text in v1.
575
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
576
+ appendSpan(spans, &len, spanWith(base, .{ .text = image.text }));
577
+ index += image.consumed + 1;
578
+ literal_start = index;
579
+ continue;
580
+ }
581
+ } else if (rest[0] == '<') {
582
+ if (parseAutolinkAt(text, index, &scan_cache)) |link| {
583
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
584
+ appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
585
+ index += link.consumed;
586
+ literal_start = index;
587
+ continue;
588
+ }
589
+ } else if (rest[0] == 'h' and atAutolinkBoundary(text, index)) {
590
+ if (parseBareUrlAt(rest)) |link| {
591
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
592
+ appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
593
+ index += link.consumed;
594
+ literal_start = index;
595
+ continue;
596
+ }
597
+ } else if (rest[0] == '#' and atAutolinkBoundary(text, index)) {
598
+ if (self.options.issue_link_base) |issue_base| {
599
+ if (parseIssueRefAt(rest)) |ref| {
600
+ flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
601
+ appendSpan(spans, &len, spanWith(base, .{
602
+ .text = rest[0..ref.consumed],
603
+ .link = self.ui.fmt("{s}{s}", .{ issue_base, ref.digits }),
604
+ }));
605
+ index += ref.consumed;
606
+ literal_start = index;
607
+ continue;
608
+ }
609
+ }
610
+ }
611
+ index += 1;
612
+ }
613
+ // Tail (including everything after a span-capacity stop),
614
+ // styled with the state at the stop point.
615
+ flushLiteral(spans, &len, text[literal_start..], base, bold, italic, strike);
616
+ if (len == 0) {
617
+ spans[0] = spanWith(base, .{ .text = text });
618
+ len = 1;
619
+ }
620
+ return spans[0..len];
621
+ }
622
+
623
+ fn flushLiteral(
624
+ spans: *[text_spans.max_text_spans_per_paragraph]TextSpan,
625
+ len: *usize,
626
+ slice: []const u8,
627
+ base: TextSpan,
628
+ bold: bool,
629
+ italic: bool,
630
+ strike: bool,
631
+ ) void {
632
+ if (slice.len == 0) return;
633
+ var span = spanWith(base, .{ .text = slice });
634
+ if (bold) span.weight = .bold;
635
+ if (italic) span.italic = true;
636
+ if (strike) span.strikethrough = true;
637
+ appendSpan(spans, len, span);
638
+ }
639
+
640
+ fn appendSpan(spans: *[text_spans.max_text_spans_per_paragraph]TextSpan, len: *usize, span: TextSpan) void {
641
+ if (len.* >= spans.len) return;
642
+ spans[len.*] = span;
643
+ len.* += 1;
644
+ }
645
+
646
+ fn spanWith(base: TextSpan, overrides: TextSpan) TextSpan {
647
+ var span = overrides;
648
+ if (span.weight == .regular) span.weight = base.weight;
649
+ if (!span.italic) span.italic = base.italic;
650
+ if (!span.strikethrough) span.strikethrough = base.strikethrough;
651
+ if (span.scale == 0) span.scale = base.scale;
652
+ if (span.color == null) span.color = base.color;
653
+ return span;
654
+ }
655
+ };
656
+ };
657
+ }
658
+
659
+ // ------------------------------------------------------------ line model
660
+
661
+ const LineIterator = struct {
662
+ source: []const u8,
663
+ index: usize = 0,
664
+
665
+ fn next(self: *LineIterator) ?[]const u8 {
666
+ if (self.index >= self.source.len) return null;
667
+ const start = self.index;
668
+ const end = std.mem.indexOfScalarPos(u8, self.source, start, '\n') orelse self.source.len;
669
+ self.index = @min(end + 1, self.source.len);
670
+ return std.mem.trimEnd(u8, self.source[start..end], "\r");
671
+ }
672
+
673
+ fn peek(self: *LineIterator) ?[]const u8 {
674
+ var copy = self.*;
675
+ return copy.next();
676
+ }
677
+
678
+ fn peekSecond(self: *LineIterator) ?[]const u8 {
679
+ var copy = self.*;
680
+ _ = copy.next() orelse return null;
681
+ return copy.next();
682
+ }
683
+ };
684
+
685
+ // ----------------------------------------------------------- table model
686
+
687
+ const TableRow = struct {
688
+ cells: [max_markdown_table_columns][]const u8 = undefined,
689
+ len: usize = 0,
690
+ };
691
+
692
+ const TextAlignValue = canvas.TextAlign;
693
+
694
+ const TableAlignments = struct {
695
+ columns: [max_markdown_table_columns]TextAlignValue = undefined,
696
+ len: usize = 0,
697
+ };
698
+
699
+ /// Split a pipe row into trimmed cell slices. Null when the line has no
700
+ /// pipe, yields no cells, or has more than `max_markdown_table_columns`
701
+ /// cells (the caller then degrades the block to plain text). `\|` does
702
+ /// not split (GFM's in-cell pipe escape); the cell text is unescaped at
703
+ /// emit time.
704
+ fn splitTableRow(line: []const u8) ?TableRow {
705
+ const trimmed = std.mem.trim(u8, line, " \t");
706
+ if (trimmed.len == 0) return null;
707
+ if (std.mem.indexOfScalar(u8, trimmed, '|') == null) return null;
708
+ var rest = trimmed;
709
+ if (rest[0] == '|') rest = rest[1..];
710
+ if (rest.len > 0 and rest[rest.len - 1] == '|' and !(rest.len > 1 and rest[rest.len - 2] == '\\')) {
711
+ rest = rest[0 .. rest.len - 1];
712
+ }
713
+ var row = TableRow{};
714
+ var start: usize = 0;
715
+ var index: usize = 0;
716
+ while (index < rest.len) : (index += 1) {
717
+ if (rest[index] == '\\') {
718
+ index += 1; // Skip the escaped byte (covers `\|`).
719
+ continue;
720
+ }
721
+ if (rest[index] != '|') continue;
722
+ if (row.len >= max_markdown_table_columns) return null;
723
+ row.cells[row.len] = std.mem.trim(u8, rest[start..index], " \t");
724
+ row.len += 1;
725
+ start = index + 1;
726
+ }
727
+ if (row.len >= max_markdown_table_columns) return null;
728
+ row.cells[row.len] = std.mem.trim(u8, rest[@min(start, rest.len)..], " \t");
729
+ row.len += 1;
730
+ return row;
731
+ }
732
+
733
+ /// Parse a GFM delimiter row (`| --- | :--: | ---: |`): every cell must
734
+ /// be dashes with optional leading/trailing colons mapping to
735
+ /// start/center/end column alignment.
736
+ fn tableDelimiterAlignments(line: []const u8) ?TableAlignments {
737
+ const row = splitTableRow(line) orelse return null;
738
+ var result = TableAlignments{ .len = row.len };
739
+ for (row.cells[0..row.len], 0..) |cell, column| {
740
+ if (cell.len == 0) return null;
741
+ var body = cell;
742
+ const leading = body[0] == ':';
743
+ if (leading) body = body[1..];
744
+ var trailing = false;
745
+ if (body.len > 0 and body[body.len - 1] == ':') {
746
+ trailing = true;
747
+ body = body[0 .. body.len - 1];
748
+ }
749
+ if (body.len == 0) return null;
750
+ for (body) |byte| {
751
+ if (byte != '-') return null;
752
+ }
753
+ result.columns[column] = if (leading and trailing)
754
+ .center
755
+ else if (trailing)
756
+ .end
757
+ else
758
+ .start;
759
+ }
760
+ return result;
761
+ }
762
+
763
+ /// A table starts at a pipe header row whose next line is a delimiter row
764
+ /// with the same column count (GFM). Anything else falls through to the
765
+ /// paragraph path.
766
+ fn isTableStart(lines: *LineIterator) bool {
767
+ const first = lines.peek() orelse return false;
768
+ const header = splitTableRow(first) orelse return false;
769
+ const second = lines.peekSecond() orelse return false;
770
+ const alignments = tableDelimiterAlignments(second) orelse return false;
771
+ return alignments.len == header.len;
772
+ }
773
+
774
+ fn headingLevel(line: []const u8) ?usize {
775
+ var level: usize = 0;
776
+ while (level < line.len and line[level] == '#') level += 1;
777
+ if (level == 0 or level > 6) return null;
778
+ if (level < line.len and line[level] != ' ') return null;
779
+ return level;
780
+ }
781
+
782
+ fn isHorizontalRule(line: []const u8) bool {
783
+ if (line.len < 3) return false;
784
+ const marker = line[0];
785
+ if (marker != '-' and marker != '*' and marker != '_') return false;
786
+ var count: usize = 0;
787
+ for (line) |byte| {
788
+ if (byte == marker) {
789
+ count += 1;
790
+ } else if (byte != ' ') {
791
+ return false;
792
+ }
793
+ }
794
+ return count >= 3;
795
+ }
796
+
797
+ const ListMarkerKind = enum { bullet, ordered, task };
798
+
799
+ const ListMarker = struct {
800
+ kind: ListMarkerKind,
801
+ /// Nesting level derived from leading spaces (two per level).
802
+ indent: usize,
803
+ /// Ordinal label for ordered items ("3."), empty otherwise.
804
+ label: []const u8,
805
+ checked: bool = false,
806
+ content: []const u8,
807
+ };
808
+
809
+ fn listMarker(line: []const u8) ?ListMarker {
810
+ var spaces: usize = 0;
811
+ while (spaces < line.len and line[spaces] == ' ') spaces += 1;
812
+ const indent = @min(spaces / 2, max_markdown_list_depth - 1);
813
+ const rest = line[spaces..];
814
+ if (rest.len < 2) return null;
815
+
816
+ if ((rest[0] == '-' or rest[0] == '*' or rest[0] == '+') and rest[1] == ' ') {
817
+ const content = std.mem.trim(u8, rest[2..], " \t");
818
+ if (std.mem.startsWith(u8, content, "[ ] ")) {
819
+ return .{ .kind = .task, .indent = indent, .label = "", .checked = false, .content = content[4..] };
820
+ }
821
+ if (std.mem.startsWith(u8, content, "[x] ") or std.mem.startsWith(u8, content, "[X] ")) {
822
+ return .{ .kind = .task, .indent = indent, .label = "", .checked = true, .content = content[4..] };
823
+ }
824
+ return .{ .kind = .bullet, .indent = indent, .label = "", .content = content };
825
+ }
826
+
827
+ var digits: usize = 0;
828
+ while (digits < rest.len and std.ascii.isDigit(rest[digits])) digits += 1;
829
+ if (digits > 0 and digits + 1 < rest.len and rest[digits] == '.' and rest[digits + 1] == ' ') {
830
+ return .{
831
+ .kind = .ordered,
832
+ .indent = indent,
833
+ .label = rest[0 .. digits + 1],
834
+ .content = std.mem.trim(u8, rest[digits + 2 ..], " \t"),
835
+ };
836
+ }
837
+ return null;
838
+ }
839
+
840
+ fn startsNewBlock(line: []const u8) bool {
841
+ const trimmed = std.mem.trim(u8, line, " \t");
842
+ if (trimmed.len == 0) return true;
843
+ if (std.mem.startsWith(u8, trimmed, "```")) return true;
844
+ if (headingLevel(trimmed) != null) return true;
845
+ if (isHorizontalRule(trimmed)) return true;
846
+ if (std.mem.startsWith(u8, trimmed, ">")) return true;
847
+ if (listMarker(line) != null) return true;
848
+ if (std.ascii.startsWithIgnoreCase(trimmed, "<details")) return true;
849
+ return false;
850
+ }
851
+
852
+ const InlineLink = struct {
853
+ text: []const u8,
854
+ target: []const u8,
855
+ consumed: usize,
856
+ };
857
+
858
+ /// Memoized forward scans for one `parseInline` pass. The inline walk
859
+ /// only moves forward, so the next occurrence of a closer (or of the
860
+ /// autolink scheme separator) found from one position stays the answer
861
+ /// for every position up to it — without this, a wall of `[`, `<`, or
862
+ /// `![` rescans to the terminator at every byte, and a kilobyte of
863
+ /// hostile input costs a megabyte of scanning (quadratic; a real
864
+ /// pasted-garbage hang).
865
+ const ScanCache = struct {
866
+ close_bracket: Slot = .{}, // ']'
867
+ close_paren: Slot = .{}, // ')'
868
+ angle_close: Slot = .{}, // '>'
869
+ /// ' ' queried by autolink target checks (from just past `<`).
870
+ space: Slot = .{}, // ' '
871
+ /// ' ' queried by link title-strips (from just past `](`). A
872
+ /// separate slot: the two query streams sit at different offsets,
873
+ /// and sharing one memo lets them evict each other back into
874
+ /// quadratic rescans on interleaved `[`/`<` walls.
875
+ title_space: Slot = .{}, // ' '
876
+ scheme_sep: Slot = .{}, // "://"
877
+
878
+ const Slot = struct {
879
+ valid: bool = false,
880
+ scanned_from: usize = 0,
881
+ /// Next occurrence at/after `scanned_from`; null when the scan
882
+ /// proved none remains.
883
+ pos: ?usize = null,
884
+ };
885
+
886
+ fn nextScalar(slot: *Slot, text: []const u8, from: usize, byte: u8) ?usize {
887
+ if (cached(slot, from)) |hit| return hit.pos;
888
+ const found = std.mem.indexOfScalarPos(u8, text, from, byte);
889
+ slot.* = .{ .valid = true, .scanned_from = from, .pos = found };
890
+ return found;
891
+ }
892
+
893
+ fn nextPattern(slot: *Slot, text: []const u8, from: usize, pattern: []const u8) ?usize {
894
+ if (cached(slot, from)) |hit| return hit.pos;
895
+ const found = std.mem.indexOfPos(u8, text, from, pattern);
896
+ slot.* = .{ .valid = true, .scanned_from = from, .pos = found };
897
+ return found;
898
+ }
899
+
900
+ const Hit = struct { pos: ?usize };
901
+
902
+ fn cached(slot: *Slot, from: usize) ?Hit {
903
+ if (!slot.valid or from < slot.scanned_from) return null;
904
+ if (slot.pos) |pos| {
905
+ if (from > pos) return null;
906
+ return .{ .pos = pos };
907
+ }
908
+ return .{ .pos = null };
909
+ }
910
+ };
911
+
912
+ /// Parse `[text](target)` at `source[index]`; null when malformed (the
913
+ /// caller then treats `[` as literal text). `consumed` is relative to
914
+ /// `index`.
915
+ fn parseLinkAt(source: []const u8, index: usize, cache: *ScanCache) ?InlineLink {
916
+ const rest = source[index..];
917
+ if (rest.len < 4 or rest[0] != '[') return null;
918
+ const close_bracket_abs = ScanCache.nextScalar(&cache.close_bracket, source, index, ']') orelse return null;
919
+ const close_bracket = close_bracket_abs - index;
920
+ if (close_bracket + 1 >= rest.len or rest[close_bracket + 1] != '(') return null;
921
+ const close_paren_abs = ScanCache.nextScalar(&cache.close_paren, source, close_bracket_abs + 2, ')') orelse return null;
922
+ const close_paren = close_paren_abs - index;
923
+ const text = rest[1..close_bracket];
924
+ var target = rest[close_bracket + 2 .. close_paren];
925
+ // Strip an optional title: [text](url "title"). Memoized like the
926
+ // closers: an unbounded target rescanned per failed attempt is the
927
+ // same quadratic wall.
928
+ if (ScanCache.nextScalar(&cache.title_space, source, close_bracket_abs + 2, ' ')) |space_abs| {
929
+ if (space_abs < close_paren_abs) target = target[0 .. space_abs - (close_bracket_abs + 2)];
930
+ }
931
+ if (text.len == 0 or target.len == 0) return null;
932
+ return .{ .text = text, .target = target, .consumed = close_paren + 1 };
933
+ }
934
+
935
+ /// Parse `<scheme://...>` autolinks at `source[index]`. `consumed` is
936
+ /// relative to `index`.
937
+ fn parseAutolinkAt(source: []const u8, index: usize, cache: *ScanCache) ?InlineLink {
938
+ const rest = source[index..];
939
+ if (rest.len < 3 or rest[0] != '<') return null;
940
+ const close_abs = ScanCache.nextScalar(&cache.angle_close, source, index, '>') orelse return null;
941
+ const close = close_abs - index;
942
+ const target = rest[1..close];
943
+ const sep_abs = ScanCache.nextPattern(&cache.scheme_sep, source, index + 1, "://") orelse return null;
944
+ if (sep_abs + "://".len > close_abs) return null;
945
+ if (ScanCache.nextScalar(&cache.space, source, index + 1, ' ')) |space_abs| {
946
+ if (space_abs < close_abs) return null;
947
+ }
948
+ return .{ .text = target, .target = target, .consumed = close + 1 };
949
+ }
950
+
951
+ /// Word-boundary test for bare-URL and `#N` autolinking (the classic
952
+ /// `(^|[^\w/&])` register): don't link when continuing a word, a
953
+ /// path (`/`), or an HTML entity (`&`).
954
+ fn atAutolinkBoundary(text: []const u8, index: usize) bool {
955
+ if (index == 0) return true;
956
+ const previous = text[index - 1];
957
+ return !isWordByte(previous) and previous != '/' and previous != '&';
958
+ }
959
+
960
+ /// Parse a bare `http://`/`https://` URL at the start of `rest`
961
+ /// (GFM-style autolink extension): the URL runs to whitespace or `<`,
962
+ /// then trailing punctuation and unbalanced close parens are trimmed so
963
+ /// prose like "see https://example.com." links cleanly.
964
+ fn parseBareUrlAt(rest: []const u8) ?InlineLink {
965
+ const scheme_len: usize = if (std.mem.startsWith(u8, rest, "https://"))
966
+ "https://".len
967
+ else if (std.mem.startsWith(u8, rest, "http://"))
968
+ "http://".len
969
+ else
970
+ return null;
971
+ var end = scheme_len;
972
+ var balance: isize = 0;
973
+ while (end < rest.len) : (end += 1) {
974
+ const byte = rest[end];
975
+ if (isInlineSpace(byte) or byte == '\n' or byte == '<' or byte == '>') break;
976
+ if (byte == '(') balance += 1;
977
+ if (byte == ')') balance -= 1;
978
+ }
979
+ // Trim trailing punctuation, keeping the paren balance current
980
+ // incrementally — recomputing it per trimmed ')' is quadratic in the
981
+ // tail length (a hostile URL ending in a wall of parens used to
982
+ // hang).
983
+ while (end > scheme_len) {
984
+ const byte = rest[end - 1];
985
+ if (byte == ')') {
986
+ if (balance < 0) {
987
+ end -= 1;
988
+ balance += 1;
989
+ continue;
990
+ }
991
+ break;
992
+ }
993
+ switch (byte) {
994
+ '.', ',', ';', ':', '!', '?', '\'', '"' => end -= 1,
995
+ else => break,
996
+ }
997
+ }
998
+ if (end == scheme_len) return null;
999
+ const target = rest[0..end];
1000
+ return .{ .text = target, .target = target, .consumed = end };
1001
+ }
1002
+
1003
+ const IssueRef = struct {
1004
+ /// The digits after `#`.
1005
+ digits: []const u8,
1006
+ consumed: usize,
1007
+ };
1008
+
1009
+ /// Parse `#123` at the start of `rest`: one or more digits ending at a
1010
+ /// word boundary (the classic `#(\d+)\b` register). The caller checks
1011
+ /// the leading boundary and supplies the link base.
1012
+ fn parseIssueRefAt(rest: []const u8) ?IssueRef {
1013
+ if (rest.len < 2 or rest[0] != '#') return null;
1014
+ var end: usize = 1;
1015
+ while (end < rest.len and std.ascii.isDigit(rest[end])) end += 1;
1016
+ if (end == 1) return null;
1017
+ if (end < rest.len and isWordByte(rest[end])) return null;
1018
+ return .{ .digits = rest[1..end], .consumed = end };
1019
+ }
1020
+
1021
+ fn hasCloser(rest: []const u8, delim: []const u8) bool {
1022
+ return std.mem.indexOf(u8, rest, delim) != null;
1023
+ }
1024
+
1025
+ fn isInlineSpace(byte: u8) bool {
1026
+ return byte == ' ' or byte == '\t';
1027
+ }
1028
+
1029
+ fn isWordByte(byte: u8) bool {
1030
+ return std.ascii.isAlphanumeric(byte) or byte == '_';
1031
+ }