@native-sdk/cli 0.7.0 → 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 (52) 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 +9 -7
  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 +451 -33
  13. package/src/primitives/canvas/code_tests.zig +855 -5
  14. package/src/primitives/canvas/events.zig +111 -1
  15. package/src/primitives/canvas/markdown_tests.zig +17 -18
  16. package/src/primitives/canvas/root.zig +4 -0
  17. package/src/primitives/canvas/text.zig +6 -0
  18. package/src/primitives/canvas/ui.zig +108 -29
  19. package/src/primitives/canvas/ui_markup.zig +23 -9
  20. package/src/primitives/canvas/ui_markup_compiled.zig +13 -0
  21. package/src/primitives/canvas/ui_markup_compiled_tests.zig +12 -0
  22. package/src/primitives/canvas/ui_markup_contract.zig +8 -1
  23. package/src/primitives/canvas/ui_markup_view.zig +16 -0
  24. package/src/primitives/canvas/ui_markup_view_tests.zig +71 -5
  25. package/src/primitives/canvas/ui_schema.zig +13 -0
  26. package/src/primitives/canvas/ui_schema_tests.zig +9 -7
  27. package/src/primitives/canvas/ui_tests.zig +26 -0
  28. package/src/primitives/canvas/widget_invalidation.zig +1 -0
  29. package/src/primitives/canvas/widget_metrics.zig +10 -5
  30. package/src/primitives/canvas/widget_render.zig +660 -39
  31. package/src/primitives/canvas/widget_render_controls.zig +4 -4
  32. package/src/primitives/canvas/widget_runtime.zig +2 -0
  33. package/src/primitives/canvas/widget_text_input.zig +165 -8
  34. package/src/primitives/canvas/widget_tree.zig +6 -5
  35. package/src/primitives/canvas/widgets.zig +25 -0
  36. package/src/runtime/canvas_budget_edge_tests.zig +3 -2
  37. package/src/runtime/canvas_limits.zig +13 -6
  38. package/src/runtime/canvas_widget_clipboard_tests.zig +7 -4
  39. package/src/runtime/canvas_widget_context_menu.zig +7 -2
  40. package/src/runtime/canvas_widget_event_tests.zig +18 -14
  41. package/src/runtime/canvas_widget_events.zig +51 -20
  42. package/src/runtime/canvas_widget_runtime.zig +105 -4
  43. package/src/runtime/canvas_widget_scroll_driver_tests.zig +59 -0
  44. package/src/runtime/canvas_widget_split_tree_tests.zig +100 -0
  45. package/src/runtime/canvas_widget_state.zig +27 -0
  46. package/src/runtime/canvas_widget_text_tests.zig +326 -0
  47. package/src/runtime/core.zig +15 -5
  48. package/src/runtime/gpu_surface_events.zig +12 -12
  49. package/src/runtime/view.zig +54 -16
  50. package/src/runtime/view_widget_scroll.zig +48 -18
  51. package/src/runtime/view_widget_text.zig +54 -13
  52. package/src/runtime/window_view_runtime.zig +9 -0
@@ -134,6 +134,104 @@ pub fn widgetKeyboardNewlineTextEditEvent(kind: WidgetKind, event: WidgetKeyboar
134
134
  return .{ .insert_text = "\n" };
135
135
  }
136
136
 
137
+ /// Editable code owns a plain Tab as indentation input. The file's
138
+ /// leading whitespace votes for tabs versus spaces; space widths 2..8
139
+ /// compete by how many indentation levels they divide cleanly, with the
140
+ /// wider width winning exact ties (4-space files also divide by 2).
141
+ /// Ambiguous or unindented source falls back to two spaces.
142
+ pub fn widgetCodeTabTextEditEvent(widget: Widget, event: WidgetKeyboardEvent) ?TextInputEvent {
143
+ if (widget.kind != .textarea or !widget.code_editor or widget.state.disabled) return null;
144
+ if (event.phase != .key_down or event.focus_moved or event.text.len != 0) return null;
145
+ if (event.modifiers.shift or event.modifiers.hasNavigationModifier()) return null;
146
+ if (!std.ascii.eqlIgnoreCase(event.key, "tab")) return null;
147
+ return .{ .insert_text = codeIndentationInsertion(widget) };
148
+ }
149
+
150
+ const CodeIndentKind = enum { none, spaces, tabs };
151
+
152
+ fn codeIndentationInsertion(widget: Widget) []const u8 {
153
+ var tab_lines: usize = 0;
154
+ var space_lines: usize = 0;
155
+ var space_width_scores: [9]usize = @splat(0);
156
+ var only_space_indent: ?usize = null;
157
+
158
+ var line_start: usize = 0;
159
+ while (line_start <= widget.text.len) {
160
+ const newline = std.mem.indexOfScalarPos(u8, widget.text, line_start, '\n');
161
+ const line_end = newline orelse widget.text.len;
162
+ const line = widget.text[line_start..line_end];
163
+ var cursor: usize = 0;
164
+ var spaces: usize = 0;
165
+ var tabs: usize = 0;
166
+ while (cursor < line.len) : (cursor += 1) {
167
+ switch (line[cursor]) {
168
+ ' ' => spaces += 1,
169
+ '\t' => tabs += 1,
170
+ else => break,
171
+ }
172
+ }
173
+ // Whitespace-only lines do not state a file convention.
174
+ if (cursor < line.len and cursor > 0) {
175
+ if (tabs > 0) {
176
+ tab_lines += 1;
177
+ } else {
178
+ space_lines += 1;
179
+ only_space_indent = if (space_lines == 1) spaces else null;
180
+ for (2..space_width_scores.len) |width| {
181
+ if (spaces % width == 0) space_width_scores[width] += 1;
182
+ }
183
+ }
184
+ }
185
+
186
+ if (newline == null) break;
187
+ line_start = line_end + 1;
188
+ }
189
+
190
+ const selection = widget.text_selection orelse text_model.TextSelection.collapsed(widget.text.len);
191
+ const local_kind = codeIndentKindAt(widget.text, selection.focus);
192
+ const tabs_win = tab_lines > space_lines or
193
+ (tab_lines == space_lines and tab_lines > 0 and local_kind == .tabs);
194
+ if (tabs_win) return "\t";
195
+
196
+ var inferred_width: usize = 2;
197
+ if (space_lines == 1) {
198
+ const width = only_space_indent orelse 0;
199
+ if (width >= 2 and width <= 8) inferred_width = width;
200
+ } else if (space_lines > 1) {
201
+ var best_width: usize = 2;
202
+ var best_score: usize = 0;
203
+ for (2..space_width_scores.len) |width| {
204
+ const score = space_width_scores[width];
205
+ if (score > best_score or (score == best_score and score > 0 and width > best_width)) {
206
+ best_width = width;
207
+ best_score = score;
208
+ }
209
+ }
210
+ if (best_score * 2 >= space_lines) inferred_width = best_width;
211
+ }
212
+
213
+ return switch (inferred_width) {
214
+ 3 => " ",
215
+ 4 => " ",
216
+ 5 => " ",
217
+ 6 => " ",
218
+ 7 => " ",
219
+ 8 => " ",
220
+ else => " ",
221
+ };
222
+ }
223
+
224
+ fn codeIndentKindAt(text: []const u8, offset: usize) CodeIndentKind {
225
+ const caret = @min(offset, text.len);
226
+ const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..caret], '\n')) |newline| newline + 1 else 0;
227
+ if (line_start >= text.len) return .none;
228
+ return switch (text[line_start]) {
229
+ '\t' => .tabs,
230
+ ' ' => .spaces,
231
+ else => .none,
232
+ };
233
+ }
234
+
137
235
  /// The single-line text-entry kinds: their value can never hold a line
138
236
  /// break (Enter submits instead of editing — see
139
237
  /// `widgetKeyboardNewlineTextEditEvent`), so text inserted into them
@@ -152,7 +250,7 @@ pub fn widgetKindSingleLineTextEntry(kind: WidgetKind) bool {
152
250
  /// runtime's per-view widget-text budget
153
251
  /// (`max_canvas_widget_text_bytes_per_view`), the largest insert the
154
252
  /// editor could accept anyway.
155
- const max_sanitized_text_edit_bytes: usize = 65536;
253
+ const max_sanitized_text_edit_bytes: usize = text_model.max_widget_text_bytes_per_view;
156
254
  const SanitizedTextEditScratch = struct {
157
255
  bytes: [max_sanitized_text_edit_bytes]u8,
158
256
  };
@@ -946,3 +1044,15 @@ test "sanitizedSingleLineTextInputEvent strips composition text and shifts the p
946
1044
  const multi = sanitizedSingleLineTextInputEvent(.textarea, .{ .set_composition = .{ .text = "a\nb" } }).?;
947
1045
  try testing.expectEqualStrings("a\nb", multi.set_composition.text);
948
1046
  }
1047
+
1048
+ test "sanitizedSingleLineTextInputEvent sanitizes inserts above the former 64 KiB ceiling" {
1049
+ const testing = std.testing;
1050
+ const input = try testing.allocator.alloc(u8, 65537);
1051
+ defer testing.allocator.free(input);
1052
+ @memset(input, 'a');
1053
+ input[32768] = '\n';
1054
+
1055
+ const sanitized = sanitizedSingleLineTextInputEvent(.text_field, .{ .insert_text = input }).?;
1056
+ try testing.expectEqual(@as(usize, input.len - 1), sanitized.insert_text.len);
1057
+ try testing.expect(std.mem.indexOfAny(u8, sanitized.insert_text, "\r\n") == null);
1058
+ }
@@ -203,8 +203,8 @@ test "markdown maps lists, task lists, code fences, quotes, and rules" {
203
203
  try testing.expectEqual(canvas.WidgetKind.column, ordered_row.children[0].kind);
204
204
  try testing.expectEqualStrings("1.", ordered_row.children[0].children[0].text);
205
205
 
206
- // The fenced block is a panel wrapping highlighted mono spans.
207
- try testing.expectEqual(@as(usize, 1), countKind(tree.root, .panel));
206
+ // Fences use the same deliberately bare code component.
207
+ try testing.expectEqual(@as(usize, 0), countKind(tree.root, .panel));
208
208
  const code = findParagraphContaining(tree.root, "const x = 1;").?;
209
209
  try testing.expect(code.spans[0].monospace);
210
210
  try testing.expectEqual(@as(?canvas.TextSpanColor, .syntax_keyword), code.spans[0].color);
@@ -223,22 +223,22 @@ test "language-tagged code fences highlight tokens and preserve indentation" {
223
223
  \\```
224
224
  , .{});
225
225
 
226
- const panel = findKind(tree.root, .panel).?;
226
+ const code = findParagraphContaining(tree.root, "pub fn main() void").?;
227
227
  var source_text: std.ArrayListUnmanaged(u8) = .empty;
228
228
  defer source_text.deinit(testing.allocator);
229
- try appendParagraphText(panel, &source_text, testing.allocator);
229
+ try appendParagraphText(code, &source_text, testing.allocator);
230
230
  try testing.expectEqualStrings(
231
231
  "pub fn main() void {\n const message = \"hello\";\n // keep this indentation\n return 42;\n}",
232
232
  source_text.items,
233
233
  );
234
- try testing.expect(allSpansMonospace(panel));
235
- try testing.expect(hasSpan(panel, "pub", .syntax_keyword));
236
- try testing.expect(hasSpan(panel, "void", .syntax_literal));
237
- try testing.expect(hasSpan(panel, "\"hello\"", .syntax_literal));
238
- try testing.expect(hasSpan(panel, "// keep this indentation", .syntax_comment));
239
- try testing.expect(hasSpan(panel, "42", .syntax_literal));
240
-
241
- const indented = findParagraphContaining(panel, "const message").?;
234
+ try testing.expect(allSpansMonospace(code));
235
+ try testing.expect(hasSpan(code, "pub", .syntax_keyword));
236
+ try testing.expect(hasSpan(code, "void", .syntax_literal));
237
+ try testing.expect(hasSpan(code, "\"hello\"", .syntax_literal));
238
+ try testing.expect(hasSpan(code, "// keep this indentation", .syntax_comment));
239
+ try testing.expect(hasSpan(code, "42", .syntax_literal));
240
+
241
+ const indented = findParagraphContaining(code, "const message").?;
242
242
  var runs: [text_spans.max_text_span_runs_per_paragraph]text_spans.TextSpanRun = undefined;
243
243
  const layout = text_spans.layoutTextSpans(indented.spans, .{ .size = 14, .max_width = 10_000 }, &runs);
244
244
  var indented_keyword_x: ?f32 = null;
@@ -284,12 +284,11 @@ test "per-line syntax highlighting does not drop fenced code" {
284
284
  var doc = TestDoc.init();
285
285
  defer doc.deinit();
286
286
  const tree = try doc.build(source, .{});
287
- const panel = findKind(tree.root, .panel).?;
288
287
  var rendered: std.ArrayListUnmanaged(u8) = .empty;
289
288
  defer rendered.deinit(testing.allocator);
290
- try appendParagraphText(panel, &rendered, testing.allocator);
289
+ try appendParagraphText(tree.root, &rendered, testing.allocator);
291
290
  try testing.expectEqualStrings(code_source, rendered.items);
292
- try testing.expect(hasSpan(panel, "const", .syntax_keyword));
291
+ try testing.expect(hasSpan(tree.root, "const", .syntax_keyword));
293
292
  }
294
293
 
295
294
  test "details blocks are caller-controlled collapsibles" {
@@ -480,7 +479,7 @@ test "the README-shaped fixture renders through the mapper and the reference ren
480
479
  const cli_link = findRoleLabel(tree.root, .link, "`flg`").?;
481
480
  const open_msg = tree.msgForPointer(cli_link.id, .up).?;
482
481
  try testing.expectEqualStrings("https://example.com/flg", open_msg.open_url);
483
- try testing.expect(countKind(tree.root, .panel) >= 2); // fenced code blocks
482
+ try testing.expectEqual(@as(usize, 0), countKind(tree.root, .panel));
484
483
 
485
484
  // Layout + emit + reference-render the document; the pixel signature is
486
485
  // the golden. Estimator-driven and provider-free: deterministic.
@@ -549,11 +548,11 @@ test "the README-shaped fixture renders through the mapper and the reference ren
549
548
  // scales, wrapped bullets and em-dash spacing at the face's real
550
549
  // advances, real sans and mono outlines (fixed-pitch runs sit in their
551
550
  // 0.6 em cells), GFM tables as borderless cells on hairline row
552
- // separators, fenced-code panels with preserved source indentation and
551
+ // separators, bare fenced code with preserved source indentation and
553
552
  // language-token colors, and near-black underlined links.
554
553
  // Update deliberately when markdown rendering changes, reviewing the
555
554
  // rendered pixels first (see reference_tests.zig conventions).
556
- const markdown_document_reference_signature: u64 = 12721641780797724784;
555
+ const markdown_document_reference_signature: u64 = 5787917808851547223;
557
556
 
558
557
  fn markdownGoldenDumpRequested() bool {
559
558
  if (comptime !@import("builtin").link_libc) return false;
@@ -204,6 +204,7 @@ pub const TextCaretDirection = text_model.TextCaretDirection;
204
204
  pub const TextCaretMove = text_model.TextCaretMove;
205
205
  pub const TextCompositionUpdate = text_model.TextCompositionUpdate;
206
206
  pub const TextInputEvent = text_model.TextInputEvent;
207
+ pub const max_widget_text_bytes_per_view = text_model.max_widget_text_bytes_per_view;
207
208
  pub const TextEditState = text_model.TextEditState;
208
209
  pub const TextBuffer = text_model.TextBuffer;
209
210
 
@@ -637,6 +638,7 @@ pub const WidgetInvalidation = event_model.WidgetInvalidation;
637
638
  pub const WidgetClipboardAction = event_model.WidgetClipboardAction;
638
639
  pub const widgetKeyboardClipboardAction = event_model.widgetKeyboardClipboardAction;
639
640
  pub const widgetKeyboardNewlineTextEditEvent = event_model.widgetKeyboardNewlineTextEditEvent;
641
+ pub const widgetCodeTabTextEditEvent = event_model.widgetCodeTabTextEditEvent;
640
642
  pub const widgetKindSingleLineTextEntry = event_model.widgetKindSingleLineTextEntry;
641
643
  pub const sanitizedSingleLineTextInputEvent = event_model.sanitizedSingleLineTextInputEvent;
642
644
  pub const widgetKeyboardControlIntent = event_model.widgetKeyboardControlIntent;
@@ -718,6 +720,8 @@ pub const textInputViewportForWidget = widget_runtime.textInputViewportForWidget
718
720
  pub const textInputClearButtonRect = widget_runtime.textInputClearButtonRect;
719
721
  pub const textInputClearButtonHitRect = widget_runtime.textInputClearButtonHitRect;
720
722
  pub const textInputContentExtentForWidget = widget_runtime.textInputContentExtentForWidget;
723
+ pub const textInputContentWidthForWidget = widget_runtime.textInputContentWidthForWidget;
724
+ pub const cacheTextInputContentWidthForWidget = widget_runtime.cacheTextInputContentWidthForWidget;
721
725
  pub const textInputMaxScrollOffsetForWidget = widget_runtime.textInputMaxScrollOffsetForWidget;
722
726
  pub const clampedTextInputScrollOffsetForWidget = widget_runtime.clampedTextInputScrollOffsetForWidget;
723
727
  pub const textInputMaxHorizontalScrollOffsetForWidget = widget_runtime.textInputMaxHorizontalScrollOffsetForWidget;
@@ -2,6 +2,12 @@ const text_atlas = @import("text_atlas.zig");
2
2
  const text_layout = @import("text_layout.zig");
3
3
  const text_interaction = @import("text_interaction.zig");
4
4
 
5
+ /// Largest retained widget-text pool a view may expose. Text-event
6
+ /// sanitization and defensive single-line presentation share this ceiling
7
+ /// with the runtime so an insert the editor can accept is never too large for
8
+ /// those correctness seams to rewrite.
9
+ pub const max_widget_text_bytes_per_view: usize = 512 * 1024;
10
+
5
11
  pub const Glyph = text_atlas.Glyph;
6
12
  pub const GlyphAtlasKey = text_atlas.GlyphAtlasKey;
7
13
  pub const GlyphAtlasEntry = text_atlas.GlyphAtlasEntry;
@@ -304,8 +304,8 @@ pub const VirtualWindowRecord = struct {
304
304
 
305
305
  pub const UiHandlerEvent = enum {
306
306
  press,
307
- /// A multi-click press (click_count >= 2 on the release): the
308
- /// 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`:
309
309
  /// a double-click release prefers this handler and falls back to
310
310
  /// `.press`, so binding it is strictly additive — the first click
311
311
  /// of every double-click still dispatches the single-press message
@@ -558,6 +558,10 @@ pub fn Ui(comptime Msg: type) type {
558
558
  /// via `on_toggle`). Model-owned: the view renders child
559
559
  /// rows only while expanded.
560
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,
561
565
  disabled: bool = false,
562
566
  /// Image resource reference for image-bearing widgets
563
567
  /// (`image`, `icon_button`, `avatar`): a `canvas.ImageId` the
@@ -762,14 +766,14 @@ pub fn Ui(comptime Msg: type) type {
762
766
  /// the live bottom. Meaningless on every other element.
763
767
  scrollback: u32 = 0,
764
768
  on_press: ?Msg = null,
765
- /// Double-click Msg (builder-only): dispatched on a release
766
- /// whose click count reached 2, in place of `on_press` for
767
- /// that release. The FIRST click of the double still
768
- /// dispatches `on_press` on its own release, so the natural
769
- /// pairing is select-on-press + act-on-double-press (a list
770
- /// row that selects on click and opens/plays on double
771
- /// click). Like `on_press`, binding it makes the element a
772
- /// 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.
773
777
  on_double_press: ?Msg = null,
774
778
  on_toggle: ?Msg = null,
775
779
  on_change: ?Msg = null,
@@ -1359,14 +1363,14 @@ pub fn Ui(comptime Msg: type) type {
1359
1363
  }
1360
1364
 
1361
1365
  /// `msgForPointer` with the pointer's click count: a release
1362
- /// whose count reached 2 prefers the widget's `on_double_press`
1366
+ /// whose count is exactly 2 prefers the widget's `on_double_press`
1363
1367
  /// handler and falls back to the ordinary press resolution
1364
1368
  /// (so a double-click on a widget without the double channel
1365
1369
  /// behaves exactly like two single clicks). This is the
1366
1370
  /// dispatcher the runtime pointer path uses; the two-argument
1367
1371
  /// form stays the single-click entry point.
1368
1372
  pub fn msgForPointerClick(self: Tree, target_id: ObjectId, phase: canvas.WidgetPointerPhase, click_count: u8) ?Msg {
1369
- if (phase == .up and click_count >= 2) {
1373
+ if (phase == .up and click_count == 2) {
1370
1374
  if (self.msgFor(target_id, .double_press)) |msg| return msg;
1371
1375
  }
1372
1376
  return self.msgForPointer(target_id, phase);
@@ -1377,6 +1381,14 @@ pub fn Ui(comptime Msg: type) type {
1377
1381
  /// entry widgets.
1378
1382
  pub fn msgForKeyboard(self: Tree, target_id: ObjectId, keyboard: canvas.WidgetKeyboardEvent) ?Msg {
1379
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
+ }
1380
1392
  // A list row prefers a bound submit handler on plain
1381
1393
  // Enter: Enter is the row's PRIMARY action (open the
1382
1394
  // record, play the track — the desktop list convention),
@@ -1410,7 +1422,9 @@ pub fn Ui(comptime Msg: type) type {
1410
1422
  // bytes that the new-input sanitizer would strip.
1411
1423
  if (self.msgForTextEdit(target_id, stamped)) |msg| return msg;
1412
1424
  } else {
1413
- 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();
1414
1428
  if (locally_derived) |text_edit| {
1415
1429
  // Direct Tree consumers still sanitize locally:
1416
1430
  // these bytes have not crossed the runtime seam.
@@ -1865,11 +1879,12 @@ pub fn Ui(comptime Msg: type) type {
1865
1879
  /// Disclosure-tree container: descendant rows carrying
1866
1880
  /// `role = .treeitem` (at any nesting depth) form one roving
1867
1881
  /// keyboard focus set with the ARIA tree keymap — Up/Down walk
1868
- /// visible rows (selection follows focus through each row's
1869
- /// `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,
1870
1884
  /// Right expands or moves to the first child row, Home/End jump
1871
- /// to the edges. Expansion is model-owned: expandable rows set
1872
- /// `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`.
1873
1888
  pub fn tree(self: *Self, options: ElementOptions, children: anytype) Node {
1874
1889
  return self.el(.tree, options, children);
1875
1890
  }
@@ -2297,6 +2312,12 @@ pub fn Ui(comptime Msg: type) type {
2297
2312
  key: ?UiKey = null,
2298
2313
  global_key: ?UiKey = null,
2299
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,
2300
2321
  /// Prefix each logical source line with a muted, monospace
2301
2322
  /// number. Off by default.
2302
2323
  line_numbers: bool = false,
@@ -2304,19 +2325,74 @@ pub fn Ui(comptime Msg: type) type {
2304
2325
  /// intact inside one horizontal scroll region.
2305
2326
  wrap: bool = true,
2306
2327
  width: f32 = 0,
2307
- /// Definite surface height. Overflow scrolls vertically;
2308
- /// no-wrap surfaces scroll on both axes.
2328
+ /// Definite code-region height. Overflow scrolls vertically;
2329
+ /// no-wrap regions scroll on both axes.
2309
2330
  height: f32 = 0,
2310
2331
  min_width: f32 = 0,
2311
2332
  grow: f32 = 0,
2312
2333
  semantics: canvas.WidgetSemantics = .{},
2313
2334
  };
2314
2335
 
2315
- /// A themed source-code surface with bounded syntax highlighting.
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.
2316
2340
  /// Markdown fences lower through this same component.
2317
2341
  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;
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
+ }
2320
2396
  const content = if (numbered)
2321
2397
  self.numberedCodeParagraph(source, options.language, options.wrap, line_count)
2322
2398
  else
@@ -2347,19 +2423,17 @@ pub fn Ui(comptime Msg: type) type {
2347
2423
  .grow = 1,
2348
2424
  }, .{track});
2349
2425
  };
2350
- var surface = self.el(.panel, .{
2426
+ var root = self.el(.column, .{
2351
2427
  .key = options.key,
2352
2428
  .global_key = options.global_key,
2353
2429
  .width = options.width,
2354
2430
  .height = options.height,
2355
2431
  .min_width = options.min_width,
2356
2432
  .grow = options.grow,
2357
- .padding = 12,
2358
- .style_tokens = .{ .background = .surface_subtle },
2359
2433
  .semantics = options.semantics,
2360
2434
  }, .{body});
2361
- surface.widget.layout.clip_content = true;
2362
- return surface;
2435
+ root.widget.layout.clip_content = true;
2436
+ return root;
2363
2437
  }
2364
2438
 
2365
2439
  /// Keep numbered source in one selectable paragraph. The renderer
@@ -2492,6 +2566,10 @@ pub fn Ui(comptime Msg: type) type {
2492
2566
  /// Upper bound for formatting renderer-owned logical-line markers.
2493
2567
  /// Sources above it keep every source byte and omit the gutter.
2494
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;
2495
2573
  pub const max_code_spans_per_surface: usize = 512;
2496
2574
 
2497
2575
  const CodeSpanBudget = struct {
@@ -2566,10 +2644,10 @@ pub fn Ui(comptime Msg: type) type {
2566
2644
  const max_code_logical_lines_per_paragraph: usize =
2567
2645
  canvas.text_spans.max_text_span_lines_per_paragraph;
2568
2646
 
2569
- fn codeLineCount(source: []const u8) usize {
2647
+ fn codeLineCount(source: []const u8, include_terminal_line: bool) usize {
2570
2648
  if (source.len == 0) return 1;
2571
2649
  return std.mem.count(u8, source, "\n") +
2572
- @intFromBool(source[source.len - 1] != '\n');
2650
+ @intFromBool(include_terminal_line or source[source.len - 1] != '\n');
2573
2651
  }
2574
2652
 
2575
2653
  fn decimalDigits(value: usize) usize {
@@ -3520,6 +3598,7 @@ pub fn Ui(comptime Msg: type) type {
3520
3598
  .image_id = options.image,
3521
3599
  .value = options.value,
3522
3600
  .value_x = options.value_x,
3601
+ .tree_level = options.tree_level,
3523
3602
  .terminal = .{ .pty = options.pty, .scrollback = options.scrollback },
3524
3603
  .scroll_axes = options.axis,
3525
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
@@ -1867,8 +1868,8 @@ pub const markdown_on_details_message = "on-details takes a bare Msg tag whose p
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)";
1868
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)";
1869
1870
  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";
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";
1872
1873
  pub const stepper_active_message = "stepper requires an active attribute (a number or one {binding}) naming the active step index";
1873
1874
  pub const stepper_attr_message = "unknown attribute for stepper - it takes active, key, global-key, and label";
1874
1875
  pub const stepper_children_message = "stepper takes only step children (each step is a text leaf: <step>Work</step>)";
@@ -2220,7 +2221,11 @@ fn validateMarkdown(node: MarkupNode) ?MarkupErrorInfo {
2220
2221
  }
2221
2222
 
2222
2223
  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
+ // 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";
2224
2229
  var known = std.mem.tokenizeScalar(u8, names, ' ');
2225
2230
  while (known.next()) |candidate| {
2226
2231
  if (std.ascii.eqlIgnoreCase(name, candidate)) return true;
@@ -2247,13 +2252,22 @@ fn validateCode(node: MarkupNode) ?MarkupErrorInfo {
2247
2252
  }
2248
2253
  continue;
2249
2254
  }
2250
- if (std.mem.eql(u8, attribute.name, "line-numbers") or std.mem.eql(u8, attribute.name, "wrap")) {
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
+ {
2251
2259
  if (attribute.value.len == 0) continue;
2252
2260
  if (attrExpressionError(attribute.value, invalid_expression_message)) |message| {
2253
2261
  return attrError(node, attribute, message);
2254
2262
  }
2255
2263
  continue;
2256
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
+ }
2257
2271
  const known = std.mem.eql(u8, attribute.name, "width") or
2258
2272
  std.mem.eql(u8, attribute.name, "height") or
2259
2273
  std.mem.eql(u8, attribute.name, "min-width") or
@@ -788,6 +788,8 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
788
788
  if (std.mem.eql(u8, attribute.name, "kind")) continue;
789
789
  const known = std.mem.eql(u8, attribute.name, "source") or
790
790
  std.mem.eql(u8, attribute.name, "language") or
791
+ std.mem.eql(u8, attribute.name, "editable") or
792
+ std.mem.eql(u8, attribute.name, "on-input") or
791
793
  std.mem.eql(u8, attribute.name, "line-numbers") or
792
794
  std.mem.eql(u8, attribute.name, "wrap") or
793
795
  std.mem.eql(u8, attribute.name, "width") or
@@ -825,6 +827,15 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
825
827
  if (comptime (node.attr("line-numbers") != null)) {
826
828
  options.line_numbers = videoFlagValue(node, entries, comptime node.attr("line-numbers").?, ui, model, scope);
827
829
  }
830
+ if (comptime (node.attr("editable") != null)) {
831
+ options.editable = videoFlagValue(node, entries, comptime node.attr("editable").?, ui, model, scope);
832
+ }
833
+ if (comptime (node.attr("on-input") != null)) {
834
+ const expression = comptime (markup.parseMessageExpression(node.attr("on-input").?) orelse
835
+ fail(node, "invalid message expression: on-* takes a Msg tag (\"add\") or tag with one binding payload (\"toggle:{item.id}\")"));
836
+ options.on_input = comptime (inputConstructor(expression.tag) orelse
837
+ fail(node, "on-input tag must carry a TextInputEvent payload"));
838
+ }
828
839
  if (comptime (node.attr("wrap") != null)) {
829
840
  options.wrap = videoFlagValue(node, entries, comptime node.attr("wrap").?, ui, model, scope);
830
841
  }
@@ -2091,6 +2102,8 @@ fn CompiledMarkupEngine(comptime ModelT: type, comptime MsgT: type, comptime res
2091
2102
  const msg = constructMessage(node, expression, entries, ui, model, scope);
2092
2103
  if (comptime std.mem.eql(u8, event, "press")) {
2093
2104
  options.on_press = msg;
2105
+ } else if (comptime std.mem.eql(u8, event, "double-press")) {
2106
+ options.on_double_press = msg;
2094
2107
  } else if (comptime std.mem.eql(u8, event, "toggle")) {
2095
2108
  options.on_toggle = msg;
2096
2109
  } else if (comptime std.mem.eql(u8, event, "change")) {
@@ -1120,6 +1120,18 @@ test "compiled code element matches the interpreter and Ui.code" {
1120
1120
  const wrapped = try wrapped_ui.finalize(CodeCompiled.build(&wrapped_ui, &model));
1121
1121
  try testing.expect(fixture.findByKind(wrapped.root, .scroll_view) == null);
1122
1122
  try testing.expect(fixture.findByText(wrapped.root, .text, "1") == null);
1123
+
1124
+ model.editable_code = true;
1125
+ var editable_compiled_ui = CodeUi.init(arena);
1126
+ const editable_compiled = try editable_compiled_ui.finalize(CodeCompiled.build(&editable_compiled_ui, &model));
1127
+ var editable_interpreted_ui = CodeUi.init(arena);
1128
+ const editable_interpreted = try editable_interpreted_ui.finalize(try view.build(&editable_interpreted_ui, &model));
1129
+ var editable_hand_ui = CodeUi.init(arena);
1130
+ const editable_hand = try editable_hand_ui.finalize(fixture.handCodeView(&editable_hand_ui, &model));
1131
+ try expectSameTree(fixture.CodeMsg, editable_hand, editable_interpreted);
1132
+ try expectSameTree(fixture.CodeMsg, editable_hand, editable_compiled);
1133
+ try testing.expectEqual(canvas.WidgetKind.textarea, editable_compiled.root.kind);
1134
+ try testing.expect(editable_compiled.root.code_editor);
1123
1135
  }
1124
1136
 
1125
1137
  // ------------------------------------------- template/use + style parity