@native-sdk/cli 0.6.3 → 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 (40) hide show
  1. package/package.json +9 -9
  2. package/packages/core/package-lock.json +2 -2
  3. package/packages/core/package.json +1 -1
  4. package/skill-data/native-ui/SKILL.md +17 -2
  5. package/src/primitives/canvas/code.zig +590 -0
  6. package/src/primitives/canvas/code_tests.zig +1062 -0
  7. package/src/primitives/canvas/layout_audit.zig +3 -1
  8. package/src/primitives/canvas/markdown.zig +13 -11
  9. package/src/primitives/canvas/markdown_tests.zig +167 -4
  10. package/src/primitives/canvas/root.zig +4 -2
  11. package/src/primitives/canvas/tests.zig +1 -0
  12. package/src/primitives/canvas/text_measure_cache.zig +4 -4
  13. package/src/primitives/canvas/text_span_tests.zig +254 -0
  14. package/src/primitives/canvas/text_spans.zig +556 -32
  15. package/src/primitives/canvas/themes/geist.zig +29 -0
  16. package/src/primitives/canvas/tokens.zig +72 -2
  17. package/src/primitives/canvas/ui.zig +304 -5
  18. package/src/primitives/canvas/ui_markup.zig +59 -2
  19. package/src/primitives/canvas/ui_markup_compiled.zig +76 -0
  20. package/src/primitives/canvas/ui_markup_compiled_tests.zig +33 -0
  21. package/src/primitives/canvas/ui_markup_contract.zig +34 -0
  22. package/src/primitives/canvas/ui_markup_view.zig +73 -0
  23. package/src/primitives/canvas/ui_markup_view_tests.zig +85 -0
  24. package/src/primitives/canvas/ui_schema.zig +17 -6
  25. package/src/primitives/canvas/ui_schema_tests.zig +7 -6
  26. package/src/primitives/canvas/widget_invalidation.zig +3 -0
  27. package/src/primitives/canvas/widget_layout.zig +57 -8
  28. package/src/primitives/canvas/widget_layout_tests.zig +35 -0
  29. package/src/primitives/canvas/widget_metrics.zig +30 -1
  30. package/src/primitives/canvas/widget_render.zig +454 -9
  31. package/src/primitives/canvas/widget_text_select.zig +2 -2
  32. package/src/primitives/canvas/widgets.zig +13 -0
  33. package/src/root.zig +1 -0
  34. package/src/runtime/canvas_widget_clipboard_tests.zig +130 -0
  35. package/src/runtime/canvas_widget_context_menu.zig +12 -2
  36. package/src/runtime/canvas_widget_events.zig +7 -1
  37. package/src/runtime/canvas_widget_runtime.zig +7 -2
  38. package/src/runtime/canvas_widget_text_tests.zig +57 -0
  39. package/src/runtime/view.zig +7 -3
  40. package/src/runtime/view_widget_text.zig +194 -4
@@ -244,7 +244,9 @@ fn auditNodeTextOverflow(layout: WidgetLayoutTree, node_index: usize, tokens: De
244
244
  }
245
245
 
246
246
  fn auditSpanParagraphOverflow(widget: Widget, frame: geometry.RectF, node_index: usize, tokens: DesignTokens, sink: *FindingSink) void {
247
- const content = frame.inset(widget.layout.padding).normalized();
247
+ var framed_widget = widget;
248
+ framed_widget.frame = frame;
249
+ const content = widget_metrics.widgetTextSpanContentFrame(framed_widget, tokens).normalized();
248
250
  var runs: [text_spans_model.max_text_span_runs_per_paragraph]text_spans_model.TextSpanRun = undefined;
249
251
  const span_layout = text_spans_model.layoutTextSpans(
250
252
  widget.spans,
@@ -10,7 +10,8 @@
10
10
  //!
11
11
  //! Supported blocks: `#`/`##`/`###` headings (deeper levels clamp to h3),
12
12
  //! paragraphs, bullet/ordered/task lists (nesting up to
13
- //! `max_markdown_list_depth` by two-space indent), fenced code blocks,
13
+ //! `max_markdown_list_depth` by two-space indent), fenced code blocks
14
+ //! (source indentation preserved and language-tagged fences highlighted),
14
15
  //! `>` blockquotes, horizontal rules, GFM pipe tables (header row +
15
16
  //! delimiter row + body rows onto `table`/`data_row`/`data_cell` widgets;
16
17
  //! `:---`/`:--:`/`---:` delimiter cells set per-column start/center/end
@@ -57,6 +58,7 @@
57
58
  //! that exceed a capacity truncate deterministically.
58
59
 
59
60
  const std = @import("std");
61
+ const code_model = @import("code.zig");
60
62
  const geometry = @import("geometry");
61
63
  const canvas = @import("root.zig");
62
64
  const text_spans = @import("text_spans.zig");
@@ -291,7 +293,8 @@ pub fn Markdown(comptime Msg: type) type {
291
293
  }
292
294
 
293
295
  fn parseCodeFence(self: *Builder, lines: *LineIterator) ?Node {
294
- _ = lines.next(); // opening fence (info string ignored)
296
+ const opening = lines.next() orelse return null;
297
+ const language = code_model.languageFromFence(opening);
295
298
  const start = lines.index;
296
299
  var end = start;
297
300
  while (lines.next()) |line| {
@@ -299,13 +302,7 @@ pub fn Markdown(comptime Msg: type) type {
299
302
  end = lines.index;
300
303
  }
301
304
  const code = std.mem.trimEnd(u8, lines.source[start..@min(end, lines.source.len)], "\n");
302
- const code_span = [_]TextSpan{.{ .text = code, .monospace = true }};
303
- return self.ui.el(.panel, .{
304
- .padding = 12,
305
- .style_tokens = .{ .background = .surface_subtle },
306
- }, .{
307
- self.ui.paragraph(.{}, &code_span),
308
- });
305
+ return self.ui.code(.{ .language = language }, code);
309
306
  }
310
307
 
311
308
  fn parseBlockquote(self: *Builder, lines: *LineIterator) ?Node {
@@ -365,9 +362,14 @@ pub fn Markdown(comptime Msg: type) type {
365
362
  .semantics = .{ .label = marker.content },
366
363
  }),
367
364
  };
368
- if (depth == 0) return self.ui.row(.{ .gap = 8 }, .{ lead, content });
365
+ // The outer row must keep stretch alignment so a wrapped
366
+ // paragraph receives the row's full measured height. A
367
+ // one-child column consumes that stretched marker slot
368
+ // while laying its marker at the slot's leading edge.
369
+ const lead_top = self.ui.column(.{}, .{lead});
370
+ if (depth == 0) return self.ui.row(.{ .gap = 8 }, .{ lead_top, content });
369
371
  const indent = self.ui.el(.stack, .{ .width = @as(f32, @floatFromInt(depth)) * 16 }, .{});
370
- return self.ui.row(.{ .gap = 8 }, .{ indent, lead, content });
372
+ return self.ui.row(.{ .gap = 8 }, .{ indent, lead_top, content });
371
373
  }
372
374
 
373
375
  fn parseDetails(self: *Builder, lines: *LineIterator) ?Node {
@@ -48,6 +48,42 @@ fn countKind(widget: canvas.Widget, kind: canvas.WidgetKind) usize {
48
48
  return count;
49
49
  }
50
50
 
51
+ fn findKind(widget: canvas.Widget, kind: canvas.WidgetKind) ?canvas.Widget {
52
+ if (widget.kind == kind) return widget;
53
+ for (widget.children) |child| {
54
+ if (findKind(child, kind)) |found| return found;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ fn appendParagraphText(widget: canvas.Widget, out: *std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator) !void {
60
+ if (widget.kind == .text and widget.spans.len > 0) {
61
+ try out.appendSlice(allocator, widget.text);
62
+ return;
63
+ }
64
+ for (widget.children) |child| try appendParagraphText(child, out, allocator);
65
+ }
66
+
67
+ fn hasSpan(widget: canvas.Widget, text: []const u8, color: ?canvas.TextSpanColor) bool {
68
+ for (widget.spans) |span| {
69
+ if (std.mem.eql(u8, span.text, text) and span.color == color) return true;
70
+ }
71
+ for (widget.children) |child| {
72
+ if (hasSpan(child, text, color)) return true;
73
+ }
74
+ return false;
75
+ }
76
+
77
+ fn allSpansMonospace(widget: canvas.Widget) bool {
78
+ for (widget.spans) |span| {
79
+ if (!span.monospace) return false;
80
+ }
81
+ for (widget.children) |child| {
82
+ if (!allSpansMonospace(child)) return false;
83
+ }
84
+ return true;
85
+ }
86
+
51
87
  fn findParagraphContaining(widget: canvas.Widget, fragment: []const u8) ?canvas.Widget {
52
88
  if (widget.kind == .text and widget.spans.len > 0 and std.mem.indexOf(u8, widget.text, fragment) != null) return widget;
53
89
  for (widget.children) |child| {
@@ -72,6 +108,18 @@ fn findKindLabel(widget: canvas.Widget, kind: canvas.WidgetKind, label: []const
72
108
  return null;
73
109
  }
74
110
 
111
+ fn findRowWithDirectParagraph(widget: canvas.Widget, fragment: []const u8) ?canvas.Widget {
112
+ if (widget.kind == .row) {
113
+ for (widget.children) |child| {
114
+ if (child.kind == .text and child.spans.len > 0 and std.mem.indexOf(u8, child.text, fragment) != null) return widget;
115
+ }
116
+ }
117
+ for (widget.children) |child| {
118
+ if (findRowWithDirectParagraph(child, fragment)) |found| return found;
119
+ }
120
+ return null;
121
+ }
122
+
75
123
  test "markdown maps headings, paragraphs, and inline styles onto spans" {
76
124
  var doc = TestDoc.init();
77
125
  defer doc.deinit();
@@ -144,11 +192,104 @@ test "markdown maps lists, task lists, code fences, quotes, and rules" {
144
192
  try testing.expect(findParagraphContaining(tree.root, "one") != null);
145
193
  try testing.expect(findParagraphContaining(tree.root, "quoted wisdom") != null);
146
194
  try testing.expectEqual(@as(usize, 2), countKind(tree.root, .separator));
147
-
148
- // The fenced block is a panel wrapping a mono paragraph.
195
+ // The row keeps stretch alignment for wrapped paragraph height, while
196
+ // a leading column pins the marker itself to the first-line edge.
197
+ const bullet_row = findRowWithDirectParagraph(tree.root, "first").?;
198
+ const ordered_row = findRowWithDirectParagraph(tree.root, "one").?;
199
+ try testing.expectEqual(canvas.WidgetCrossAlignment.stretch, bullet_row.layout.cross_alignment);
200
+ try testing.expectEqual(canvas.WidgetKind.column, bullet_row.children[0].kind);
201
+ try testing.expectEqualStrings("•", bullet_row.children[0].children[0].text);
202
+ try testing.expectEqual(canvas.WidgetCrossAlignment.stretch, ordered_row.layout.cross_alignment);
203
+ try testing.expectEqual(canvas.WidgetKind.column, ordered_row.children[0].kind);
204
+ try testing.expectEqualStrings("1.", ordered_row.children[0].children[0].text);
205
+
206
+ // The fenced block is a panel wrapping highlighted mono spans.
149
207
  try testing.expectEqual(@as(usize, 1), countKind(tree.root, .panel));
150
208
  const code = findParagraphContaining(tree.root, "const x = 1;").?;
151
209
  try testing.expect(code.spans[0].monospace);
210
+ try testing.expectEqual(@as(?canvas.TextSpanColor, .syntax_keyword), code.spans[0].color);
211
+ }
212
+
213
+ test "language-tagged code fences highlight tokens and preserve indentation" {
214
+ var doc = TestDoc.init();
215
+ defer doc.deinit();
216
+ const tree = try doc.build(
217
+ \\```zig
218
+ \\pub fn main() void {
219
+ \\ const message = "hello";
220
+ \\ // keep this indentation
221
+ \\ return 42;
222
+ \\}
223
+ \\```
224
+ , .{});
225
+
226
+ const panel = findKind(tree.root, .panel).?;
227
+ var source_text: std.ArrayListUnmanaged(u8) = .empty;
228
+ defer source_text.deinit(testing.allocator);
229
+ try appendParagraphText(panel, &source_text, testing.allocator);
230
+ try testing.expectEqualStrings(
231
+ "pub fn main() void {\n const message = \"hello\";\n // keep this indentation\n return 42;\n}",
232
+ source_text.items,
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").?;
242
+ var runs: [text_spans.max_text_span_runs_per_paragraph]text_spans.TextSpanRun = undefined;
243
+ const layout = text_spans.layoutTextSpans(indented.spans, .{ .size = 14, .max_width = 10_000 }, &runs);
244
+ var indented_keyword_x: ?f32 = null;
245
+ for (layout.runs) |run| {
246
+ if (run.line_index == 1 and std.mem.eql(u8, run.text, "const")) indented_keyword_x = run.x;
247
+ }
248
+ // Four source spaces occupy real horizontal advance before `const`.
249
+ try testing.expect(indented_keyword_x != null);
250
+ try testing.expectApproxEqAbs(@as(f32, 4 * 14 * 0.6), indented_keyword_x.?, 0.01);
251
+ }
252
+
253
+ test "unrecognized code-fence languages remain plain monospace" {
254
+ var doc = TestDoc.init();
255
+ defer doc.deinit();
256
+ const tree = try doc.build(
257
+ \\```made-up-language
258
+ \\alpha 42
259
+ \\```
260
+ , .{});
261
+
262
+ const code = findParagraphContaining(tree.root, "alpha 42").?;
263
+ try testing.expectEqual(@as(usize, 1), code.spans.len);
264
+ try testing.expect(code.spans[0].monospace);
265
+ try testing.expectEqual(@as(?canvas.TextSpanColor, .syntax_plain), code.spans[0].color);
266
+ }
267
+
268
+ test "per-line syntax highlighting does not drop fenced code" {
269
+ const code_source =
270
+ "const a0 = 0;\n" ++
271
+ "const a1 = 1;\n" ++
272
+ "const a2 = 2;\n" ++
273
+ "const a3 = 3;\n" ++
274
+ "const a4 = 4;\n" ++
275
+ "const a5 = 5;\n" ++
276
+ "const a6 = 6;\n" ++
277
+ "const a7 = 7;\n" ++
278
+ "const a8 = 8;\n" ++
279
+ "const a9 = 9;\n" ++
280
+ "const a10 = 10;\n" ++
281
+ "const a11 = 11;";
282
+ const source = "```zig\n" ++ code_source ++ "\n```";
283
+
284
+ var doc = TestDoc.init();
285
+ defer doc.deinit();
286
+ const tree = try doc.build(source, .{});
287
+ const panel = findKind(tree.root, .panel).?;
288
+ var rendered: std.ArrayListUnmanaged(u8) = .empty;
289
+ defer rendered.deinit(testing.allocator);
290
+ try appendParagraphText(panel, &rendered, testing.allocator);
291
+ try testing.expectEqualStrings(code_source, rendered.items);
292
+ try testing.expect(hasSpan(panel, "const", .syntax_keyword));
152
293
  }
153
294
 
154
295
  test "details blocks are caller-controlled collapsibles" {
@@ -391,6 +532,12 @@ test "the README-shaped fixture renders through the mapper and the reference ren
391
532
  const surface = try canvas.ReferenceRenderSurface.init(width, height, pixels);
392
533
  try surface.renderPass(frame.renderPass(), canvas.Color.rgb8(255, 255, 255));
393
534
 
535
+ // Deliberate golden updates can be reviewed as pixels before pinning
536
+ // the new signature.
537
+ if (markdownGoldenDumpRequested()) {
538
+ try dumpMarkdownGoldenPng("/tmp/markdown-shots/readme.png", width, height, pixels);
539
+ }
540
+
394
541
  // Golden: byte-identical reference rendering of the README fixture.
395
542
  try testing.expectEqual(markdown_document_reference_signature, support.referenceSurfaceSignature(pixels));
396
543
  try support.expectVisiblePixel(surface.pixelRgba8(24, 32));
@@ -402,11 +549,27 @@ test "the README-shaped fixture renders through the mapper and the reference ren
402
549
  // scales, wrapped bullets and em-dash spacing at the face's real
403
550
  // advances, real sans and mono outlines (fixed-pitch runs sit in their
404
551
  // 0.6 em cells), GFM tables as borderless cells on hairline row
405
- // separators, fenced-code panels, and near-black underlined links.
552
+ // separators, fenced-code panels with preserved source indentation and
553
+ // language-token colors, and near-black underlined links.
406
554
  // Update deliberately when markdown rendering changes, reviewing the
407
555
  // rendered pixels first (see reference_tests.zig conventions).
408
- const markdown_document_reference_signature: u64 = 4124710367581899536;
556
+ const markdown_document_reference_signature: u64 = 12721641780797724784;
409
557
 
558
+ fn markdownGoldenDumpRequested() bool {
559
+ if (comptime !@import("builtin").link_libc) return false;
560
+ return std.c.getenv("MARKDOWN_GOLDEN_DUMP") != null;
561
+ }
562
+
563
+ fn dumpMarkdownGoldenPng(path: []const u8, width: usize, height: usize, pixels: []const u8) !void {
564
+ const io = testing.io;
565
+ std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path) orelse ".") catch {};
566
+ var file = try std.Io.Dir.cwd().createFile(io, path, .{});
567
+ defer file.close(io);
568
+ var write_buffer: [4096]u8 = undefined;
569
+ var writer = file.writer(io, &write_buffer);
570
+ try canvas.png.writeRgba8(&writer.interface, width, height, pixels);
571
+ try writer.interface.flush();
572
+ }
410
573
 
411
574
  test "bare URLs autolink at word boundaries with trailing punctuation trimmed" {
412
575
  var doc = TestDoc.init();
@@ -357,6 +357,7 @@ pub const ColorContrast = token_model.ColorContrast;
357
357
  pub const ThemeOptions = token_model.ThemeOptions;
358
358
  pub const ThemePack = token_model.ThemePack;
359
359
  pub const ColorTokens = token_model.ColorTokens;
360
+ pub const colorTokenValue = token_model.colorTokenValue;
360
361
  pub const FontFamily = token_model.FontFamily;
361
362
  pub const TypographyTokens = token_model.TypographyTokens;
362
363
  pub const SpacingTokens = token_model.SpacingTokens;
@@ -530,8 +531,9 @@ pub const max_chart_axis_ticks = chart.max_chart_axis_ticks;
530
531
  pub const chartPointCount = chart.chartPointCount;
531
532
  pub const chartHoverIndex = chart.chartHoverIndex;
532
533
 
533
- // GitHub-flavored-markdown mapper (markdown source -> widget tree + span
534
- // model) lives in `markdown.zig`; also exported as `native_sdk.markdown`.
534
+ // Shared source-code lexer/presentation model and GitHub-flavored-markdown
535
+ // mapper. Markdown fenced blocks lower through `Ui.code`.
536
+ pub const code = @import("code.zig");
535
537
  pub const markdown = @import("markdown.zig");
536
538
 
537
539
  // Deterministic key-lookup scratch shared by the per-frame planners and
@@ -25,6 +25,7 @@ test {
25
25
  _ = @import("text_metrics_tests.zig");
26
26
  _ = @import("text_batch_tests.zig");
27
27
  _ = @import("text_span_tests.zig");
28
+ _ = @import("code_tests.zig");
28
29
  _ = @import("markdown_tests.zig");
29
30
  _ = @import("markdown_hostile_tests.zig");
30
31
  _ = @import("layout_audit_tests.zig");
@@ -72,11 +72,11 @@ pub const max_cached_advance_run_bytes: usize = 2048;
72
72
  /// the peek/fetch split.
73
73
  pub const advance_cache_capacity: usize = 256;
74
74
 
75
- /// Oversize scratch: one slot covering runs up to the per-view text
76
- /// budget (`canvas_limits.max_canvas_text_bytes_per_view`). A run this
77
- /// long still gets ONE batched call per fetch; it just is not retained
75
+ /// Oversize scratch: one slot covering runs up to the canvas-widget source
76
+ /// budget (`canvas_limits.max_canvas_widget_text_bytes_per_view`). A run
77
+ /// this long still gets ONE batched call per fetch; it just is not retained
78
78
  /// across other fetches.
79
- pub const max_batched_advance_run_bytes: usize = 32768;
79
+ pub const max_batched_advance_run_bytes: usize = 65536;
80
80
 
81
81
  /// Process-wide invalidation stamp for everything keyed on measured
82
82
  /// text: cached advances here and retained wrap results downstream.
@@ -4,6 +4,7 @@ const canvas = @import("root.zig");
4
4
  const text_spans = @import("text_spans.zig");
5
5
  const text_metrics = @import("text_metrics.zig");
6
6
  const ui_model = @import("ui.zig");
7
+ const widget_text_select = @import("widget_text_select.zig");
7
8
 
8
9
  const testing = std.testing;
9
10
  const TextSpan = text_spans.TextSpan;
@@ -77,6 +78,28 @@ test "mono spans measure and draw with the mono font id" {
77
78
  try testing.expectApproxEqAbs(@as(f32, 9 * 14 * 0.6), result.runs[1].width, 0.01);
78
79
  }
79
80
 
81
+ test "mono spans preserve source indentation after line breaks" {
82
+ const spans = [_]TextSpan{
83
+ .{ .text = "fn main() {\n ", .monospace = true },
84
+ .{ .text = "return", .monospace = true, .color = .info },
85
+ .{ .text = ";\n}", .monospace = true },
86
+ };
87
+ var runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
88
+ const result = layout(&spans, .{ .size = 14, .max_width = 10_000 }, &runs);
89
+
90
+ var indent: ?TextSpanRun = null;
91
+ var keyword: ?TextSpanRun = null;
92
+ for (result.runs) |run| {
93
+ if (run.line_index == 1 and std.mem.eql(u8, run.text, " ")) indent = run;
94
+ if (run.line_index == 1 and std.mem.eql(u8, run.text, "return")) keyword = run;
95
+ }
96
+ try testing.expect(indent != null);
97
+ try testing.expect(keyword != null);
98
+ try testing.expectEqual(@as(f32, 0), indent.?.x);
99
+ try testing.expect(keyword.?.x > 0);
100
+ try testing.expectApproxEqAbs(indent.?.width, keyword.?.x, 0.01);
101
+ }
102
+
80
103
  const FakeMeasure = struct {
81
104
  calls: usize = 0,
82
105
  mono_calls: usize = 0,
@@ -198,6 +221,112 @@ test "an oversized word cluster-wraps instead of overflowing" {
198
221
  try testing.expectEqual(@as(usize, 20), total);
199
222
  }
200
223
 
224
+ test "a later visual-line page retains an over-capacity wrapped paragraph" {
225
+ const spans = [_]TextSpan{.{ .text = "a" ** 140 }};
226
+ const options = text_spans.TextSpanLayoutOptions{ .size = 14, .max_width = 1 };
227
+ var first_runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
228
+ const first = layout(&spans, options, &first_runs);
229
+
230
+ try testing.expectEqual(@as(usize, 140), first.line_count);
231
+ try testing.expectEqual(text_spans.max_text_span_lines_per_paragraph, first.runs.len);
232
+ try testing.expect(first.truncated);
233
+
234
+ var later_runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
235
+ const later = text_spans.layoutTextSpansFromLine(
236
+ &spans,
237
+ options,
238
+ text_spans.max_text_span_lines_per_paragraph,
239
+ &later_runs,
240
+ );
241
+ try testing.expectEqual(first.line_count, later.line_count);
242
+ try testing.expectEqual(first.size.width, later.size.width);
243
+ try testing.expectEqual(first.size.height, later.size.height);
244
+ try testing.expectEqual(@as(usize, 12), later.runs.len);
245
+ try testing.expectEqual(@as(usize, 128), later.runs[0].line_index);
246
+ try testing.expectEqual(@as(usize, 139), later.runs[later.runs.len - 1].line_index);
247
+ try testing.expect(!later.truncated);
248
+ }
249
+
250
+ const VariableClusterMeasure = struct {
251
+ fn advance(text: []const u8) f32 {
252
+ return switch (text[0]) {
253
+ 'a' => 3,
254
+ 0xc3 => 10, // é
255
+ 0xcc => 0, // combining acute: continuation of the é cluster
256
+ 0xe7 => 20, // 界
257
+ 'z' => 5,
258
+ 'q' => 7,
259
+ else => 1,
260
+ };
261
+ }
262
+
263
+ fn measure(_: ?*anyopaque, _: canvas.FontId, _: f32, text: []const u8) f32 {
264
+ var width: f32 = 0;
265
+ var cursor: usize = 0;
266
+ while (cursor < text.len) {
267
+ width += advance(text[cursor..]);
268
+ const sequence_len = std.unicode.utf8ByteSequenceLength(text[cursor]) catch 1;
269
+ cursor += @min(sequence_len, text.len - cursor);
270
+ }
271
+ return width;
272
+ }
273
+
274
+ fn measureAdvances(
275
+ _: ?*anyopaque,
276
+ _: canvas.FontId,
277
+ _: f32,
278
+ text: []const u8,
279
+ advances: []f32,
280
+ ) bool {
281
+ @memset(advances, 0);
282
+ var cursor: usize = 0;
283
+ while (cursor < text.len) {
284
+ advances[cursor] = advance(text[cursor..]);
285
+ const sequence_len = std.unicode.utf8ByteSequenceLength(text[cursor]) catch 1;
286
+ cursor += @min(sequence_len, text.len - cursor);
287
+ }
288
+ return true;
289
+ }
290
+ };
291
+
292
+ test "visible run slicing follows measured cluster advances" {
293
+ const source = "a\xc3\xa9\xcc\x81\xe7\x95\x8czq";
294
+ const spans = [_]TextSpan{.{ .text = source }};
295
+ const batched_provider = text_metrics.TextMeasureProvider{
296
+ .measure_fn = VariableClusterMeasure.measure,
297
+ .measure_advances_fn = VariableClusterMeasure.measureAdvances,
298
+ };
299
+ const unbatched_provider = text_metrics.TextMeasureProvider{
300
+ .measure_fn = VariableClusterMeasure.measure,
301
+ };
302
+ var options = text_spans.TextSpanLayoutOptions{
303
+ .size = 14,
304
+ .max_width = 10_000,
305
+ .measure = &batched_provider,
306
+ };
307
+ var runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
308
+ const result = layout(&spans, options, &runs);
309
+ try testing.expectEqual(@as(usize, 1), result.runs.len);
310
+
311
+ // The viewport begins inside 界. Keep the preceding é+combining-mark
312
+ // cluster and the following z guard, but neither the leading a nor q.
313
+ for ([_]*const text_metrics.TextMeasureProvider{
314
+ &batched_provider,
315
+ &unbatched_provider,
316
+ }) |provider| {
317
+ options.measure = provider;
318
+ const visible = text_spans.textSpanRunVisibleSlice(
319
+ spans[0],
320
+ result.runs[0],
321
+ options,
322
+ 14,
323
+ 20,
324
+ ).?;
325
+ try testing.expectEqualStrings("\xc3\xa9\xcc\x81\xe7\x95\x8cz", visible.text);
326
+ try testing.expectEqual(@as(f32, 3), visible.x);
327
+ }
328
+ }
329
+
201
330
  test "center alignment shifts whole lines" {
202
331
  const spans = [_]TextSpan{.{ .text = "hi" }};
203
332
  var runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
@@ -507,6 +636,131 @@ test "span selection maps points to paragraph offsets and back to rects" {
507
636
  try testing.expectEqual(@as(usize, 0), text_spans.textSpanSelectionRects(paragraph, &spans, options, .{ .start = 3, .end = 3 }, &rects).len);
508
637
  }
509
638
 
639
+ test "preformatted span hit mapping preserves unpainted source whitespace" {
640
+ const trailing = "value \t\n";
641
+ const trailing_spans = [_]TextSpan{.{
642
+ .text = trailing,
643
+ .monospace = true,
644
+ .color = .syntax_plain,
645
+ }};
646
+ const options = text_spans.TextSpanLayoutOptions{ .size = 14, .max_width = 200 };
647
+ try testing.expectEqual(
648
+ trailing.len,
649
+ text_spans.textSpanOffsetForPoint(
650
+ trailing,
651
+ &trailing_spans,
652
+ options,
653
+ geometry.PointF.init(500, 2),
654
+ ).?,
655
+ );
656
+
657
+ const whitespace = " \n\t";
658
+ const whitespace_spans = [_]TextSpan{.{
659
+ .text = whitespace,
660
+ .monospace = true,
661
+ .color = .syntax_plain,
662
+ }};
663
+ try testing.expectEqual(
664
+ @as(usize, 0),
665
+ text_spans.textSpanOffsetForPoint(
666
+ whitespace,
667
+ &whitespace_spans,
668
+ options,
669
+ geometry.PointF.init(-1, 2),
670
+ ).?,
671
+ );
672
+ try testing.expectEqual(
673
+ whitespace.len,
674
+ text_spans.textSpanOffsetForPoint(
675
+ whitespace,
676
+ &whitespace_spans,
677
+ options,
678
+ geometry.PointF.init(500, 500),
679
+ ).?,
680
+ );
681
+ }
682
+
683
+ test "span hit mapping and selection page beyond the first 128 visual lines" {
684
+ const paragraph = "a" ** 140;
685
+ const spans = [_]TextSpan{.{ .text = paragraph, .monospace = true }};
686
+ const options = text_spans.TextSpanLayoutOptions{ .size = 14, .max_width = 1 };
687
+ var runs: [text_spans.max_text_span_runs_per_paragraph]TextSpanRun = undefined;
688
+ const layout_result = layout(&spans, options, &runs);
689
+ try testing.expectEqual(@as(usize, 140), layout_result.line_count);
690
+
691
+ const later_line: usize = 132;
692
+ const y = (@as(f32, @floatFromInt(later_line)) + 0.5) * layout_result.line_height;
693
+ try testing.expectEqual(
694
+ later_line,
695
+ text_spans.textSpanOffsetForPoint(
696
+ paragraph,
697
+ &spans,
698
+ options,
699
+ geometry.PointF.init(-1, y),
700
+ ).?,
701
+ );
702
+
703
+ var rects: [16]canvas.TextSelectionRect = undefined;
704
+ const selection = text_spans.textSpanSelectionRects(
705
+ paragraph,
706
+ &spans,
707
+ options,
708
+ .{ .start = later_line, .end = paragraph.len },
709
+ &rects,
710
+ );
711
+ try testing.expectEqual(paragraph.len - later_line, selection.len);
712
+ try testing.expectEqual(later_line, selection[0].range.start);
713
+ try testing.expectEqual(
714
+ @as(f32, @floatFromInt(later_line)) * layout_result.line_height,
715
+ selection[0].rect.y,
716
+ );
717
+ try testing.expectEqual(paragraph.len, selection[selection.len - 1].range.end);
718
+
719
+ // The renderer's fixed rect budget folds every remaining line,
720
+ // including the second layout page, into its final highlight.
721
+ var bounded_rects: [widget_text_select.max_static_text_selection_rects]canvas.TextSelectionRect = undefined;
722
+ const bounded = text_spans.textSpanSelectionRects(
723
+ paragraph,
724
+ &spans,
725
+ options,
726
+ .{ .start = 0, .end = paragraph.len },
727
+ &bounded_rects,
728
+ );
729
+ try testing.expectEqual(bounded_rects.len, bounded.len);
730
+ try testing.expectEqual(@as(usize, 63), bounded[bounded.len - 1].range.start);
731
+ try testing.expectEqual(paragraph.len, bounded[bounded.len - 1].range.end);
732
+ try testing.expectApproxEqAbs(@as(f32, 0), bounded[bounded.len - 1].rect.x, 0.001);
733
+ try testing.expectApproxEqAbs(63 * layout_result.line_height, bounded[bounded.len - 1].rect.y, 0.001);
734
+ try testing.expectApproxEqAbs(
735
+ (paragraph.len - 63) * layout_result.line_height,
736
+ bounded[bounded.len - 1].rect.height,
737
+ 0.001,
738
+ );
739
+ }
740
+
741
+ test "span selection crosses an empty interior visual-line page" {
742
+ const paragraph = "a\n" ++
743
+ ("\n" ** (text_spans.max_text_span_lines_per_paragraph * 2)) ++
744
+ "b";
745
+ const spans = [_]TextSpan{.{ .text = paragraph, .monospace = true }};
746
+ const options = text_spans.TextSpanLayoutOptions{ .size = 14, .max_width = 100 };
747
+
748
+ var rects: [4]canvas.TextSelectionRect = undefined;
749
+ const selection = text_spans.textSpanSelectionRects(
750
+ paragraph,
751
+ &spans,
752
+ options,
753
+ .{ .start = 0, .end = paragraph.len },
754
+ &rects,
755
+ );
756
+
757
+ try testing.expectEqual(@as(usize, 2), selection.len);
758
+ try testing.expectEqual(@as(usize, 0), selection[0].range.start);
759
+ try testing.expectEqual(@as(usize, 1), selection[0].range.end);
760
+ try testing.expectEqual(paragraph.len - 1, selection[1].range.start);
761
+ try testing.expectEqual(paragraph.len, selection[1].range.end);
762
+ }
763
+
510
764
  test "span selection degrades to unsupported when spans alias other storage" {
511
765
  const paragraph = "Hello world";
512
766
  // Spans that do NOT slice into `paragraph` (a stack copy: the bytes