@native-sdk/cli 0.6.2 → 0.6.3

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 (36) 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/src/platform/macos/appkit_host.h +2 -0
  7. package/src/platform/macos/appkit_host.m +36 -10
  8. package/src/platform/macos/root.zig +7 -1
  9. package/src/platform/types.zig +2 -0
  10. package/src/primitives/canvas/equality.zig +3 -1
  11. package/src/primitives/canvas/events.zig +4 -0
  12. package/src/primitives/canvas/root.zig +11 -0
  13. package/src/primitives/canvas/text.zig +10 -0
  14. package/src/primitives/canvas/text_interaction.zig +164 -22
  15. package/src/primitives/canvas/text_layout.zig +107 -21
  16. package/src/primitives/canvas/text_tests.zig +86 -0
  17. package/src/primitives/canvas/ui.zig +21 -16
  18. package/src/primitives/canvas/ui_markup_reflect.zig +20 -3
  19. package/src/primitives/canvas/ui_markup_view_tests.zig +16 -0
  20. package/src/primitives/canvas/ui_tests.zig +6 -0
  21. package/src/primitives/canvas/widget_runtime.zig +1 -0
  22. package/src/primitives/canvas/widget_text_input.zig +23 -11
  23. package/src/runtime/api.zig +9 -0
  24. package/src/runtime/canvas_frame_helpers.zig +1 -0
  25. package/src/runtime/canvas_limits.zig +7 -0
  26. package/src/runtime/canvas_widget_accessibility_tests.zig +27 -1
  27. package/src/runtime/canvas_widget_clipboard_tests.zig +16 -0
  28. package/src/runtime/canvas_widget_display.zig +15 -1
  29. package/src/runtime/canvas_widget_events.zig +43 -19
  30. package/src/runtime/canvas_widget_runtime.zig +67 -10
  31. package/src/runtime/canvas_widget_state.zig +1 -0
  32. package/src/runtime/canvas_widget_text_tests.zig +1878 -70
  33. package/src/runtime/gpu_surface_events.zig +38 -0
  34. package/src/runtime/view.zig +30 -0
  35. package/src/runtime/view_widget_text.zig +1048 -10
  36. package/src/runtime/view_widget_tree.zig +2 -0
@@ -116,6 +116,10 @@ pub const text_caret_direction_members = [_][]const u8{
116
116
  "previous", "next", "previous_word", "next_word", "start", "end",
117
117
  };
118
118
 
119
+ pub const text_caret_affinity_members = [_][]const u8{
120
+ "upstream", "downstream",
121
+ };
122
+
119
123
  /// A Msg arm payload union DECLARING the text-input event shape rather than
120
124
  /// being `canvas.TextInputEvent` by identity — the transpiled-core case,
121
125
  /// where the emitted module declares its own mirror union (type identity
@@ -125,7 +129,8 @@ pub const text_caret_direction_members = [_][]const u8{
125
129
  /// - `insert_text` a bytes payload; the seven verb arms void;
126
130
  /// - `move_caret` a record of `direction` (an enum with exactly the six
127
131
  /// caret-direction member names) and `extend: bool`;
128
- /// - `set_selection` a record of numeric `anchor`/`focus`;
132
+ /// - `set_selection` a record of numeric `anchor`/`focus`, optionally
133
+ /// plus the native `upstream`/`downstream` caret-affinity enum;
129
134
  /// - `set_composition` a record of bytes `text` and optional numeric
130
135
  /// `cursor`.
131
136
  /// Numeric fields accept integer or float (the transpiler's number model
@@ -323,11 +328,23 @@ fn isSelectionRecord(comptime T: type) bool {
323
328
  .@"struct" => |s| s,
324
329
  else => return false,
325
330
  };
326
- if (info.fields.len != 2) return false;
331
+ if (info.fields.len != 2 and info.fields.len != 3) return false;
327
332
  if (!@hasField(T, "anchor") or !@hasField(T, "focus")) return false;
328
333
  inline for (info.fields) |field| {
329
- if (!isNumeric(field.type)) return false;
334
+ if (comptime std.mem.eql(u8, field.name, "affinity")) {
335
+ const members = switch (@typeInfo(field.type)) {
336
+ .@"enum" => |e| e.fields,
337
+ else => return false,
338
+ };
339
+ if (members.len != text_caret_affinity_members.len) return false;
340
+ inline for (text_caret_affinity_members) |name| {
341
+ if (!@hasField(field.type, name)) return false;
342
+ }
343
+ } else if (!isNumeric(field.type)) {
344
+ return false;
345
+ }
330
346
  }
347
+ if (info.fields.len == 3 and !@hasField(T, "affinity")) return false;
331
348
  return true;
332
349
  }
333
350
 
@@ -4428,6 +4428,8 @@ test "reactions misuse fails the build with the pinned teaching messages" {
4428
4428
  pub const MirrorCaretDirection = enum(u8) { previous = 0, next = 1, previous_word = 2, next_word = 3, start = 4, end = 5 };
4429
4429
  pub const MirrorCaretMove = struct { direction: MirrorCaretDirection, extend: bool };
4430
4430
  pub const MirrorSelection = struct { anchor: i64, focus: i64 };
4431
+ pub const MirrorCaretAffinity = enum(u8) { upstream = 0, downstream = 1 };
4432
+ pub const MirrorSelectionWithAffinity = struct { anchor: i64, focus: i64, affinity: MirrorCaretAffinity };
4431
4433
  pub const MirrorTextInputEvent = union(enum) {
4432
4434
  insert_text: []const u8,
4433
4435
  delete_backward,
@@ -4455,6 +4457,20 @@ test "declaredTextInputUnion accepts the emitted mirror shape and rejects near-m
4455
4457
  try testing.expect(markup_view.declaredTextInputUnion(MirrorTextInputEvent));
4456
4458
  // The canvas union itself matches structurally too (usize numerics).
4457
4459
  try testing.expect(markup_view.declaredTextInputUnion(canvas.TextInputEvent));
4460
+ const MirrorTextInputEventWithAffinity = union(enum) {
4461
+ insert_text: []const u8,
4462
+ delete_backward,
4463
+ delete_forward,
4464
+ delete_word_backward,
4465
+ delete_word_forward,
4466
+ clear,
4467
+ move_caret: MirrorCaretMove,
4468
+ set_selection: MirrorSelectionWithAffinity,
4469
+ set_composition: struct { text: []const u8, cursor: ?i64 },
4470
+ commit_composition,
4471
+ cancel_composition,
4472
+ };
4473
+ try testing.expect(markup_view.declaredTextInputUnion(MirrorTextInputEventWithAffinity));
4458
4474
  // Near-misses stay out: a missing arm, a non-bytes insert payload, a
4459
4475
  // wrong caret vocabulary.
4460
4476
  const MissingArm = union(enum) {
@@ -382,6 +382,12 @@ test "single-line keyboard fallback derivation sanitizes line breaks like the ru
382
382
  // A STAMPED edit (the runtime already sanitized it) passes through.
383
383
  const stamped = canvas.WidgetKeyboardEvent{ .phase = .key_down, .edit = .{ .insert_text = "clean" } };
384
384
  try testing.expectEqualStrings("clean", tree.msgForKeyboard(field.id, stamped).?.draft.insert_text);
385
+
386
+ // History replay stamps retained bytes, not new input. A raw newline
387
+ // already present in a controlled single-line value must survive the
388
+ // app-side mirror unchanged.
389
+ const stamped_history = canvas.WidgetKeyboardEvent{ .phase = .key_down, .edit = .{ .insert_text = "\n" } };
390
+ try testing.expectEqualStrings("\n", tree.msgForKeyboard(field.id, stamped_history).?.draft.insert_text);
385
391
  }
386
392
 
387
393
  test "typed handlers imply accessibility actions" {
@@ -43,6 +43,7 @@ pub const max_widget_text_range_rects: usize = 4;
43
43
  pub const widgetControlHeight = widget_metrics.widgetControlHeight;
44
44
  pub const WidgetTextGeometry = widget_text_input.WidgetTextGeometry;
45
45
  pub const textSelectionForWidgetPoint = widget_text_input.textSelectionForWidgetPoint;
46
+ pub const textCaretPositionForWidgetPoint = widget_text_input.textCaretPositionForWidgetPoint;
46
47
  pub const textOffsetForWidgetPoint = widget_text_input.textOffsetForWidgetPoint;
47
48
  pub const textInputViewportForWidget = widget_text_input.textInputViewportForWidget;
48
49
  pub const textInputClearButtonRect = widget_text_input.textInputClearButtonRect;
@@ -17,7 +17,7 @@ const TextRange = text_model.TextRange;
17
17
  const TextSelection = text_model.TextSelection;
18
18
  const DesignTokens = token_model.DesignTokens;
19
19
  const Widget = widget_model.Widget;
20
- const snapTextSelection = text_model.snapTextSelection;
20
+ const snapTextCaretSelection = text_model.snapTextCaretSelection;
21
21
  const snapTextOffset = text_model.snapTextOffset;
22
22
  const snapTextRange = text_model.snapTextRange;
23
23
  const measureTextWidthForFont = text_model.measureTextWidthForFont;
@@ -25,8 +25,8 @@ const nextTextLineEnd = text_model.nextTextLineEnd;
25
25
  const isTextBreakByte = text_model.isTextBreakByte;
26
26
  const textLineRange = text_model.textLineRange;
27
27
  const textLineCaretX = text_model.textLineCaretX;
28
- const layoutTextCaretRect = text_model.layoutTextCaretRect;
29
- const layoutTextOffsetForPoint = text_model.layoutTextOffsetForPoint;
28
+ const layoutTextCaretRectWithAffinity = text_model.layoutTextCaretRectWithAffinity;
29
+ const layoutTextCaretPositionForPoint = text_model.layoutTextCaretPositionForPoint;
30
30
  const TextLineIterator = text_model.TextLineIterator;
31
31
 
32
32
  pub fn widgetPlaceholder(widget: Widget) []const u8 {
@@ -128,15 +128,20 @@ pub fn persistWidgetTextInputPresentedText(builder: *Builder, raw: []const u8, p
128
128
  }
129
129
 
130
130
  pub fn textSelectionForWidgetPoint(widget: Widget, point: geometry.PointF, anchor: ?usize, tokens: DesignTokens) ?TextSelection {
131
- const offset = textOffsetForWidgetPoint(widget, point, tokens) orelse return null;
131
+ const position = textCaretPositionForWidgetPoint(widget, point, tokens) orelse return null;
132
132
  const selection = if (anchor) |anchor_offset|
133
- TextSelection{ .anchor = anchor_offset, .focus = offset }
133
+ TextSelection{ .anchor = anchor_offset, .focus = position.offset, .affinity = position.affinity }
134
134
  else
135
- TextSelection.collapsed(offset);
136
- return snapTextSelection(widget.text, selection);
135
+ TextSelection.collapsedAt(position);
136
+ return snapTextCaretSelection(widget.text, selection);
137
137
  }
138
138
 
139
139
  pub fn textOffsetForWidgetPoint(widget: Widget, point: geometry.PointF, tokens: DesignTokens) ?usize {
140
+ const position = textCaretPositionForWidgetPoint(widget, point, tokens) orelse return null;
141
+ return position.offset;
142
+ }
143
+
144
+ pub fn textCaretPositionForWidgetPoint(widget: Widget, point: geometry.PointF, tokens: DesignTokens) ?text_model.TextCaretPosition {
140
145
  if (!widget_access.widgetTextInputKind(widget.kind)) return null;
141
146
  if (widget.state.disabled) return null;
142
147
  const text_size = widgetTextInputSize(widget, tokens);
@@ -144,7 +149,8 @@ pub fn textOffsetForWidgetPoint(widget: Widget, point: geometry.PointF, tokens:
144
149
  const layout_options = widgetTextInputLayoutOptions(widget, tokens, text_size, text_inset);
145
150
  const origin = widgetTextInputOrigin(widget, tokens, text_size, text_inset, layout_options);
146
151
  const draw_text = widgetTextInputDrawText(widget, tokens, text_size, origin, tokens.colors.text, layout_options);
147
- return layoutTextOffsetForPoint(draw_text, layout_options, point);
152
+ const position = layoutTextCaretPositionForPoint(draw_text, layout_options, point) orelse return null;
153
+ return text_model.snapTextCaretPosition(widget.text, position);
148
154
  }
149
155
 
150
156
  pub fn widgetTextInputSize(widget: Widget, tokens: DesignTokens) f32 {
@@ -371,8 +377,13 @@ fn widgetTextInputLineCount(widget: Widget, font_id: FontId, text_size: f32, opt
371
377
  count += 1;
372
378
  if (end >= text.len) break;
373
379
  start = end;
374
- if (start < text.len and text[start] == '\n') start += 1;
375
- while (options.wrap == .word and start < text.len and isTextBreakByte(text[start])) start += 1;
380
+ if (start < text.len and text[start] == '\n') {
381
+ // Leading whitespace after a hard break belongs to the next
382
+ // editable line; only a soft wrap elides separators.
383
+ start += 1;
384
+ } else {
385
+ while (options.wrap == .word and start < text.len and isTextBreakByte(text[start])) start += 1;
386
+ }
376
387
  }
377
388
  return @max(1, count);
378
389
  }
@@ -478,7 +489,8 @@ pub fn textGeometryForWidget(widget: Widget, tokens: DesignTokens) WidgetTextGeo
478
489
 
479
490
  if (widget_access.widgetTextSelectionRange(widget)) |range| {
480
491
  if (range.isCollapsed(widget.text.len)) {
481
- value.caret_bounds = layoutTextCaretRect(draw_text, layout_options, range.start);
492
+ const affinity = if (widget.text_selection) |selection| selection.affinity else .upstream;
493
+ value.caret_bounds = layoutTextCaretRectWithAffinity(draw_text, layout_options, range.start, affinity);
482
494
  } else {
483
495
  const bounds = textRangeBounds(draw_text, layout_options, range);
484
496
  value.selection_bounds = bounds.bounds;
@@ -95,6 +95,15 @@ pub const CanvasWidgetKeyboardEvent = struct {
95
95
  /// tail so an edit that unmounts the hovered listener never
96
96
  /// strands its leave.
97
97
  standalone: bool = false,
98
+ /// Continuation edits replay an existing history entry and must not
99
+ /// themselves create a new entry.
100
+ history_replay: bool = false,
101
+ /// Stable retained-history identity for a compound undo/redo. Follow-up
102
+ /// edits are re-derived from this entry after every controlled-tree
103
+ /// rebuild instead of retaining borrowed slices into the compactable
104
+ /// history byte pool.
105
+ history_replay_serial: u64 = 0,
106
+ history_replay_redo: bool = false,
98
107
  };
99
108
 
100
109
  /// A scroll container's offset changed from a user gesture (wheel,
@@ -327,6 +327,7 @@ pub fn canvasWidgetPointerEventFromGpuInput(input_event: GpuSurfaceInputEvent) ?
327
327
  .delta = geometry.OffsetF.init(input_event.delta_x, input_event.delta_y),
328
328
  .pointer_id = input_event.pointer_id,
329
329
  .button = input_event.button,
330
+ .modifiers = canvasWidgetKeyboardModifiers(input_event.modifiers),
330
331
  };
331
332
  }
332
333
 
@@ -176,6 +176,13 @@ pub const max_canvas_widget_semantics_per_view: usize = 1024;
176
176
  // a 1024-node view retains proportionally more text.
177
177
  pub const max_canvas_widget_text_bytes_per_view: usize = 65536;
178
178
  pub const max_canvas_widget_source_text_entries_per_view: usize = 256;
179
+ /// Retained editor undo/redo is delta-based: changed bytes share this
180
+ /// per-view pool and metadata stays bounded independently. Matching the
181
+ /// live text budget guarantees that clearing a maximal editor can still
182
+ /// be undone; an unusually large whole-document replacement whose removed
183
+ /// plus inserted bytes exceed the pool simply starts a fresh history.
184
+ pub const max_canvas_widget_text_history_bytes_per_view: usize = max_canvas_widget_text_bytes_per_view;
185
+ pub const max_canvas_widget_text_history_entries_per_view: usize = 128;
179
186
  // Inline styled runs retained across all `.text` widgets of a view. Each
180
187
  // span is a small struct (style flags + slices into the widget text
181
188
  // bytes); per-paragraph capacity is `canvas.max_text_spans_per_paragraph`.
@@ -846,6 +846,7 @@ test "runtime publishes canvas widget accessibility snapshots to platform" {
846
846
  .{ .id = 4, .kind = .text_field, .frame = geometry.RectF.init(12, 96, 160, 28), .text = "Search", .placeholder = "Search deployments", .text_selection = canvas.TextSelection{ .anchor = 1, .focus = 4 }, .text_composition = canvas.TextRange.init(2, 5), .state = .{ .required = true, .read_only = true, .invalid = true } },
847
847
  .{ .id = 5, .kind = .select, .frame = geometry.RectF.init(184, 96, 120, 28), .text = "Production", .state = .{ .expanded = false }, .semantics = .{ .label = "Environment" } },
848
848
  .{ .id = 10, .kind = .data_grid, .frame = geometry.RectF.init(12, 132, 220, 64), .text = "Deployments", .layout = .{ .gap = 2 }, .children = &rows },
849
+ .{ .id = 6, .kind = .input, .frame = geometry.RectF.init(184, 58, 120, 28), .text = "Draft" },
849
850
  };
850
851
  var layout_nodes: [16]canvas.WidgetLayoutNode = undefined;
851
852
  const layout = try canvas.layoutWidgetTree(.{
@@ -860,7 +861,7 @@ test "runtime publishes canvas widget accessibility snapshots to platform" {
860
861
  try std.testing.expect(platform_state.update_count >= 1);
861
862
  try std.testing.expectEqual(@as(platform.WindowId, 1), platform_state.window_id);
862
863
  try std.testing.expectEqualStrings("canvas", platform_state.view_label[0..platform_state.view_label_len]);
863
- try std.testing.expectEqual(@as(usize, 12), platform_state.node_count);
864
+ try std.testing.expectEqual(@as(usize, 13), platform_state.node_count);
864
865
  try std.testing.expectEqual(platform.WidgetAccessibilityRole.group, platform_state.nodes[0].role);
865
866
  try std.testing.expectEqual(platform.WidgetAccessibilityRole.button, platform_state.nodes[1].role);
866
867
  try std.testing.expectEqual(platform.WidgetAccessibilityRole.checkbox, platform_state.nodes[2].role);
@@ -870,12 +871,15 @@ test "runtime publishes canvas widget accessibility snapshots to platform" {
870
871
  const cell_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 16).?;
871
872
  const text_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 4).?;
872
873
  const select_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 5).?;
874
+ const initial_editor_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 6).?;
873
875
  try std.testing.expectEqual(@as(?bool, false), select_node.expanded);
874
876
  try std.testing.expect(text_node.required);
875
877
  try std.testing.expect(text_node.read_only);
876
878
  try std.testing.expect(text_node.invalid);
877
879
  try std.testing.expect(!text_node.actions.set_text);
878
880
  try std.testing.expect(text_node.actions.set_selection);
881
+ try std.testing.expect(!initial_editor_node.can_undo);
882
+ try std.testing.expect(!initial_editor_node.can_redo);
879
883
  try std.testing.expectEqual(platform.WidgetAccessibilityRole.grid, grid_node.role);
880
884
  try std.testing.expectEqual(@as(?usize, 2), grid_node.grid_row_count);
881
885
  try std.testing.expectEqual(@as(?usize, 2), grid_node.grid_column_count);
@@ -900,6 +904,28 @@ test "runtime publishes canvas widget accessibility snapshots to platform" {
900
904
  try std.testing.expectEqual(@as(f32, 12), platform_state.nodes[1].bounds.x);
901
905
  try std.testing.expectEqual(@as(f32, 14), platform_state.nodes[1].bounds.y);
902
906
 
907
+ runtime.views[0].focused = true;
908
+ runtime.views[0].keyboard_active = true;
909
+ runtime.views[0].canvas_widget_focused_id = 6;
910
+ _ = try runtime.views[0].applyCanvasWidgetTextEdit(6, .{ .insert_text = "!" });
911
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(0);
912
+ const edited_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 6).?;
913
+ try std.testing.expect(edited_node.can_undo);
914
+ try std.testing.expect(!edited_node.can_redo);
915
+
916
+ const editor_target = runtime.views[0].widgetLayoutTree().focusTargetById(6).?;
917
+ const undo = runtime.views[0].canvasWidgetTextHistoryShortcut(editor_target, .{
918
+ .phase = .key_down,
919
+ .key = "z",
920
+ .modifiers = .{ .super = true },
921
+ }).?;
922
+ _ = try runtime.views[0].applyCanvasWidgetTextEditWithoutHistory(6, undo.edit);
923
+ runtime.views[0].commitCanvasWidgetTextHistoryReplayIfComplete(editor_target, undo.serial, undo.redo);
924
+ _ = try runtime.refreshCanvasWidgetDisplayListIfOwned(0);
925
+ const undone_node = platformWidgetAccessibilityNodeById(platform_state.nodes[0..platform_state.node_count], 6).?;
926
+ try std.testing.expect(!undone_node.can_undo);
927
+ try std.testing.expect(undone_node.can_redo);
928
+
903
929
  const published_after_layout = platform_state.update_count;
904
930
  try runtime.dispatchPlatformEvent(app_state.app(), .{ .gpu_surface_input = .{
905
931
  .window_id = 1,
@@ -483,6 +483,22 @@ test "static text drag selection highlights, copies, and clears" {
483
483
  // With nothing selected, copy leaves the clipboard untouched.
484
484
  try harness.runtime.dispatchPlatformEvent(app, keyInput("c", cmd));
485
485
  try std.testing.expectEqualStrings(body, try harness.runtime.readClipboard(&clipboard_buffer));
486
+
487
+ // Shift is an editable-text extension gesture. It must not prevent a
488
+ // fresh static-text drag from establishing its own press anchor.
489
+ try harness.runtime.dispatchPlatformEvent(app, .{ .gpu_surface_input = .{
490
+ .window_id = 1,
491
+ .label = "canvas",
492
+ .kind = .pointer_down,
493
+ .x = 13,
494
+ .y = 18,
495
+ .modifiers = .{ .shift = true },
496
+ } });
497
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_drag, 211, 75));
498
+ retained = try harness.runtime.canvasWidgetLayout(1, "canvas");
499
+ try std.testing.expectEqualDeep(canvas.TextSelection{ .anchor = 0, .focus = body.len }, retained.nodes[1].widget.text_selection.?);
500
+ try std.testing.expectEqual(@as(canvas.ObjectId, 2), harness.runtime.views[0].canvas_widget_selected_text_id);
501
+ try harness.runtime.dispatchPlatformEvent(app, pointerInput(.pointer_up, 211, 75));
486
502
  }
487
503
 
488
504
  test "span paragraph drag selection copies the concatenated bytes" {
@@ -5,6 +5,7 @@ const platform = @import("../platform/root.zig");
5
5
  const validation = @import("validation.zig");
6
6
  const runtime_api = @import("api.zig");
7
7
  const runtime_view = @import("view.zig");
8
+ const view_widget_text = @import("view_widget_text.zig");
8
9
  const canvas_limits = @import("canvas_limits.zig");
9
10
  const canvas_frame_helpers = @import("canvas_frame.zig");
10
11
  const canvas_widget_runtime = @import("canvas_widget_runtime.zig");
@@ -41,6 +42,7 @@ pub fn RuntimeCanvasWidgetDisplay(comptime Runtime: type) type {
41
42
  const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
42
43
  if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
43
44
  if (!std.meta.eql(self.views[index].widget_tokens, tokens)) {
45
+ self.views[index].clearCanvasWidgetTextVerticalGoal();
44
46
  self.views[index].widget_tokens = tokens;
45
47
  self.views[index].widget_revision += 1;
46
48
  }
@@ -213,6 +215,14 @@ pub fn RuntimeCanvasWidgetDisplay(comptime Runtime: type) type {
213
215
  const semantics = view.widgetSemantics();
214
216
  const count = @min(semantics.len, nodes.len);
215
217
  for (semantics[0..count], 0..) |node, index| {
218
+ const focused = node.state.focused or (view.keyboard_active and view.focused and node.id == view.canvas_widget_focused_id);
219
+ // Native menu validation only consults the focused editor.
220
+ // Resolving history for that one node also avoids searching
221
+ // the retained layout once per accessibility node.
222
+ const history = if (focused)
223
+ view.canvasWidgetTextHistoryAvailability(node.id)
224
+ else
225
+ view_widget_text.CanvasWidgetTextHistoryAvailability{};
216
226
  nodes[index] = .{
217
227
  .id = node.id,
218
228
  .parent_id = canvasWidgetSemanticParentId(semantics, node.parent_index),
@@ -234,7 +244,7 @@ pub fn RuntimeCanvasWidgetDisplay(comptime Runtime: type) type {
234
244
  .scroll_viewport_extent = if (node.scroll.present) node.scroll.viewport_extent else null,
235
245
  .scroll_content_extent = if (node.scroll.present) node.scroll.content_extent else null,
236
246
  .enabled = !node.state.disabled,
237
- .focused = node.state.focused or (view.keyboard_active and view.focused and node.id == view.canvas_widget_focused_id),
247
+ .focused = focused,
238
248
  .hovered = node.state.hovered or (node.id != 0 and node.id == view.canvas_widget_hovered_id),
239
249
  .pressed = node.state.pressed or (node.id != 0 and node.id == view.canvas_widget_pressed_id),
240
250
  .selected = canvasWidgetSelectedState(node),
@@ -242,6 +252,8 @@ pub fn RuntimeCanvasWidgetDisplay(comptime Runtime: type) type {
242
252
  .required = node.state.required,
243
253
  .read_only = node.state.read_only,
244
254
  .invalid = node.state.invalid,
255
+ .can_undo = history.can_undo,
256
+ .can_redo = history.can_redo,
245
257
  .focusable = node.focusable,
246
258
  .actions = platformWidgetAccessibilityActions(node.actions),
247
259
  };
@@ -594,6 +606,8 @@ fn hashWidgetAccessibilityNodes(nodes: []const platform.WidgetAccessibilityNode)
594
606
  hashAccessibilityValue(&hasher, node.required);
595
607
  hashAccessibilityValue(&hasher, node.read_only);
596
608
  hashAccessibilityValue(&hasher, node.invalid);
609
+ hashAccessibilityValue(&hasher, node.can_undo);
610
+ hashAccessibilityValue(&hasher, node.can_redo);
597
611
  hashAccessibilityValue(&hasher, node.focusable);
598
612
  inline for (comptime std.meta.fieldNames(platform.WidgetAccessibilityActions)) |field_name| {
599
613
  hashAccessibilityValue(&hasher, @field(node.actions, field_name));
@@ -2020,7 +2020,7 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
2020
2020
  /// and clear-button stamping precedent, made the rule). Before
2021
2021
  /// the stamp, edits that only THIS derivation produced — Escape's
2022
2022
  /// search-field clear, Escape's composition cancel, the
2023
- /// single-line ArrowUp/Down caret jumps — mutated the editor
2023
+ /// runtime's geometry-aware ArrowUp/Down caret jumps — mutated the editor
2024
2024
  /// while the app-side dispatch re-derived the key on its own and
2025
2025
  /// heard nothing: the field visibly cleared while `model.query`
2026
2026
  /// kept the stale term, and the next keystroke dispatched
@@ -2031,27 +2031,50 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
2031
2031
  const index = runtimeFindViewIndex(self, keyboard_event.window_id, keyboard_event.view_label) orelse return;
2032
2032
  if (self.views[index].kind != .gpu_surface) return;
2033
2033
  const target = keyboard_event.target orelse return;
2034
- const derived = self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
2035
- // Single-line sanitization happens HERE — after derivation,
2034
+ const history_shortcut = if (!keyboard_event.history_replay)
2035
+ self.views[index].canvasWidgetTextHistoryShortcut(target, keyboard_event.keyboard)
2036
+ else
2037
+ null;
2038
+ const derived = if (history_shortcut) |shortcut|
2039
+ shortcut.edit
2040
+ else
2041
+ self.views[index].canvasWidgetKeyboardTextEdit(target, keyboard_event.keyboard) orelse return;
2042
+ if (history_shortcut) |shortcut| {
2043
+ keyboard_event.history_replay = true;
2044
+ keyboard_event.history_replay_serial = shortcut.serial;
2045
+ keyboard_event.history_replay_redo = shortcut.redo;
2046
+ }
2047
+ // New single-line input is sanitized HERE — after derivation,
2036
2048
  // BEFORE the stamp — so the retained editor and the app's
2037
- // `on_input` mirror hear byte-identical sanitized inserts
2038
- // (clipboard paste from both entry points, typed and
2039
- // automation text_input, IME composition — every insertion
2040
- // source flows through this one seam). Pre-stamped pastes
2041
- // arrive already sanitized (`clampCanvasWidgetPasteText`
2042
- // strips BEFORE clamping so capacity never counts stripped
2043
- // bytes); re-sanitizing them is a no-op. A suppressed edit (an
2044
- // insert that was ONLY line breaks) also clears any raw
2045
- // pre-stamped paste so the app can never hear bytes the
2046
- // editor refused; the app-side fallback derivation applies
2047
- // the same sanitize rule, so both derivations still agree.
2048
- const edit = canvas.sanitizedSingleLineTextInputEvent(target.kind, derived) orelse {
2049
- keyboard_event.keyboard.edit = null;
2050
- return;
2051
- };
2049
+ // `on_input` mirror hear byte-identical sanitized inserts.
2050
+ // Clipboard paste, typed and automation text_input, and IME
2051
+ // composition all flow through this seam. History replay is
2052
+ // the deliberate exception below: its payload is retained
2053
+ // state rather than new input.
2054
+ // History payloads are retained bytes, not new user input:
2055
+ // replay them exactly so Undo can restore a model-provided
2056
+ // single-line value that contains raw line breaks. Every
2057
+ // non-history insertion still crosses the sanitizer below.
2058
+ const edit = if (keyboard_event.history_replay)
2059
+ derived
2060
+ else
2061
+ canvas.sanitizedSingleLineTextInputEvent(target.kind, derived) orelse {
2062
+ keyboard_event.keyboard.edit = null;
2063
+ return;
2064
+ };
2052
2065
  keyboard_event.keyboard.edit = edit;
2053
2066
 
2054
- const dirty = try self.views[index].applyCanvasWidgetTextEdit(target.id, edit) orelse return;
2067
+ const dirty = if (keyboard_event.history_replay)
2068
+ try self.views[index].applyCanvasWidgetTextEditWithoutHistory(target.id, edit) orelse return
2069
+ else
2070
+ try self.views[index].applyCanvasWidgetTextEdit(target.id, edit) orelse return;
2071
+ if (keyboard_event.history_replay) {
2072
+ self.views[index].commitCanvasWidgetTextHistoryReplayIfComplete(
2073
+ target,
2074
+ keyboard_event.history_replay_serial,
2075
+ keyboard_event.history_replay_redo,
2076
+ );
2077
+ }
2055
2078
  if (canvasDirtyRegionForView(self.views[index].frame, dirty)) |dirty_region| {
2056
2079
  self.invalidateFor(.state, dirty_region);
2057
2080
  } else {
@@ -2102,6 +2125,7 @@ pub fn RuntimeCanvasWidgetEvents(comptime Runtime: type) type {
2102
2125
  target_id,
2103
2126
  pointer_event.pointer.point,
2104
2127
  pointer_event.pointer.phase == .move,
2128
+ pointer_event.pointer.phase == .down and pointer_event.pointer.modifiers.shift,
2105
2129
  pointer_event.pointer.click_count,
2106
2130
  );
2107
2131
  // Pointer placement lives first in the retained editor, but a
@@ -151,6 +151,12 @@ pub const CanvasWidgetTextReconcileEntry = struct {
151
151
  text: []const u8 = &.{},
152
152
  source_text_len: usize = 0,
153
153
  source_text_hash: u64 = 0,
154
+ /// The selection declared by the previous SOURCE tree, distinct from
155
+ /// the runtime-owned selection in `text_selection`. Legacy controlled
156
+ /// models always materialize the default `.upstream` affinity, so an
157
+ /// unchanged source affinity is an echo; a changed affinity is an
158
+ /// explicit source-side visual-caret move.
159
+ source_text_selection: ?canvas.TextSelection = null,
154
160
  text_selection: ?canvas.TextSelection = null,
155
161
  text_composition: ?canvas.TextRange = null,
156
162
  value: f32 = 0,
@@ -246,6 +252,7 @@ pub const CanvasWidgetSourceTextEntry = struct {
246
252
  kind: canvas.WidgetKind = .text_field,
247
253
  text_len: usize = 0,
248
254
  text_hash: u64 = 0,
255
+ text_selection: ?canvas.TextSelection = null,
249
256
  };
250
257
 
251
258
  /// The SOURCE-side selected state (and value, for sliders) of one
@@ -588,13 +595,18 @@ pub fn collectCanvasWidgetTextReconcileEntries(
588
595
  if (node.widget.id == 0 or !canvasWidgetTextReconcileKind(node.widget)) continue;
589
596
  if (len >= output.len) break;
590
597
  const text_range = try appendWidgetTextStorageRange(text_storage, text_len, node.widget.text);
591
- const source_text = canvasWidgetSourceTextByIdKind(source_entries, node.widget.id, node.widget.kind) orelse canvasWidgetSourceTextFingerprint(node.widget.text);
598
+ const source_entry = canvasWidgetSourceTextEntryByIdKind(source_entries, node.widget.id, node.widget.kind);
599
+ const source_text = if (source_entry) |entry|
600
+ CanvasWidgetSourceTextFingerprint{ .len = entry.text_len, .hash = entry.text_hash }
601
+ else
602
+ canvasWidgetSourceTextFingerprint(node.widget.text);
592
603
  output[len] = .{
593
604
  .id = node.widget.id,
594
605
  .kind = node.widget.kind,
595
606
  .text = text_storage[text_range.start..text_range.end],
596
607
  .source_text_len = source_text.len,
597
608
  .source_text_hash = source_text.hash,
609
+ .source_text_selection = if (source_entry) |entry| entry.text_selection else null,
598
610
  .text_selection = node.widget.text_selection,
599
611
  .text_composition = node.widget.text_composition,
600
612
  .value = node.widget.value,
@@ -632,12 +644,21 @@ pub fn canvasWidgetSourceTextByIdKind(
632
644
  id: canvas.ObjectId,
633
645
  kind: canvas.WidgetKind,
634
646
  ) ?CanvasWidgetSourceTextFingerprint {
647
+ const entry = canvasWidgetSourceTextEntryByIdKind(entries, id, kind) orelse return null;
648
+ return .{
649
+ .len = entry.text_len,
650
+ .hash = entry.text_hash,
651
+ };
652
+ }
653
+
654
+ fn canvasWidgetSourceTextEntryByIdKind(
655
+ entries: []const CanvasWidgetSourceTextEntry,
656
+ id: canvas.ObjectId,
657
+ kind: canvas.WidgetKind,
658
+ ) ?CanvasWidgetSourceTextEntry {
635
659
  for (entries) |entry| {
636
660
  if (entry.id != id or entry.kind != kind) continue;
637
- return .{
638
- .len = entry.text_len,
639
- .hash = entry.text_hash,
640
- };
661
+ return entry;
641
662
  }
642
663
  return null;
643
664
  }
@@ -755,8 +776,10 @@ pub fn canvasWidgetLayoutNodeWithTextReconcileState(
755
776
  previous: *const CanvasWidgetTextEntryIndex,
756
777
  ) canvas.WidgetLayoutNode {
757
778
  var copy = node;
758
- if (copy.widget.id == 0) return copy;
759
- if (copy.widget.state.disabled or canvasWidgetLayoutNodeHidden(layout, node_index)) return copy;
779
+ if (copy.widget.id == 0) return canvasWidgetLayoutNodeWithCaretSafeSelection(copy);
780
+ if (copy.widget.state.disabled or canvasWidgetLayoutNodeHidden(layout, node_index)) {
781
+ return canvasWidgetLayoutNodeWithCaretSafeSelection(copy);
782
+ }
760
783
 
761
784
  if (copy.widget.kind == .text) {
762
785
  // Static text selections survive rebuilds only while the source
@@ -766,7 +789,7 @@ pub fn canvasWidgetLayoutNodeWithTextReconcileState(
766
789
  copy.widget.text_selection = entry.text_selection;
767
790
  }
768
791
  }
769
- return copy;
792
+ return canvasWidgetLayoutNodeWithCaretSafeSelection(copy);
770
793
  }
771
794
  if (!canvasWidgetEditableTextKind(copy.widget.kind)) return copy;
772
795
 
@@ -780,7 +803,9 @@ pub fn canvasWidgetLayoutNodeWithTextReconcileState(
780
803
  const next_source_text = canvasWidgetSourceTextFingerprint(copy.widget.text);
781
804
  const source_unchanged = entry.source_text_len == next_source_text.len and entry.source_text_hash == next_source_text.hash;
782
805
  const source_matches_runtime_text = std.mem.eql(u8, entry.text, copy.widget.text);
783
- if (!source_unchanged and !source_matches_runtime_text) return copy;
806
+ if (!source_unchanged and !source_matches_runtime_text) {
807
+ return canvasWidgetLayoutNodeWithCaretSafeSelection(copy);
808
+ }
784
809
  if (source_unchanged) copy.widget.text = entry.text;
785
810
  // The retained scroll offset rides `value` for every editable
786
811
  // text kind: the textarea's vertical offset and the single-line
@@ -792,8 +817,40 @@ pub fn canvasWidgetLayoutNodeWithTextReconcileState(
792
817
  if (copy.widget.text_selection == null and copy.widget.text_composition == null) {
793
818
  copy.widget.text_selection = entry.text_selection;
794
819
  copy.widget.text_composition = entry.text_composition;
820
+ } else if (copy.widget.text_selection) |*source_selection| {
821
+ // Caret affinity is runtime geometry at a byte offset. Core
822
+ // and C-ABI controlled models historically echo only
823
+ // anchor/focus, so the bridge materializes `.upstream` on
824
+ // every rebuild. When those offsets faithfully echo the
825
+ // retained selection, keep the retained visual-line owner;
826
+ // changing either offset remains the source-authoritative
827
+ // way to move the selection.
828
+ if (entry.text_selection) |retained_selection| {
829
+ if (source_selection.anchor == retained_selection.anchor and
830
+ source_selection.focus == retained_selection.focus)
831
+ {
832
+ const source_affinity_changed = if (entry.source_text_selection) |previous_source_selection|
833
+ source_selection.affinity != previous_source_selection.affinity
834
+ else
835
+ // The legacy shape can only materialize upstream;
836
+ // a first downstream value is therefore explicit.
837
+ source_selection.affinity != .upstream;
838
+ if (!source_affinity_changed) {
839
+ source_selection.affinity = retained_selection.affinity;
840
+ }
841
+ }
842
+ }
795
843
  }
796
844
  }
845
+ return canvasWidgetLayoutNodeWithCaretSafeSelection(copy);
846
+ }
847
+
848
+ fn canvasWidgetLayoutNodeWithCaretSafeSelection(node: canvas.WidgetLayoutNode) canvas.WidgetLayoutNode {
849
+ var copy = node;
850
+ if (!canvasWidgetEditableTextKind(copy.widget.kind)) return copy;
851
+ if (copy.widget.text_selection) |selection| {
852
+ copy.widget.text_selection = canvas.snapTextCaretSelection(copy.widget.text, selection);
853
+ }
797
854
  return copy;
798
855
  }
799
856
 
@@ -1174,7 +1231,7 @@ pub fn canvasWidgetTextEditUnchanged(previous: canvas.TextEditState, next: canva
1174
1231
  }
1175
1232
 
1176
1233
  pub fn canvasTextSelectionsEqual(a: canvas.TextSelection, b: canvas.TextSelection) bool {
1177
- return a.anchor == b.anchor and a.focus == b.focus;
1234
+ return a.anchor == b.anchor and a.focus == b.focus and a.affinity == b.affinity;
1178
1235
  }
1179
1236
 
1180
1237
  pub fn textSelectionCollapsedAt(selection: ?canvas.TextSelection, offset: usize) bool {
@@ -790,6 +790,7 @@ pub fn RuntimeCanvasWidgetState(comptime Runtime: type) type {
790
790
  const index = runtimeFindViewIndex(self, window_id, label) orelse return error.ViewNotFound;
791
791
  if (self.views[index].kind != .gpu_surface) return error.InvalidViewOptions;
792
792
  if (std.meta.eql(self.views[index].widget_tokens, tokens)) return self.views[index].info();
793
+ self.views[index].clearCanvasWidgetTextVerticalGoal();
793
794
  self.views[index].widget_tokens = tokens;
794
795
  self.views[index].widget_revision += 1;
795
796
  if (self.views[index].canvas_display_list_widget_owned) {