@native-sdk/cli 0.6.2 → 0.7.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 (64) hide show
  1. package/build.zig +8 -0
  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 +62 -21
  6. package/skill-data/native-ui/SKILL.md +17 -2
  7. package/src/platform/macos/appkit_host.h +2 -0
  8. package/src/platform/macos/appkit_host.m +36 -10
  9. package/src/platform/macos/root.zig +7 -1
  10. package/src/platform/types.zig +2 -0
  11. package/src/primitives/canvas/code.zig +590 -0
  12. package/src/primitives/canvas/code_tests.zig +1062 -0
  13. package/src/primitives/canvas/equality.zig +3 -1
  14. package/src/primitives/canvas/events.zig +4 -0
  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 +167 -4
  18. package/src/primitives/canvas/root.zig +15 -2
  19. package/src/primitives/canvas/tests.zig +1 -0
  20. package/src/primitives/canvas/text.zig +10 -0
  21. package/src/primitives/canvas/text_interaction.zig +164 -22
  22. package/src/primitives/canvas/text_layout.zig +107 -21
  23. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  24. package/src/primitives/canvas/text_span_tests.zig +254 -0
  25. package/src/primitives/canvas/text_spans.zig +556 -32
  26. package/src/primitives/canvas/text_tests.zig +86 -0
  27. package/src/primitives/canvas/themes/geist.zig +29 -0
  28. package/src/primitives/canvas/tokens.zig +72 -2
  29. package/src/primitives/canvas/ui.zig +325 -21
  30. package/src/primitives/canvas/ui_markup.zig +59 -2
  31. package/src/primitives/canvas/ui_markup_compiled.zig +76 -0
  32. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  33. package/src/primitives/canvas/ui_markup_contract.zig +34 -0
  34. package/src/primitives/canvas/ui_markup_reflect.zig +20 -3
  35. package/src/primitives/canvas/ui_markup_view.zig +73 -0
  36. package/src/primitives/canvas/ui_markup_view_tests.zig +101 -0
  37. package/src/primitives/canvas/ui_schema.zig +17 -6
  38. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  39. package/src/primitives/canvas/ui_tests.zig +6 -0
  40. package/src/primitives/canvas/widget_invalidation.zig +3 -0
  41. package/src/primitives/canvas/widget_layout.zig +57 -8
  42. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  43. package/src/primitives/canvas/widget_metrics.zig +30 -1
  44. package/src/primitives/canvas/widget_render.zig +454 -9
  45. package/src/primitives/canvas/widget_runtime.zig +1 -0
  46. package/src/primitives/canvas/widget_text_input.zig +23 -11
  47. package/src/primitives/canvas/widget_text_select.zig +2 -2
  48. package/src/primitives/canvas/widgets.zig +13 -0
  49. package/src/root.zig +1 -0
  50. package/src/runtime/api.zig +9 -0
  51. package/src/runtime/canvas_frame_helpers.zig +1 -0
  52. package/src/runtime/canvas_limits.zig +7 -0
  53. package/src/runtime/canvas_widget_accessibility_tests.zig +27 -1
  54. package/src/runtime/canvas_widget_clipboard_tests.zig +146 -0
  55. package/src/runtime/canvas_widget_context_menu.zig +12 -2
  56. package/src/runtime/canvas_widget_display.zig +15 -1
  57. package/src/runtime/canvas_widget_events.zig +50 -20
  58. package/src/runtime/canvas_widget_runtime.zig +74 -12
  59. package/src/runtime/canvas_widget_state.zig +1 -0
  60. package/src/runtime/canvas_widget_text_tests.zig +1935 -70
  61. package/src/runtime/gpu_surface_events.zig +38 -0
  62. package/src/runtime/view.zig +37 -3
  63. package/src/runtime/view_widget_text.zig +1242 -14
  64. package/src/runtime/view_widget_tree.zig +2 -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");
@@ -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 {
@@ -937,6 +936,11 @@ pub fn Ui(comptime Msg: type) type {
937
936
  on_terminal: ?TerminalMsgFn = null,
938
937
  context_menu: []const ContextMenuItem = &.{},
939
938
  nodes: []const Node = &.{},
939
+ /// Internal source fingerprint for adjacent code paragraphs
940
+ /// that form one selectable document. `finalizeNode` combines
941
+ /// it with their parent structural id into a source-sensitive
942
+ /// group identity.
943
+ static_text_group_fingerprint: u64 = 0,
940
944
  /// Markup authoring provenance, stamped by the markup engines
941
945
  /// when the builder carries a `provenance_sink`; null for
942
946
  /// builder-authored (Zig) nodes, which is itself the honest
@@ -1024,6 +1028,14 @@ pub fn Ui(comptime Msg: type) type {
1024
1028
  },
1025
1029
  .set_selection => |selection| blk: {
1026
1030
  const Selection = @FieldType(Payload, "set_selection");
1031
+ if (comptime @hasField(Selection, "affinity")) {
1032
+ const Affinity = @FieldType(Selection, "affinity");
1033
+ break :blk @unionInit(Payload, "set_selection", .{
1034
+ .anchor = num(@FieldType(Selection, "anchor"), selection.anchor),
1035
+ .focus = num(@FieldType(Selection, "focus"), selection.focus),
1036
+ .affinity = @field(Affinity, @tagName(selection.affinity)),
1037
+ });
1038
+ }
1027
1039
  break :blk @unionInit(Payload, "set_selection", .{
1028
1040
  .anchor = num(@FieldType(Selection, "anchor"), selection.anchor),
1029
1041
  .focus = num(@FieldType(Selection, "focus"), selection.focus),
@@ -1392,22 +1404,19 @@ pub fn Ui(comptime Msg: type) type {
1392
1404
  // consumers, tests); the textarea newline mapping
1393
1405
  // resolves BEFORE it because the generic key mapping
1394
1406
  // has no Enter case.
1395
- const edit = if (keyboard.edit != null)
1396
- keyboard.edit
1397
- else
1398
- canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse keyboard.textEditEvent();
1399
- if (edit) |text_edit| {
1400
- // Single-line kinds sanitize the edit with the
1401
- // SAME rule the runtime seam applies before
1402
- // stamping (strip line breaks; suppress inserts
1403
- // that strip to nothing), so the fallback
1404
- // derivation for events that never crossed the
1405
- // runtime can never feed a model mirror bytes
1406
- // the retained editor would refuse. Stamped
1407
- // edits are already sanitized and pass through
1408
- // untouched.
1409
- if (canvas.sanitizedSingleLineTextInputEvent(widget.kind, text_edit)) |sanitized| {
1410
- if (self.msgForTextEdit(target_id, sanitized)) |msg| return msg;
1407
+ if (keyboard.edit) |stamped| {
1408
+ // Runtime stamps are authoritative. In particular,
1409
+ // history replay can restore exact model-provided
1410
+ // bytes that the new-input sanitizer would strip.
1411
+ if (self.msgForTextEdit(target_id, stamped)) |msg| return msg;
1412
+ } else {
1413
+ const locally_derived = canvas.widgetKeyboardNewlineTextEditEvent(widget.kind, keyboard) orelse keyboard.textEditEvent();
1414
+ if (locally_derived) |text_edit| {
1415
+ // Direct Tree consumers still sanitize locally:
1416
+ // these bytes have not crossed the runtime seam.
1417
+ if (canvas.sanitizedSingleLineTextInputEvent(widget.kind, text_edit)) |sanitized| {
1418
+ if (self.msgForTextEdit(target_id, sanitized)) |msg| return msg;
1419
+ }
1411
1420
  }
1412
1421
  }
1413
1422
  }
@@ -2284,6 +2293,292 @@ pub fn Ui(comptime Msg: type) type {
2284
2293
  return self.el(.stack, .{ .grow = grow }, .{});
2285
2294
  }
2286
2295
 
2296
+ pub const CodeOptions = struct {
2297
+ key: ?UiKey = null,
2298
+ global_key: ?UiKey = null,
2299
+ language: code_model.Language = .plain,
2300
+ /// Prefix each logical source line with a muted, monospace
2301
+ /// number. Off by default.
2302
+ line_numbers: bool = false,
2303
+ /// Word-wrap long source lines. `false` keeps logical lines
2304
+ /// intact inside one horizontal scroll region.
2305
+ wrap: bool = true,
2306
+ width: f32 = 0,
2307
+ /// Definite surface height. Overflow scrolls vertically;
2308
+ /// no-wrap surfaces scroll on both axes.
2309
+ height: f32 = 0,
2310
+ min_width: f32 = 0,
2311
+ grow: f32 = 0,
2312
+ semantics: canvas.WidgetSemantics = .{},
2313
+ };
2314
+
2315
+ /// A themed source-code surface with bounded syntax highlighting.
2316
+ /// Markdown fences lower through this same component.
2317
+ pub fn code(self: *Self, options: CodeOptions, source: []const u8) Node {
2318
+ const line_count = codeLineCount(source);
2319
+ const numbered = options.line_numbers and line_count <= max_code_lines;
2320
+ const content = if (numbered)
2321
+ self.numberedCodeParagraph(source, options.language, options.wrap, line_count)
2322
+ else
2323
+ self.codeParagraphChunks(source, options.language, options.wrap);
2324
+ const body = if (options.wrap)
2325
+ if (options.height > 0) blk: {
2326
+ // Generic scroll children stay viewport-sized by
2327
+ // contract. Put code in an internal flow track whose
2328
+ // non-growing paragraph retains its full wrapped
2329
+ // height, giving the vertical scroll walker an honest
2330
+ // descendant extent without remeasuring arbitrary
2331
+ // public scroll content.
2332
+ var tracked_content = content;
2333
+ tracked_content.widget.layout.grow = 0;
2334
+ const track = self.column(.{}, .{tracked_content});
2335
+ break :blk self.scroll(.{ .axis = .vertical, .grow = 1 }, .{track});
2336
+ } else content
2337
+ else blk: {
2338
+ // The engine scrollbar overlays the viewport's bottom
2339
+ // edge. Reserve one quiet band inside the scrollable
2340
+ // track so the final code baseline never sits under it.
2341
+ const track = self.column(.{}, .{
2342
+ content,
2343
+ self.el(.stack, .{ .height = 8 }, .{}),
2344
+ });
2345
+ break :blk self.scroll(.{
2346
+ .axis = if (options.height > 0) .both else .horizontal,
2347
+ .grow = 1,
2348
+ }, .{track});
2349
+ };
2350
+ var surface = self.el(.panel, .{
2351
+ .key = options.key,
2352
+ .global_key = options.global_key,
2353
+ .width = options.width,
2354
+ .height = options.height,
2355
+ .min_width = options.min_width,
2356
+ .grow = options.grow,
2357
+ .padding = 12,
2358
+ .style_tokens = .{ .background = .surface_subtle },
2359
+ .semantics = options.semantics,
2360
+ }, .{body});
2361
+ surface.widget.layout.clip_content = true;
2362
+ return surface;
2363
+ }
2364
+
2365
+ /// Keep numbered source in one selectable paragraph. The renderer
2366
+ /// owns its muted gutter, so marker digits never enter retained
2367
+ /// text or clipboard bytes; it derives each marker baseline from
2368
+ /// this paragraph's real wrapped layout.
2369
+ fn numberedCodeParagraph(
2370
+ self: *Self,
2371
+ source: []const u8,
2372
+ language: code_model.Language,
2373
+ wrap: bool,
2374
+ line_count: usize,
2375
+ ) Node {
2376
+ var state: code_model.HighlightState = .{};
2377
+ var source_node = self.codeParagraphWithState(source, language, wrap, 1, &state, null);
2378
+ source_node.widget.code_line_number_digits = @intCast(decimalDigits(line_count));
2379
+ return source_node;
2380
+ }
2381
+
2382
+ /// Keep ordinary code in one text widget so static selection and copy
2383
+ /// span logical lines. Only split when the paragraph layout's bounded
2384
+ /// line capacity requires it; every chunk remains independently
2385
+ /// visible instead of silently truncating a large source block.
2386
+ fn codeParagraphChunks(self: *Self, source: []const u8, language: code_model.Language, wrap: bool) Node {
2387
+ var state: code_model.HighlightState = .{};
2388
+ var budget: CodeSpanBudget = .{
2389
+ .remaining_chunks = codeParagraphChunkCount(source, wrap),
2390
+ };
2391
+ return self.codeParagraphChunksWithStateBudgeted(
2392
+ source,
2393
+ language,
2394
+ wrap,
2395
+ if (wrap) 1 else 0,
2396
+ &state,
2397
+ &budget,
2398
+ );
2399
+ }
2400
+
2401
+ fn codeParagraphChunksWithState(
2402
+ self: *Self,
2403
+ source: []const u8,
2404
+ language: code_model.Language,
2405
+ wrap: bool,
2406
+ grow: f32,
2407
+ state: *code_model.HighlightState,
2408
+ ) Node {
2409
+ return self.codeParagraphChunksWithStateBudgeted(
2410
+ source,
2411
+ language,
2412
+ wrap,
2413
+ grow,
2414
+ state,
2415
+ null,
2416
+ );
2417
+ }
2418
+
2419
+ fn codeParagraphChunksWithStateBudgeted(
2420
+ self: *Self,
2421
+ source: []const u8,
2422
+ language: code_model.Language,
2423
+ wrap: bool,
2424
+ grow: f32,
2425
+ state: *code_model.HighlightState,
2426
+ budget: ?*CodeSpanBudget,
2427
+ ) Node {
2428
+ const chunk_count = codeParagraphChunkCount(source, wrap);
2429
+ if (chunk_count == 1) {
2430
+ return self.codeParagraphWithState(source, language, wrap, grow, state, budget);
2431
+ }
2432
+ const chunks = self.arena.alloc(Node, chunk_count) catch {
2433
+ self.failed = true;
2434
+ return self.column(.{}, .{});
2435
+ };
2436
+ const group_fingerprint = std.hash.Wyhash.hash(0, source) | 1;
2437
+ var chunk_index: usize = 0;
2438
+ var chunk_start: usize = 0;
2439
+ while (chunk_start < source.len) {
2440
+ const chunk_end = codeParagraphChunkEnd(source, chunk_start, wrap);
2441
+ chunks[chunk_index] = self.codeParagraphWithState(
2442
+ source[chunk_start..chunk_end],
2443
+ language,
2444
+ wrap,
2445
+ 0,
2446
+ state,
2447
+ budget,
2448
+ );
2449
+ chunks[chunk_index].static_text_group_fingerprint = group_fingerprint;
2450
+ chunks[chunk_index].widget.static_text_group_offset = chunk_start;
2451
+ chunk_index += 1;
2452
+ chunk_start = chunk_end;
2453
+ }
2454
+ return self.column(.{ .grow = grow }, .{chunks[0..chunk_index]});
2455
+ }
2456
+
2457
+ fn codeParagraphWithState(
2458
+ self: *Self,
2459
+ source: []const u8,
2460
+ language: code_model.Language,
2461
+ wrap: bool,
2462
+ grow: f32,
2463
+ state: *code_model.HighlightState,
2464
+ budget: ?*CodeSpanBudget,
2465
+ ) Node {
2466
+ var storage: [canvas.text_spans.max_text_spans_per_paragraph]canvas.TextSpan = undefined;
2467
+ var highlighted = if (source.len == 0) blk: {
2468
+ storage[0] = .{ .text = source, .monospace = true, .color = .syntax_plain };
2469
+ break :blk storage[0..1];
2470
+ } else code_model.highlightWithState(source, language, &storage, state);
2471
+ if (budget) |span_budget| {
2472
+ std.debug.assert(span_budget.remaining_chunks > 0);
2473
+ span_budget.remaining_chunks -= 1;
2474
+ const highlighted_total = span_budget.used +
2475
+ highlighted.len +
2476
+ span_budget.remaining_chunks;
2477
+ if (highlighted_total <= max_code_spans_per_surface) {
2478
+ span_budget.used += highlighted.len;
2479
+ } else {
2480
+ storage[0] = .{
2481
+ .text = source,
2482
+ .monospace = true,
2483
+ .color = .syntax_plain,
2484
+ };
2485
+ highlighted = storage[0..1];
2486
+ span_budget.used += 1;
2487
+ }
2488
+ }
2489
+ return self.paragraph(.{ .wrap = wrap, .grow = grow }, highlighted);
2490
+ }
2491
+
2492
+ /// Upper bound for formatting renderer-owned logical-line markers.
2493
+ /// Sources above it keep every source byte and omit the gutter.
2494
+ pub const max_code_lines: usize = 128;
2495
+ pub const max_code_spans_per_surface: usize = 512;
2496
+
2497
+ const CodeSpanBudget = struct {
2498
+ used: usize = 0,
2499
+ remaining_chunks: usize,
2500
+ };
2501
+
2502
+ fn codeParagraphChunkCount(source: []const u8, wrap: bool) usize {
2503
+ if (source.len == 0) return 1;
2504
+ var count: usize = 0;
2505
+ var start: usize = 0;
2506
+ while (start < source.len) {
2507
+ start = codeParagraphChunkEnd(source, start, wrap);
2508
+ count += 1;
2509
+ }
2510
+ return count;
2511
+ }
2512
+
2513
+ /// Pack complete logical lines while their UTF-8 scalar count fits
2514
+ /// the span layout's worst case (one glyph per visual line). A
2515
+ /// single over-capacity logical line stays whole: the viewport
2516
+ /// painter pages its visual runs without inserting a source break.
2517
+ fn codeParagraphChunkEnd(source: []const u8, start: usize, wrap: bool) usize {
2518
+ if (!wrap) {
2519
+ var cursor = start;
2520
+ var lines: usize = 0;
2521
+ while (cursor < source.len) : (cursor += 1) {
2522
+ if (source[cursor] != '\n') continue;
2523
+ lines += 1;
2524
+ if (lines >= max_code_logical_lines_per_paragraph and cursor + 1 < source.len) {
2525
+ return cursor + 1;
2526
+ }
2527
+ }
2528
+ return source.len;
2529
+ }
2530
+
2531
+ var cursor = start;
2532
+ var units: usize = 0;
2533
+ var lines: usize = 0;
2534
+ while (cursor < source.len) {
2535
+ const newline = std.mem.indexOfScalarPos(u8, source, cursor, '\n');
2536
+ const line_end = newline orelse source.len;
2537
+ const after_line = if (newline != null) line_end + 1 else line_end;
2538
+ // A trailing newline ends the final painted line without
2539
+ // adding another one. An empty source line still occupies
2540
+ // one visual line.
2541
+ const line_units = @max(1, codeScalarCount(source[cursor..line_end]));
2542
+ if (units + line_units > canvas.text_spans.max_text_span_lines_per_paragraph and cursor > start) {
2543
+ return cursor;
2544
+ }
2545
+ units += line_units;
2546
+ lines += 1;
2547
+ cursor = after_line;
2548
+ if (lines >= max_code_logical_lines_per_paragraph and cursor < source.len) return cursor;
2549
+ }
2550
+ return source.len;
2551
+ }
2552
+
2553
+ fn codeScalarCount(source: []const u8) usize {
2554
+ var count: usize = 0;
2555
+ var cursor: usize = 0;
2556
+ while (cursor < source.len) : (count += 1) {
2557
+ const sequence_len = std.unicode.utf8ByteSequenceLength(source[cursor]) catch 1;
2558
+ cursor += @min(sequence_len, source.len - cursor);
2559
+ }
2560
+ return count;
2561
+ }
2562
+
2563
+ // Keep the maximal 64 KiB newline-only source within both the
2564
+ // component's 512-span share and the runtime's 1024-node view cap:
2565
+ // 128 logical lines per paragraph yields at most 512 chunks.
2566
+ const max_code_logical_lines_per_paragraph: usize =
2567
+ canvas.text_spans.max_text_span_lines_per_paragraph;
2568
+
2569
+ fn codeLineCount(source: []const u8) usize {
2570
+ if (source.len == 0) return 1;
2571
+ return std.mem.count(u8, source, "\n") +
2572
+ @intFromBool(source[source.len - 1] != '\n');
2573
+ }
2574
+
2575
+ fn decimalDigits(value: usize) usize {
2576
+ var remaining = value;
2577
+ var digits: usize = 1;
2578
+ while (remaining >= 10) : (remaining /= 10) digits += 1;
2579
+ return digits;
2580
+ }
2581
+
2287
2582
  pub const ChartOptions = struct {
2288
2583
  key: ?UiKey = null,
2289
2584
  global_key: ?UiKey = null,
@@ -2884,14 +3179,23 @@ pub fn Ui(comptime Msg: type) type {
2884
3179
  // way, matching the single-line measurement both layout paths
2885
3180
  // already perform; overflow policy (`overflow`, trailing
2886
3181
  // ellipsis by default) decides what happens past the frame.
2887
- // Span paragraphs keep wrapping.
2888
- if (node.wrap == false and widget.kind == .text and widget.spans.len == 0) {
3182
+ // Span paragraphs honor the same explicit no-wrap policy.
3183
+ // `Ui.code` uses this to keep highlighted logical lines
3184
+ // intact inside its horizontal scroll region.
3185
+ if (node.wrap == false and widget.kind == .text) {
2889
3186
  widget.text_no_wrap = true;
2890
3187
  }
2891
3188
  widget.id = if (node.global_key) |global_key|
2892
3189
  structuralId(global_id_seed, widget.kind, global_key)
2893
3190
  else
2894
3191
  structuralId(parent_id, widget.kind, key);
3192
+ if (node.static_text_group_fingerprint != 0) {
3193
+ widget.static_text_group_id = structuralId(
3194
+ parent_id,
3195
+ .stack,
3196
+ .{ .int = node.static_text_group_fingerprint },
3197
+ );
3198
+ }
2895
3199
  // Provenance record (write-back's read half): this is the one
2896
3200
  // point where the markup-stamped source and the just-assigned
2897
3201
  // structural id are both in hand. Explicit keys (loop item
@@ -1847,7 +1847,7 @@ pub const known_color_token_names = schema.color_token_names;
1847
1847
  pub const known_radius_token_names = schema.radius_token_names;
1848
1848
 
1849
1849
  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)";
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, 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
1851
  pub const unknown_radius_token_message = "unknown radius token: radius takes a canvas RadiusTokens field name (sm, md, lg, xl)";
1852
1852
 
1853
1853
  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 +1865,10 @@ pub const markdown_issue_link_base_message = "issue-link-base takes a literal UR
1865
1865
  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
1866
  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
1867
  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)";
1868
+ 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)";
1869
+ pub const code_children_message = "code takes no children or text content - the source binding provides the code";
1870
+ pub const code_attr_message = "unknown attribute for code - it takes source, language, line-numbers, wrap, width, height, min-width, grow, key, global-key, and label";
1871
+ pub const code_language_message = "language takes a literal lexer name: plain, zig, javascript/js, typescript/ts, jsx/tsx, json, shell/sh/bash/zsh, python/py, rust/rs, c/cpp/c++/csharp/java/kotlin/swift, go, html/xml/svg, css/scss/less, or sql";
1868
1872
  pub const stepper_active_message = "stepper requires an active attribute (a number or one {binding}) naming the active step index";
1869
1873
  pub const stepper_attr_message = "unknown attribute for stepper - it takes active, key, global-key, and label";
1870
1874
  pub const stepper_children_message = "stepper takes only step children (each step is a text leaf: <step>Work</step>)";
@@ -2215,6 +2219,58 @@ fn validateMarkdown(node: MarkupNode) ?MarkupErrorInfo {
2215
2219
  return null;
2216
2220
  }
2217
2221
 
2222
+ fn codeLanguageName(name: []const u8) bool {
2223
+ const names = "plain text zig js javascript jsx ts typescript tsx json jsonc 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";
2224
+ var known = std.mem.tokenizeScalar(u8, names, ' ');
2225
+ while (known.next()) |candidate| {
2226
+ if (std.ascii.eqlIgnoreCase(name, candidate)) return true;
2227
+ }
2228
+ return false;
2229
+ }
2230
+
2231
+ /// `<code>` is a source-bound leaf lowered through `Ui.code`: syntax
2232
+ /// language is static markup, while flags and layout values can bind.
2233
+ fn validateCode(node: MarkupNode) ?MarkupErrorInfo {
2234
+ for (node.children) |child| return errorAt(child, code_children_message);
2235
+ var has_source = false;
2236
+ for (node.attrs) |attribute| {
2237
+ if (std.mem.eql(u8, attribute.name, "source")) {
2238
+ has_source = true;
2239
+ const expression = parseAttrExpression(attribute.value);
2240
+ if (expression == null or expression.? != .binding) return attrError(node, attribute, code_source_message);
2241
+ continue;
2242
+ }
2243
+ if (std.mem.eql(u8, attribute.name, "language")) {
2244
+ const expression = parseAttrExpression(attribute.value);
2245
+ if (expression == null or expression.? != .literal or !codeLanguageName(expression.?.literal)) {
2246
+ return attrError(node, attribute, code_language_message);
2247
+ }
2248
+ continue;
2249
+ }
2250
+ if (std.mem.eql(u8, attribute.name, "line-numbers") or std.mem.eql(u8, attribute.name, "wrap")) {
2251
+ if (attribute.value.len == 0) continue;
2252
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2253
+ return attrError(node, attribute, message);
2254
+ }
2255
+ continue;
2256
+ }
2257
+ const known = std.mem.eql(u8, attribute.name, "width") or
2258
+ std.mem.eql(u8, attribute.name, "height") or
2259
+ std.mem.eql(u8, attribute.name, "min-width") or
2260
+ std.mem.eql(u8, attribute.name, "grow") or
2261
+ std.mem.eql(u8, attribute.name, "label") or
2262
+ std.mem.eql(u8, attribute.name, "key") or
2263
+ std.mem.eql(u8, attribute.name, "global-key");
2264
+ if (!known) return attrError(node, attribute, code_attr_message);
2265
+ if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2266
+ return attrError(node, attribute, message);
2267
+ }
2268
+ if (attrCoverageError(node, attribute)) |info| return info;
2269
+ }
2270
+ if (!has_source) return errorAt(node, code_source_message);
2271
+ return null;
2272
+ }
2273
+
2218
2274
  /// `<stepper active="{index}">` takes only `<step>` text-leaf children:
2219
2275
  /// each step's state (completed/active/pending) derives from its position
2220
2276
  /// against the active index, so steps carry no attributes of their own.
@@ -2806,7 +2862,7 @@ fn validateVideo(node: MarkupNode) ?MarkupErrorInfo {
2806
2862
  /// The rule hooks the composite registry entries name. A registry entry
2807
2863
  /// whose hook this table does not implement is a compile error (below),
2808
2864
  /// 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" };
2865
+ 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
2866
 
2811
2867
  comptime {
2812
2868
  for (schema.elements) |entry| {
@@ -2826,6 +2882,7 @@ comptime {
2826
2882
  /// a worse inner language than plain Zig.
2827
2883
  fn validateRuleHook(hook: []const u8, document: MarkupDocument, node: MarkupNode, parent_element: ?[]const u8, template_limit: usize, slot_rule: SlotRule) ?MarkupErrorInfo {
2828
2884
  if (std.mem.eql(u8, hook, "markdown")) return validateMarkdown(node);
2885
+ if (std.mem.eql(u8, hook, "code")) return validateCode(node);
2829
2886
  if (std.mem.eql(u8, hook, "stepper")) return validateStepper(node);
2830
2887
  if (std.mem.eql(u8, hook, "step")) {
2831
2888
  // Steps inside a stepper are consumed by validateStepper; one
@@ -263,6 +263,9 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
263
263
  if (comptime std.mem.eql(u8, node.name, "markdown")) {
264
264
  return buildMarkdown(node, entries, ui, model, scope);
265
265
  }
266
+ if (comptime std.mem.eql(u8, node.name, "code")) {
267
+ return buildCode(node, entries, ui, model, scope);
268
+ }
266
269
  if (comptime std.mem.eql(u8, node.name, "stepper")) {
267
270
  return buildStepper(node, entries, ui, model, scope);
268
271
  }
@@ -776,6 +779,79 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
776
779
  return Md.view(ui, source_text, options);
777
780
  }
778
781
 
782
+ // ----------------------------------------------------------- code
783
+
784
+ fn buildCode(comptime node: markup.MarkupNode, comptime entries: []const ScopeEntry, ui: *Ui, model: *const ModelT, scope: anytype) Ui.Node {
785
+ comptime {
786
+ if (node.children.len != 0) fail(node.children[0], markup.code_children_message);
787
+ for (node.attrs) |attribute| {
788
+ if (std.mem.eql(u8, attribute.name, "kind")) continue;
789
+ const known = std.mem.eql(u8, attribute.name, "source") or
790
+ std.mem.eql(u8, attribute.name, "language") or
791
+ std.mem.eql(u8, attribute.name, "line-numbers") or
792
+ std.mem.eql(u8, attribute.name, "wrap") or
793
+ std.mem.eql(u8, attribute.name, "width") or
794
+ std.mem.eql(u8, attribute.name, "height") or
795
+ std.mem.eql(u8, attribute.name, "min-width") or
796
+ std.mem.eql(u8, attribute.name, "grow") or
797
+ std.mem.eql(u8, attribute.name, "label") or
798
+ std.mem.eql(u8, attribute.name, "key") or
799
+ std.mem.eql(u8, attribute.name, "global-key");
800
+ if (!known) fail(node, markup.code_attr_message);
801
+ }
802
+ }
803
+ const source_path = comptime blk: {
804
+ const raw = node.attr("source") orelse fail(node, markup.code_source_message);
805
+ const expression = markup.parseAttrExpression(raw) orelse fail(node, markup.code_source_message);
806
+ if (expression != .binding) fail(node, markup.code_source_message);
807
+ break :blk expression.binding;
808
+ };
809
+ comptime requireVariant(pathVariant(node, entries, source_path, true), &.{.string}, node, markup.code_source_message);
810
+ const source = switch (bindingValue(node, entries, source_path, ui, model, scope, true)) {
811
+ .string => |text| text,
812
+ else => runtimeFail([]const u8, ui),
813
+ };
814
+
815
+ var options: Ui.CodeOptions = .{};
816
+ if (comptime (node.attr("language") != null)) {
817
+ const name = comptime blk: {
818
+ const expression = markup.parseAttrExpression(node.attr("language").?) orelse fail(node, markup.code_language_message);
819
+ if (expression != .literal) fail(node, markup.code_language_message);
820
+ if (!canvas.code.isLanguageName(expression.literal)) fail(node, markup.code_language_message);
821
+ break :blk expression.literal;
822
+ };
823
+ options.language = canvas.code.languageFromName(name);
824
+ }
825
+ if (comptime (node.attr("line-numbers") != null)) {
826
+ options.line_numbers = videoFlagValue(node, entries, comptime node.attr("line-numbers").?, ui, model, scope);
827
+ }
828
+ if (comptime (node.attr("wrap") != null)) {
829
+ options.wrap = videoFlagValue(node, entries, comptime node.attr("wrap").?, ui, model, scope);
830
+ }
831
+ if (comptime (node.attr("width") != null)) {
832
+ options.width = floatAttr(node, entries, comptime node.attr("width").?, ui, model, scope);
833
+ }
834
+ if (comptime (node.attr("height") != null)) {
835
+ options.height = floatAttr(node, entries, comptime node.attr("height").?, ui, model, scope);
836
+ }
837
+ if (comptime (node.attr("min-width") != null)) {
838
+ options.min_width = floatAttr(node, entries, comptime node.attr("min-width").?, ui, model, scope);
839
+ }
840
+ if (comptime (node.attr("grow") != null)) {
841
+ options.grow = floatAttr(node, entries, comptime node.attr("grow").?, ui, model, scope);
842
+ }
843
+ if (comptime (node.attr("label") != null)) {
844
+ options.semantics.label = stringAttr(node, entries, comptime node.attr("label").?, ui, model, scope, "label expects text");
845
+ }
846
+ if (comptime (node.attr("key") != null)) {
847
+ options.key = attrKey(node, entries, comptime node.attr("key").?, ui, model, scope, "keys must be integers or strings");
848
+ }
849
+ if (comptime (node.attr("global-key") != null)) {
850
+ options.global_key = attrKey(node, entries, comptime node.attr("global-key").?, ui, model, scope, "keys must be integers or strings");
851
+ }
852
+ return ui.code(options, source);
853
+ }
854
+
779
855
  fn markdownLinkConstructor(comptime node: markup.MarkupNode, comptime raw: []const u8) Ui.LinkMsgFn {
780
856
  comptime {
781
857
  @setEvalBranchQuota(10_000);
@@ -1089,6 +1089,39 @@ test "compiled markdown element matches the interpreter and the hand-written Md.
1089
1089
  try testing.expectEqual(summary_item.id, fixture.findByKind(expanded_compiled.root, .list_item).?.id);
1090
1090
  }
1091
1091
 
1092
+ // ------------------------------------------------------ code element parity
1093
+
1094
+ const CodeUi = fixture.CodeUi;
1095
+ const CodeInterpreter = markup_view.MarkupView(fixture.CodeModel, fixture.CodeMsg);
1096
+ const CodeCompiled = canvas.CompiledMarkupView(fixture.CodeModel, fixture.CodeMsg, fixture.code_markup_source);
1097
+
1098
+ test "compiled code element matches the interpreter and Ui.code" {
1099
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
1100
+ defer arena_state.deinit();
1101
+ const arena = arena_state.allocator();
1102
+ var model = fixture.CodeModel{};
1103
+
1104
+ var view = try CodeInterpreter.init(arena, fixture.code_markup_source);
1105
+ var interpreted_ui = CodeUi.init(arena);
1106
+ const interpreted = try interpreted_ui.finalize(try view.build(&interpreted_ui, &model));
1107
+ var compiled_ui = CodeUi.init(arena);
1108
+ const compiled = try compiled_ui.finalize(CodeCompiled.build(&compiled_ui, &model));
1109
+ var hand_ui = CodeUi.init(arena);
1110
+ const hand = try hand_ui.finalize(fixture.handCodeView(&hand_ui, &model));
1111
+
1112
+ try expectSameTree(fixture.CodeMsg, hand, interpreted);
1113
+ try expectSameTree(fixture.CodeMsg, hand, compiled);
1114
+ try expectSameTexts(interpreted.root, compiled.root);
1115
+ try testing.expectEqual(canvas.ScrollAxes.horizontal, fixture.findByKind(compiled.root, .scroll_view).?.scroll_axes);
1116
+
1117
+ model.wrap_code = true;
1118
+ model.show_lines = false;
1119
+ var wrapped_ui = CodeUi.init(arena);
1120
+ const wrapped = try wrapped_ui.finalize(CodeCompiled.build(&wrapped_ui, &model));
1121
+ try testing.expect(fixture.findByKind(wrapped.root, .scroll_view) == null);
1122
+ try testing.expect(fixture.findByText(wrapped.root, .text, "1") == null);
1123
+ }
1124
+
1092
1125
  // ------------------------------------------- template/use + style parity
1093
1126
 
1094
1127
  fn expectSameStyles(expected: canvas.Widget, actual: canvas.Widget) !void {