@native-sdk/cli 0.6.3 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/build.zig +65 -91
  2. package/package.json +9 -9
  3. package/packages/core/package-lock.json +2 -2
  4. package/packages/core/package.json +1 -1
  5. package/packages/core/sdk/text.ts +25 -14
  6. package/packages/core/src/checker.ts +39 -0
  7. package/packages/core/src/emitter.ts +125 -1
  8. package/skill-data/native-ui/SKILL.md +23 -6
  9. package/src/platform/macos/appkit_host.m +25 -1
  10. package/src/platform/macos/cef_host.mm +24 -2
  11. package/src/platform/macos/root.zig +13 -0
  12. package/src/primitives/canvas/code.zig +1008 -0
  13. package/src/primitives/canvas/code_tests.zig +1912 -0
  14. package/src/primitives/canvas/events.zig +111 -1
  15. package/src/primitives/canvas/layout_audit.zig +3 -1
  16. package/src/primitives/canvas/markdown.zig +13 -11
  17. package/src/primitives/canvas/markdown_tests.zig +168 -6
  18. package/src/primitives/canvas/root.zig +8 -2
  19. package/src/primitives/canvas/tests.zig +1 -0
  20. package/src/primitives/canvas/text.zig +6 -0
  21. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  22. package/src/primitives/canvas/text_span_tests.zig +254 -0
  23. package/src/primitives/canvas/text_spans.zig +556 -32
  24. package/src/primitives/canvas/themes/geist.zig +29 -0
  25. package/src/primitives/canvas/tokens.zig +72 -2
  26. package/src/primitives/canvas/ui.zig +400 -22
  27. package/src/primitives/canvas/ui_markup.zig +78 -7
  28. package/src/primitives/canvas/ui_markup_compiled.zig +89 -0
  29. package/src/primitives/canvas/ui_markup_compiled_tests.zig +45 -0
  30. package/src/primitives/canvas/ui_markup_contract.zig +41 -0
  31. package/src/primitives/canvas/ui_markup_view.zig +89 -0
  32. package/src/primitives/canvas/ui_markup_view_tests.zig +154 -3
  33. package/src/primitives/canvas/ui_schema.zig +30 -6
  34. package/src/primitives/canvas/ui_schema_tests.zig +13 -10
  35. package/src/primitives/canvas/ui_tests.zig +26 -0
  36. package/src/primitives/canvas/widget_invalidation.zig +4 -0
  37. package/src/primitives/canvas/widget_layout.zig +57 -8
  38. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  39. package/src/primitives/canvas/widget_metrics.zig +35 -1
  40. package/src/primitives/canvas/widget_render.zig +1077 -11
  41. package/src/primitives/canvas/widget_render_controls.zig +4 -4
  42. package/src/primitives/canvas/widget_runtime.zig +2 -0
  43. package/src/primitives/canvas/widget_text_input.zig +165 -8
  44. package/src/primitives/canvas/widget_text_select.zig +2 -2
  45. package/src/primitives/canvas/widget_tree.zig +6 -5
  46. package/src/primitives/canvas/widgets.zig +38 -0
  47. package/src/root.zig +1 -0
  48. package/src/runtime/canvas_budget_edge_tests.zig +3 -2
  49. package/src/runtime/canvas_limits.zig +13 -6
  50. package/src/runtime/canvas_widget_clipboard_tests.zig +137 -4
  51. package/src/runtime/canvas_widget_context_menu.zig +17 -2
  52. package/src/runtime/canvas_widget_event_tests.zig +18 -14
  53. package/src/runtime/canvas_widget_events.zig +58 -21
  54. package/src/runtime/canvas_widget_runtime.zig +112 -6
  55. package/src/runtime/canvas_widget_scroll_driver_tests.zig +59 -0
  56. package/src/runtime/canvas_widget_split_tree_tests.zig +100 -0
  57. package/src/runtime/canvas_widget_state.zig +27 -0
  58. package/src/runtime/canvas_widget_text_tests.zig +383 -0
  59. package/src/runtime/core.zig +15 -5
  60. package/src/runtime/gpu_surface_events.zig +12 -12
  61. package/src/runtime/view.zig +61 -19
  62. package/src/runtime/view_widget_scroll.zig +48 -18
  63. package/src/runtime/view_widget_text.zig +248 -17
  64. package/src/runtime/window_view_runtime.zig +9 -0
@@ -20,6 +20,7 @@
20
20
 
21
21
  const std = @import("std");
22
22
  const builtin = @import("builtin");
23
+ const code_model = @import("code.zig");
23
24
  const font_coverage = @import("font_coverage.zig");
24
25
  const geometry = @import("geometry");
25
26
  const canvas = @import("root.zig");
@@ -303,8 +304,8 @@ pub const VirtualWindowRecord = struct {
303
304
 
304
305
  pub const UiHandlerEvent = enum {
305
306
  press,
306
- /// A multi-click press (click_count >= 2 on the release): the
307
- /// double-click channel. Resolution lives in `msgForPointerClick`:
307
+ /// The second release in a multi-click chain: the double-click
308
+ /// channel. Resolution lives in `msgForPointerClick`:
308
309
  /// a double-click release prefers this handler and falls back to
309
310
  /// `.press`, so binding it is strictly additive — the first click
310
311
  /// of every double-click still dispatches the single-press message
@@ -383,9 +384,7 @@ pub const StyleTokenRefs = struct {
383
384
  };
384
385
 
385
386
  fn colorTokenValue(colors: canvas.ColorTokens, ref: ColorTokenName) canvas.Color {
386
- return switch (ref) {
387
- inline else => |tag| @field(colors, @tagName(tag)),
388
- };
387
+ return canvas.colorTokenValue(colors, ref);
389
388
  }
390
389
 
391
390
  fn radiusTokenValue(radius: canvas.RadiusTokens, ref: RadiusTokenName) f32 {
@@ -559,6 +558,10 @@ pub fn Ui(comptime Msg: type) type {
559
558
  /// via `on_toggle`). Model-owned: the view renders child
560
559
  /// rows only while expanded.
561
560
  expanded: ?bool = null,
561
+ /// One-based logical level for a flat tree-row sequence
562
+ /// (markup: `tree-level`). Zero derives hierarchy from widget
563
+ /// nesting, preserving the original structural tree contract.
564
+ tree_level: u16 = 0,
562
565
  disabled: bool = false,
563
566
  /// Image resource reference for image-bearing widgets
564
567
  /// (`image`, `icon_button`, `avatar`): a `canvas.ImageId` the
@@ -763,14 +766,14 @@ pub fn Ui(comptime Msg: type) type {
763
766
  /// the live bottom. Meaningless on every other element.
764
767
  scrollback: u32 = 0,
765
768
  on_press: ?Msg = null,
766
- /// Double-click Msg (builder-only): dispatched on a release
767
- /// whose click count reached 2, in place of `on_press` for
768
- /// that release. The FIRST click of the double still
769
- /// dispatches `on_press` on its own release, so the natural
770
- /// pairing is select-on-press + act-on-double-press (a list
771
- /// row that selects on click and opens/plays on double
772
- /// click). Like `on_press`, binding it makes the element a
773
- /// hit target and press claimer.
769
+ /// Double-click Msg (markup: `on-double-press`): dispatched
770
+ /// on a release whose click count reached 2, in place of
771
+ /// `on_press` for that release. The FIRST click of the double
772
+ /// still dispatches `on_press` on its own release, so the
773
+ /// natural pairing is select-on-press + act-on-double-press
774
+ /// (a list row that selects on click and opens/plays on double
775
+ /// click). Like `on_press`, binding it makes the element a hit
776
+ /// target and press claimer.
774
777
  on_double_press: ?Msg = null,
775
778
  on_toggle: ?Msg = null,
776
779
  on_change: ?Msg = null,
@@ -937,6 +940,11 @@ pub fn Ui(comptime Msg: type) type {
937
940
  on_terminal: ?TerminalMsgFn = null,
938
941
  context_menu: []const ContextMenuItem = &.{},
939
942
  nodes: []const Node = &.{},
943
+ /// Internal source fingerprint for adjacent code paragraphs
944
+ /// that form one selectable document. `finalizeNode` combines
945
+ /// it with their parent structural id into a source-sensitive
946
+ /// group identity.
947
+ static_text_group_fingerprint: u64 = 0,
940
948
  /// Markup authoring provenance, stamped by the markup engines
941
949
  /// when the builder carries a `provenance_sink`; null for
942
950
  /// builder-authored (Zig) nodes, which is itself the honest
@@ -1355,14 +1363,14 @@ pub fn Ui(comptime Msg: type) type {
1355
1363
  }
1356
1364
 
1357
1365
  /// `msgForPointer` with the pointer's click count: a release
1358
- /// whose count reached 2 prefers the widget's `on_double_press`
1366
+ /// whose count is exactly 2 prefers the widget's `on_double_press`
1359
1367
  /// handler and falls back to the ordinary press resolution
1360
1368
  /// (so a double-click on a widget without the double channel
1361
1369
  /// behaves exactly like two single clicks). This is the
1362
1370
  /// dispatcher the runtime pointer path uses; the two-argument
1363
1371
  /// form stays the single-click entry point.
1364
1372
  pub fn msgForPointerClick(self: Tree, target_id: ObjectId, phase: canvas.WidgetPointerPhase, click_count: u8) ?Msg {
1365
- if (phase == .up and click_count >= 2) {
1373
+ if (phase == .up and click_count == 2) {
1366
1374
  if (self.msgFor(target_id, .double_press)) |msg| return msg;
1367
1375
  }
1368
1376
  return self.msgForPointer(target_id, phase);
@@ -1373,6 +1381,14 @@ pub fn Ui(comptime Msg: type) type {
1373
1381
  /// entry widgets.
1374
1382
  pub fn msgForKeyboard(self: Tree, target_id: ObjectId, keyboard: canvas.WidgetKeyboardEvent) ?Msg {
1375
1383
  const widget = self.findWidget(target_id) orelse return null;
1384
+ // Tree focus navigation is selection without activation.
1385
+ // `on_change` gives apps a distinct model message for that
1386
+ // path (a file browser can move its tree cursor without
1387
+ // opening a preview); rows that do not bind it retain the
1388
+ // original selection-follows-focus `on_press` behavior.
1389
+ if (widget.semantics.role == .treeitem and keyboard.focus_moved) {
1390
+ if (self.msgFor(target_id, .change)) |msg| return msg;
1391
+ }
1376
1392
  // A list row prefers a bound submit handler on plain
1377
1393
  // Enter: Enter is the row's PRIMARY action (open the
1378
1394
  // record, play the track — the desktop list convention),
@@ -1406,7 +1422,9 @@ pub fn Ui(comptime Msg: type) type {
1406
1422
  // bytes that the new-input sanitizer would strip.
1407
1423
  if (self.msgForTextEdit(target_id, stamped)) |msg| return msg;
1408
1424
  } else {
1409
- const locally_derived = canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse keyboard.textEditEvent();
1425
+ const locally_derived = canvas.widgetCodeTabTextEditEvent(widget, keyboard) orelse
1426
+ canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse
1427
+ keyboard.textEditEvent();
1410
1428
  if (locally_derived) |text_edit| {
1411
1429
  // Direct Tree consumers still sanitize locally:
1412
1430
  // these bytes have not crossed the runtime seam.
@@ -1861,11 +1879,12 @@ pub fn Ui(comptime Msg: type) type {
1861
1879
  /// Disclosure-tree container: descendant rows carrying
1862
1880
  /// `role = .treeitem` (at any nesting depth) form one roving
1863
1881
  /// keyboard focus set with the ARIA tree keymap — Up/Down walk
1864
- /// visible rows (selection follows focus through each row's
1865
- /// `on_press`), Left collapses or moves to the parent row,
1882
+ /// visible rows (selection follows focus through `on_change` when
1883
+ /// bound, else `on_press`), Left collapses or moves to the parent row,
1866
1884
  /// Right expands or moves to the first child row, Home/End jump
1867
- /// to the edges. Expansion is model-owned: expandable rows set
1868
- /// `expanded` and bind `on_toggle`.
1885
+ /// to the edges. Flat loop-rendered rows set `tree_level`; nested
1886
+ /// rows derive the same hierarchy structurally. Expansion is
1887
+ /// model-owned: expandable rows set `expanded` and bind `on_toggle`.
1869
1888
  pub fn tree(self: *Self, options: ElementOptions, children: anytype) Node {
1870
1889
  return self.el(.tree, options, children);
1871
1890
  }
@@ -2289,6 +2308,355 @@ pub fn Ui(comptime Msg: type) type {
2289
2308
  return self.el(.stack, .{ .grow = grow }, .{});
2290
2309
  }
2291
2310
 
2311
+ pub const CodeOptions = struct {
2312
+ key: ?UiKey = null,
2313
+ global_key: ?UiKey = null,
2314
+ language: code_model.Language = .plain,
2315
+ /// Opt into the engine's multiline editor behavior while
2316
+ /// retaining code highlighting. Read-only is the default.
2317
+ editable: bool = false,
2318
+ /// Receives each edit when `editable` is true. The source is
2319
+ /// controlled in exactly the same way as a textarea value.
2320
+ on_input: ?InputMsgFn = null,
2321
+ /// Prefix each logical source line with a muted, monospace
2322
+ /// number. Off by default.
2323
+ line_numbers: bool = false,
2324
+ /// Word-wrap long source lines. `false` keeps logical lines
2325
+ /// intact inside one horizontal scroll region.
2326
+ wrap: bool = true,
2327
+ width: f32 = 0,
2328
+ /// Definite code-region height. Overflow scrolls vertically;
2329
+ /// no-wrap regions scroll on both axes.
2330
+ height: f32 = 0,
2331
+ min_width: f32 = 0,
2332
+ grow: f32 = 0,
2333
+ semantics: canvas.WidgetSemantics = .{},
2334
+ };
2335
+
2336
+ /// Bare source-code content with bounded, themed syntax highlighting.
2337
+ /// The component owns layout, clipping, and scrolling, but deliberately
2338
+ /// supplies no background, border, radius, shadow, or padding. Wrap it
2339
+ /// in a panel or card when those presentation choices are wanted.
2340
+ /// Markdown fences lower through this same component.
2341
+ pub fn code(self: *Self, options: CodeOptions, source: []const u8) Node {
2342
+ const line_count = codeLineCount(source, options.editable);
2343
+ const terminal_editor_line = options.editable and source.len > 0 and source[source.len - 1] == '\n';
2344
+ const numbered = options.line_numbers and line_count - @intFromBool(terminal_editor_line) <=
2345
+ (if (options.editable) max_editable_code_lines else max_code_lines);
2346
+ if (options.editable) {
2347
+ const retained = if (options.wrap) blk: {
2348
+ // Wrapped editor geometry still uses the bounded span
2349
+ // paragraph path; no-wrap editors use the scalable
2350
+ // viewport tokenizer below.
2351
+ var state: code_model.HighlightState = .{};
2352
+ break :blk self.codeParagraphWithState(
2353
+ source,
2354
+ options.language,
2355
+ true,
2356
+ options.grow,
2357
+ &state,
2358
+ null,
2359
+ );
2360
+ } else blk: {
2361
+ const source_span = [_]canvas.TextSpan{.{
2362
+ .text = source,
2363
+ .monospace = true,
2364
+ .color = .syntax_plain,
2365
+ }};
2366
+ break :blk self.paragraph(
2367
+ .{ .wrap = false, .grow = options.grow },
2368
+ &source_span,
2369
+ );
2370
+ };
2371
+ var editor = self.el(.textarea, .{
2372
+ .key = options.key,
2373
+ .global_key = options.global_key,
2374
+ .width = options.width,
2375
+ .height = options.height,
2376
+ .min_width = options.min_width,
2377
+ .grow = options.grow,
2378
+ .semantics = options.semantics,
2379
+ .on_input = options.on_input,
2380
+ }, .{});
2381
+ // Retain the exact source once. Paint tokenizes visible
2382
+ // logical lines with `code_language`, keeping syntax
2383
+ // highlighting independent of document length.
2384
+ editor.widget.text = retained.widget.text;
2385
+ editor.widget.spans = retained.widget.spans;
2386
+ editor.widget.text_no_wrap = !options.wrap;
2387
+ editor.widget.code_line_number_digits = if (numbered)
2388
+ @intCast(decimalDigits(line_count))
2389
+ else
2390
+ 0;
2391
+ editor.widget.code_editor = true;
2392
+ editor.widget.code_language = options.language;
2393
+ editor.widget.layout.clip_content = true;
2394
+ return editor;
2395
+ }
2396
+ const content = if (numbered)
2397
+ self.numberedCodeParagraph(source, options.language, options.wrap, line_count)
2398
+ else
2399
+ self.codeParagraphChunks(source, options.language, options.wrap);
2400
+ const body = if (options.wrap)
2401
+ if (options.height > 0) blk: {
2402
+ // Generic scroll children stay viewport-sized by
2403
+ // contract. Put code in an internal flow track whose
2404
+ // non-growing paragraph retains its full wrapped
2405
+ // height, giving the vertical scroll walker an honest
2406
+ // descendant extent without remeasuring arbitrary
2407
+ // public scroll content.
2408
+ var tracked_content = content;
2409
+ tracked_content.widget.layout.grow = 0;
2410
+ const track = self.column(.{}, .{tracked_content});
2411
+ break :blk self.scroll(.{ .axis = .vertical, .grow = 1 }, .{track});
2412
+ } else content
2413
+ else blk: {
2414
+ // The engine scrollbar overlays the viewport's bottom
2415
+ // edge. Reserve one quiet band inside the scrollable
2416
+ // track so the final code baseline never sits under it.
2417
+ const track = self.column(.{}, .{
2418
+ content,
2419
+ self.el(.stack, .{ .height = 8 }, .{}),
2420
+ });
2421
+ break :blk self.scroll(.{
2422
+ .axis = if (options.height > 0) .both else .horizontal,
2423
+ .grow = 1,
2424
+ }, .{track});
2425
+ };
2426
+ var root = self.el(.column, .{
2427
+ .key = options.key,
2428
+ .global_key = options.global_key,
2429
+ .width = options.width,
2430
+ .height = options.height,
2431
+ .min_width = options.min_width,
2432
+ .grow = options.grow,
2433
+ .semantics = options.semantics,
2434
+ }, .{body});
2435
+ root.widget.layout.clip_content = true;
2436
+ return root;
2437
+ }
2438
+
2439
+ /// Keep numbered source in one selectable paragraph. The renderer
2440
+ /// owns its muted gutter, so marker digits never enter retained
2441
+ /// text or clipboard bytes; it derives each marker baseline from
2442
+ /// this paragraph's real wrapped layout.
2443
+ fn numberedCodeParagraph(
2444
+ self: *Self,
2445
+ source: []const u8,
2446
+ language: code_model.Language,
2447
+ wrap: bool,
2448
+ line_count: usize,
2449
+ ) Node {
2450
+ var state: code_model.HighlightState = .{};
2451
+ var source_node = self.codeParagraphWithState(source, language, wrap, 1, &state, null);
2452
+ source_node.widget.code_line_number_digits = @intCast(decimalDigits(line_count));
2453
+ return source_node;
2454
+ }
2455
+
2456
+ /// Keep ordinary code in one text widget so static selection and copy
2457
+ /// span logical lines. Only split when the paragraph layout's bounded
2458
+ /// line capacity requires it; every chunk remains independently
2459
+ /// visible instead of silently truncating a large source block.
2460
+ fn codeParagraphChunks(self: *Self, source: []const u8, language: code_model.Language, wrap: bool) Node {
2461
+ var state: code_model.HighlightState = .{};
2462
+ var budget: CodeSpanBudget = .{
2463
+ .remaining_chunks = codeParagraphChunkCount(source, wrap),
2464
+ };
2465
+ return self.codeParagraphChunksWithStateBudgeted(
2466
+ source,
2467
+ language,
2468
+ wrap,
2469
+ if (wrap) 1 else 0,
2470
+ &state,
2471
+ &budget,
2472
+ );
2473
+ }
2474
+
2475
+ fn codeParagraphChunksWithState(
2476
+ self: *Self,
2477
+ source: []const u8,
2478
+ language: code_model.Language,
2479
+ wrap: bool,
2480
+ grow: f32,
2481
+ state: *code_model.HighlightState,
2482
+ ) Node {
2483
+ return self.codeParagraphChunksWithStateBudgeted(
2484
+ source,
2485
+ language,
2486
+ wrap,
2487
+ grow,
2488
+ state,
2489
+ null,
2490
+ );
2491
+ }
2492
+
2493
+ fn codeParagraphChunksWithStateBudgeted(
2494
+ self: *Self,
2495
+ source: []const u8,
2496
+ language: code_model.Language,
2497
+ wrap: bool,
2498
+ grow: f32,
2499
+ state: *code_model.HighlightState,
2500
+ budget: ?*CodeSpanBudget,
2501
+ ) Node {
2502
+ const chunk_count = codeParagraphChunkCount(source, wrap);
2503
+ if (chunk_count == 1) {
2504
+ return self.codeParagraphWithState(source, language, wrap, grow, state, budget);
2505
+ }
2506
+ const chunks = self.arena.alloc(Node, chunk_count) catch {
2507
+ self.failed = true;
2508
+ return self.column(.{}, .{});
2509
+ };
2510
+ const group_fingerprint = std.hash.Wyhash.hash(0, source) | 1;
2511
+ var chunk_index: usize = 0;
2512
+ var chunk_start: usize = 0;
2513
+ while (chunk_start < source.len) {
2514
+ const chunk_end = codeParagraphChunkEnd(source, chunk_start, wrap);
2515
+ chunks[chunk_index] = self.codeParagraphWithState(
2516
+ source[chunk_start..chunk_end],
2517
+ language,
2518
+ wrap,
2519
+ 0,
2520
+ state,
2521
+ budget,
2522
+ );
2523
+ chunks[chunk_index].static_text_group_fingerprint = group_fingerprint;
2524
+ chunks[chunk_index].widget.static_text_group_offset = chunk_start;
2525
+ chunk_index += 1;
2526
+ chunk_start = chunk_end;
2527
+ }
2528
+ return self.column(.{ .grow = grow }, .{chunks[0..chunk_index]});
2529
+ }
2530
+
2531
+ fn codeParagraphWithState(
2532
+ self: *Self,
2533
+ source: []const u8,
2534
+ language: code_model.Language,
2535
+ wrap: bool,
2536
+ grow: f32,
2537
+ state: *code_model.HighlightState,
2538
+ budget: ?*CodeSpanBudget,
2539
+ ) Node {
2540
+ var storage: [canvas.text_spans.max_text_spans_per_paragraph]canvas.TextSpan = undefined;
2541
+ var highlighted = if (source.len == 0) blk: {
2542
+ storage[0] = .{ .text = source, .monospace = true, .color = .syntax_plain };
2543
+ break :blk storage[0..1];
2544
+ } else code_model.highlightWithState(source, language, &storage, state);
2545
+ if (budget) |span_budget| {
2546
+ std.debug.assert(span_budget.remaining_chunks > 0);
2547
+ span_budget.remaining_chunks -= 1;
2548
+ const highlighted_total = span_budget.used +
2549
+ highlighted.len +
2550
+ span_budget.remaining_chunks;
2551
+ if (highlighted_total <= max_code_spans_per_surface) {
2552
+ span_budget.used += highlighted.len;
2553
+ } else {
2554
+ storage[0] = .{
2555
+ .text = source,
2556
+ .monospace = true,
2557
+ .color = .syntax_plain,
2558
+ };
2559
+ highlighted = storage[0..1];
2560
+ span_budget.used += 1;
2561
+ }
2562
+ }
2563
+ return self.paragraph(.{ .wrap = wrap, .grow = grow }, highlighted);
2564
+ }
2565
+
2566
+ /// Upper bound for formatting renderer-owned logical-line markers.
2567
+ /// Sources above it keep every source byte and omit the gutter.
2568
+ pub const max_code_lines: usize = 128;
2569
+ /// Editable code paints only its viewport, so its line-number gutter
2570
+ /// can scale far beyond the bounded paragraph layout used by
2571
+ /// read-only snippets.
2572
+ pub const max_editable_code_lines: usize = 10_000;
2573
+ pub const max_code_spans_per_surface: usize = 512;
2574
+
2575
+ const CodeSpanBudget = struct {
2576
+ used: usize = 0,
2577
+ remaining_chunks: usize,
2578
+ };
2579
+
2580
+ fn codeParagraphChunkCount(source: []const u8, wrap: bool) usize {
2581
+ if (source.len == 0) return 1;
2582
+ var count: usize = 0;
2583
+ var start: usize = 0;
2584
+ while (start < source.len) {
2585
+ start = codeParagraphChunkEnd(source, start, wrap);
2586
+ count += 1;
2587
+ }
2588
+ return count;
2589
+ }
2590
+
2591
+ /// Pack complete logical lines while their UTF-8 scalar count fits
2592
+ /// the span layout's worst case (one glyph per visual line). A
2593
+ /// single over-capacity logical line stays whole: the viewport
2594
+ /// painter pages its visual runs without inserting a source break.
2595
+ fn codeParagraphChunkEnd(source: []const u8, start: usize, wrap: bool) usize {
2596
+ if (!wrap) {
2597
+ var cursor = start;
2598
+ var lines: usize = 0;
2599
+ while (cursor < source.len) : (cursor += 1) {
2600
+ if (source[cursor] != '\n') continue;
2601
+ lines += 1;
2602
+ if (lines >= max_code_logical_lines_per_paragraph and cursor + 1 < source.len) {
2603
+ return cursor + 1;
2604
+ }
2605
+ }
2606
+ return source.len;
2607
+ }
2608
+
2609
+ var cursor = start;
2610
+ var units: usize = 0;
2611
+ var lines: usize = 0;
2612
+ while (cursor < source.len) {
2613
+ const newline = std.mem.indexOfScalarPos(u8, source, cursor, '\n');
2614
+ const line_end = newline orelse source.len;
2615
+ const after_line = if (newline != null) line_end + 1 else line_end;
2616
+ // A trailing newline ends the final painted line without
2617
+ // adding another one. An empty source line still occupies
2618
+ // one visual line.
2619
+ const line_units = @max(1, codeScalarCount(source[cursor..line_end]));
2620
+ if (units + line_units > canvas.text_spans.max_text_span_lines_per_paragraph and cursor > start) {
2621
+ return cursor;
2622
+ }
2623
+ units += line_units;
2624
+ lines += 1;
2625
+ cursor = after_line;
2626
+ if (lines >= max_code_logical_lines_per_paragraph and cursor < source.len) return cursor;
2627
+ }
2628
+ return source.len;
2629
+ }
2630
+
2631
+ fn codeScalarCount(source: []const u8) usize {
2632
+ var count: usize = 0;
2633
+ var cursor: usize = 0;
2634
+ while (cursor < source.len) : (count += 1) {
2635
+ const sequence_len = std.unicode.utf8ByteSequenceLength(source[cursor]) catch 1;
2636
+ cursor += @min(sequence_len, source.len - cursor);
2637
+ }
2638
+ return count;
2639
+ }
2640
+
2641
+ // Keep the maximal 64 KiB newline-only source within both the
2642
+ // component's 512-span share and the runtime's 1024-node view cap:
2643
+ // 128 logical lines per paragraph yields at most 512 chunks.
2644
+ const max_code_logical_lines_per_paragraph: usize =
2645
+ canvas.text_spans.max_text_span_lines_per_paragraph;
2646
+
2647
+ fn codeLineCount(source: []const u8, include_terminal_line: bool) usize {
2648
+ if (source.len == 0) return 1;
2649
+ return std.mem.count(u8, source, "\n") +
2650
+ @intFromBool(include_terminal_line or source[source.len - 1] != '\n');
2651
+ }
2652
+
2653
+ fn decimalDigits(value: usize) usize {
2654
+ var remaining = value;
2655
+ var digits: usize = 1;
2656
+ while (remaining >= 10) : (remaining /= 10) digits += 1;
2657
+ return digits;
2658
+ }
2659
+
2292
2660
  pub const ChartOptions = struct {
2293
2661
  key: ?UiKey = null,
2294
2662
  global_key: ?UiKey = null,
@@ -2889,14 +3257,23 @@ pub fn Ui(comptime Msg: type) type {
2889
3257
  // way, matching the single-line measurement both layout paths
2890
3258
  // already perform; overflow policy (`overflow`, trailing
2891
3259
  // ellipsis by default) decides what happens past the frame.
2892
- // Span paragraphs keep wrapping.
2893
- if (node.wrap == false and widget.kind == .text and widget.spans.len == 0) {
3260
+ // Span paragraphs honor the same explicit no-wrap policy.
3261
+ // `Ui.code` uses this to keep highlighted logical lines
3262
+ // intact inside its horizontal scroll region.
3263
+ if (node.wrap == false and widget.kind == .text) {
2894
3264
  widget.text_no_wrap = true;
2895
3265
  }
2896
3266
  widget.id = if (node.global_key) |global_key|
2897
3267
  structuralId(global_id_seed, widget.kind, global_key)
2898
3268
  else
2899
3269
  structuralId(parent_id, widget.kind, key);
3270
+ if (node.static_text_group_fingerprint != 0) {
3271
+ widget.static_text_group_id = structuralId(
3272
+ parent_id,
3273
+ .stack,
3274
+ .{ .int = node.static_text_group_fingerprint },
3275
+ );
3276
+ }
2900
3277
  // Provenance record (write-back's read half): this is the one
2901
3278
  // point where the markup-stamped source and the just-assigned
2902
3279
  // structural id are both in hand. Explicit keys (loop item
@@ -3221,6 +3598,7 @@ pub fn Ui(comptime Msg: type) type {
3221
3598
  .image_id = options.image,
3222
3599
  .value = options.value,
3223
3600
  .value_x = options.value_x,
3601
+ .tree_level = options.tree_level,
3224
3602
  .terminal = .{ .pty = options.pty, .scrollback = options.scrollback },
3225
3603
  .scroll_axes = options.axis,
3226
3604
  .variant = options.variant,
@@ -1148,10 +1148,11 @@ pub const anchor_offset_value_message = "anchor-offset takes a literal number: t
1148
1148
  pub const anchor_dependent_attr_message = "anchor-alignment and anchor-offset only apply together with anchor - add anchor=\"below\" (or \"above\") to float this surface";
1149
1149
 
1150
1150
  /// Elements whose widget KIND the engine never hit-tests: layout and
1151
- /// decoration only. A bound `on-press`/`on-toggle` makes any element a
1152
- /// hit target (widget-level: the handler stamps the press/toggle action,
1153
- /// and presses on non-interactive content inside it fall through to it),
1154
- /// so those two are legal everywhere; the remaining value/text handlers
1151
+ /// decoration only. A bound `on-press`/`on-double-press`/`on-toggle`
1152
+ /// makes any element a hit target (widget-level: the handler stamps the
1153
+ /// press/toggle action, and presses on non-interactive content inside it
1154
+ /// fall through to it), so those three are legal everywhere; the
1155
+ /// remaining value/text handlers
1155
1156
  /// (`on-change`/`on-submit`/`on-input`) have no behavior to bind to on
1156
1157
  /// these elements and stay validation errors. Registry-derived from the
1157
1158
  /// `hit_target` element predicate, which mirrors the engine's kind
@@ -1173,7 +1174,7 @@ pub fn deadHandlerOnNonHitTarget(attr_name: []const u8) bool {
1173
1174
 
1174
1175
  pub const autofocus_element_message = "autofocus is only supported on focusable controls (text fields, buttons, checkboxes, ...) - it moves keyboard focus to the element when it mounts or when the flag turns on, and nothing about this element can take focus";
1175
1176
 
1176
- pub const non_hit_target_handler_message = "on-change/on-submit/on-input never fire here: this element has no control or text behavior - put them on a control (input, checkbox, slider) inside it (on-press/on-toggle are fine anywhere: a bound press handler makes any element pressable, and clicks on plain text or icons inside it fall through to it)";
1177
+ pub const non_hit_target_handler_message = "on-change/on-submit/on-input never fire here: this element has no control or text behavior - put them on a control (input, checkbox, slider) inside it (on-press/on-double-press/on-toggle are fine anywhere: a bound press handler makes any element pressable, and clicks on plain text or icons inside it fall through to it)";
1177
1178
 
1178
1179
  /// Elements whose widget kind layers its children on top of each other
1179
1180
  /// (every child gets the full content box), so `gap` can never space
@@ -1847,7 +1848,7 @@ pub const known_color_token_names = schema.color_token_names;
1847
1848
  pub const known_radius_token_names = schema.radius_token_names;
1848
1849
 
1849
1850
  pub const style_token_literal_message = "style token attributes take a literal token name - dynamic styling stays in Zig";
1850
- pub const unknown_color_token_message = "unknown color token: color style attributes take a canvas ColorTokens field name (background, surface, surface_subtle, surface_pressed, text, text_muted, border, accent, accent_text, destructive, destructive_text, success, success_text, warning, warning_text, info, info_text, focus_ring, shadow, scrim, disabled)";
1851
+ pub const unknown_color_token_message = "unknown color token: color style attributes take a canvas ColorTokens field name (background, surface, surface_subtle, surface_pressed, text, text_muted, syntax_plain, syntax_comment, syntax_keyword, syntax_literal, syntax_function, syntax_property, syntax_constant, border, accent, accent_text, destructive, destructive_text, success, success_text, warning, warning_text, info, info_text, focus_ring, shadow, scrim, disabled)";
1851
1852
  pub const unknown_radius_token_message = "unknown radius token: radius takes a canvas RadiusTokens field name (sm, md, lg, xl)";
1852
1853
 
1853
1854
  pub const for_children_message = "for takes one or more element children (elements, use, if/else, or a nested for) - text content is only allowed inside text-bearing elements";
@@ -1865,6 +1866,10 @@ pub const markdown_issue_link_base_message = "issue-link-base takes a literal UR
1865
1866
  pub const markdown_on_link_message = "on-link takes a bare Msg tag whose payload is the pressed link URL (a []const u8 variant, like open_url: []const u8)";
1866
1867
  pub const markdown_on_details_message = "on-details takes a bare Msg tag whose payload is the details block index (a usize variant, like toggle_details: usize)";
1867
1868
  pub const markdown_details_expanded_message = "details-expanded takes one {binding} naming a []const bool iterable (a model field, pub decl, or fn - the same sources for each accepts)";
1869
+ pub const code_source_message = "code requires a source attribute with one {binding} naming the source text (a []const u8 field or fn - arena fns work)";
1870
+ pub const code_children_message = "code takes no children or text content - the source binding provides the code";
1871
+ pub const code_attr_message = "unknown attribute for code - it takes source, language, editable, on-input, line-numbers, wrap, width, height, min-width, grow, key, global-key, and label";
1872
+ pub const code_language_message = "language takes a literal lexer name: plain, zig, javascript/js/mjs, typescript/ts, jsx/tsx, json, yaml/yml, shell/sh/bash/zsh, python/py, rust/rs, c/cpp/c++/csharp/java/kotlin/swift, go, html/xml/svg, css/scss/less, sql, or markdown/md";
1868
1873
  pub const stepper_active_message = "stepper requires an active attribute (a number or one {binding}) naming the active step index";
1869
1874
  pub const stepper_attr_message = "unknown attribute for stepper - it takes active, key, global-key, and label";
1870
1875
  pub const stepper_children_message = "stepper takes only step children (each step is a text leaf: <step>Work</step>)";
@@ -2215,6 +2220,71 @@ fn validateMarkdown(node: MarkupNode) ?MarkupErrorInfo {
2215
2220
  return null;
2216
2221
  }
2217
2222
 
2223
+ fn codeLanguageName(name: []const u8) bool {
2224
+ // Keep this tooling-safe vocabulary synchronized with
2225
+ // code.isLanguageName. ui_markup is also compiled as a standalone CLI
2226
+ // module, where importing the complete canvas lexer graph would make its
2227
+ // source files belong to multiple Zig modules.
2228
+ const names = "plain text zig js javascript mjs jsx ts typescript tsx json jsonc yaml yml sh bash zsh shell py python rs rust c h cc cpp c++ cs csharp java kotlin swift go golang html xml svg css scss less sql md markdown";
2229
+ var known = std.mem.tokenizeScalar(u8, names, ' ');
2230
+ while (known.next()) |candidate| {
2231
+ if (std.ascii.eqlIgnoreCase(name, candidate)) return true;
2232
+ }
2233
+ return false;
2234
+ }
2235
+
2236
+ /// `<code>` is a source-bound leaf lowered through `Ui.code`: syntax
2237
+ /// language is static markup, while flags and layout values can bind.
2238
+ fn validateCode(node: MarkupNode) ?MarkupErrorInfo {
2239
+ for (node.children) |child| return errorAt(child, code_children_message);
2240
+ var has_source = false;
2241
+ for (node.attrs) |attribute| {
2242
+ if (std.mem.eql(u8, attribute.name, "source")) {
2243
+ has_source = true;
2244
+ const expression = parseAttrExpression(attribute.value);
2245
+ if (expression == null or expression.? != .binding) return attrError(node, attribute, code_source_message);
2246
+ continue;
2247
+ }
2248
+ if (std.mem.eql(u8, attribute.name, "language")) {
2249
+ const expression = parseAttrExpression(attribute.value);
2250
+ if (expression == null or expression.? != .literal or !codeLanguageName(expression.?.literal)) {
2251
+ return attrError(node, attribute, code_language_message);
2252
+ }
2253
+ continue;
2254
+ }
2255
+ if (std.mem.eql(u8, attribute.name, "line-numbers") or
2256
+ std.mem.eql(u8, attribute.name, "wrap") or
2257
+ std.mem.eql(u8, attribute.name, "editable"))
2258
+ {
2259
+ if (attribute.value.len == 0) continue;
2260
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2261
+ return attrError(node, attribute, message);
2262
+ }
2263
+ continue;
2264
+ }
2265
+ if (std.mem.eql(u8, attribute.name, "on-input")) {
2266
+ if (parseMessageExpression(attribute.value) == null) {
2267
+ return attrError(node, attribute, "invalid message expression: on-* takes a Msg tag (\"add\") or tag with one binding payload (\"toggle:{item.id}\")");
2268
+ }
2269
+ continue;
2270
+ }
2271
+ const known = std.mem.eql(u8, attribute.name, "width") or
2272
+ std.mem.eql(u8, attribute.name, "height") or
2273
+ std.mem.eql(u8, attribute.name, "min-width") or
2274
+ std.mem.eql(u8, attribute.name, "grow") or
2275
+ std.mem.eql(u8, attribute.name, "label") or
2276
+ std.mem.eql(u8, attribute.name, "key") or
2277
+ std.mem.eql(u8, attribute.name, "global-key");
2278
+ if (!known) return attrError(node, attribute, code_attr_message);
2279
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2280
+ return attrError(node, attribute, message);
2281
+ }
2282
+ if (attrCoverageError(node, attribute)) |info| return info;
2283
+ }
2284
+ if (!has_source) return errorAt(node, code_source_message);
2285
+ return null;
2286
+ }
2287
+
2218
2288
  /// `<stepper active="{index}">` takes only `<step>` text-leaf children:
2219
2289
  /// each step's state (completed/active/pending) derives from its position
2220
2290
  /// against the active index, so steps carry no attributes of their own.
@@ -2806,7 +2876,7 @@ fn validateVideo(node: MarkupNode) ?MarkupErrorInfo {
2806
2876
  /// The rule hooks the composite registry entries name. A registry entry
2807
2877
  /// whose hook this table does not implement is a compile error (below),
2808
2878
  /// so attachment and implementation can never drift.
2809
- const rule_hook_names = [_][]const u8{ "markdown", "stepper", "step", "timeline", "timeline-item", "chart", "series", "context-menu", "input-group", "input-group-actions", "span", "reactions", "video" };
2879
+ const rule_hook_names = [_][]const u8{ "markdown", "code", "stepper", "step", "timeline", "timeline-item", "chart", "series", "context-menu", "input-group", "input-group-actions", "span", "reactions", "video" };
2810
2880
 
2811
2881
  comptime {
2812
2882
  for (schema.elements) |entry| {
@@ -2826,6 +2896,7 @@ comptime {
2826
2896
  /// a worse inner language than plain Zig.
2827
2897
  fn validateRuleHook(hook: []const u8, document: MarkupDocument, node: MarkupNode, parent_element: ?[]const u8, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2828
2898
  if (std.mem.eql(u8, hook, "markdown")) return validateMarkdown(node);
2899
+ if (std.mem.eql(u8, hook, "code")) return validateCode(node);
2829
2900
  if (std.mem.eql(u8, hook, "stepper")) return validateStepper(node);
2830
2901
  if (std.mem.eql(u8, hook, "step")) {
2831
2902
  // Steps inside a stepper are consumed by validateStepper; one