@native-sdk/cli 0.7.2 → 0.8.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 (61) hide show
  1. package/build/app.zig +265 -65
  2. package/build/ts_run.mjs +6 -8
  3. package/build.zig +292 -349
  4. package/package.json +13 -11
  5. package/packages/core/compile-surface/core.ts +559 -0
  6. package/packages/core/package-lock.json +375 -12
  7. package/packages/core/package.json +9 -6
  8. package/packages/core/scripts/compiler_typecheck.mjs +58 -0
  9. package/packages/core/scripts/gen_case_tables.mjs +130 -0
  10. package/packages/core/scripts/gen_declarations.mjs +97 -0
  11. package/packages/core/scripts/run_external_core_compiler.mjs +108 -0
  12. package/packages/core/scripts/stage_external_core.mjs +148 -0
  13. package/packages/core/sdk/core.d.ts +363 -0
  14. package/packages/core/sdk/events.d.ts +65 -0
  15. package/packages/core/sdk/text.d.ts +51 -0
  16. package/packages/core/src/checker.ts +3 -3
  17. package/packages/core/src/cli.ts +40 -38
  18. package/packages/core/src/contract.ts +749 -0
  19. package/packages/core/src/devhost.ts +4 -3
  20. package/packages/core/src/diagnostics.ts +5 -7
  21. package/packages/core/src/{transpile.ts → frontend.ts} +38 -50
  22. package/packages/core/src/infer.ts +1 -1
  23. package/packages/core/src/typed_ast.ts +16 -15
  24. package/packages/core/src/wyhash.ts +79 -0
  25. package/skill-data/native-ui/SKILL.md +3 -2
  26. package/skill-data/ts-core/SKILL.md +29 -29
  27. package/src/platform/macos/appkit_host.h +4 -4
  28. package/src/platform/macos/appkit_host.m +24 -4
  29. package/src/platform/macos/cef_host.mm +22 -6
  30. package/src/platform/macos/root.zig +2 -2
  31. package/src/primitives/canvas/markdown.zig +2010 -57
  32. package/src/primitives/canvas/markdown_hostile_tests.zig +40 -0
  33. package/src/primitives/canvas/markdown_tests.zig +778 -3
  34. package/src/primitives/canvas/ui_markup.zig +9 -1
  35. package/src/primitives/canvas/ui_markup_compiled.zig +29 -0
  36. package/src/primitives/canvas/ui_markup_contract.zig +11 -0
  37. package/src/primitives/canvas/ui_markup_view.zig +20 -0
  38. package/src/primitives/canvas/ui_markup_view_tests.zig +13 -1
  39. package/src/primitives/canvas/ui_schema.zig +3 -0
  40. package/src/primitives/canvas/ui_schema_tests.zig +4 -3
  41. package/src/primitives/canvas/widget_layout.zig +26 -3
  42. package/src/primitives/canvas/widget_metrics.zig +21 -3
  43. package/src/primitives/canvas/widget_render.zig +6 -1
  44. package/src/runtime/effects.zig +9 -0
  45. package/src/runtime/effects_fetch_tests.zig +21 -0
  46. package/src/runtime/ts_core_host.zig +38 -38
  47. package/src/runtime/ts_ui_app.zig +12 -12
  48. package/src/tooling/manifest.zig +32 -0
  49. package/src/tooling/raw_manifest.zig +4 -0
  50. package/src/tooling/templates.zig +25 -20
  51. package/src/tooling/ts_core.zig +55 -34
  52. package/src/tooling/verbs.zig +1 -1
  53. package/tools/corewire/core_abi.zig +169 -0
  54. package/tools/corewire/emit.zig +2418 -0
  55. package/tools/corewire/emit_facade.zig +3984 -0
  56. package/tools/corewire/emit_profile.zig +501 -0
  57. package/tools/corewire/main.zig +561 -0
  58. package/tools/corewire/shim_rt.zig +632 -0
  59. package/tools/corewire/sidecar.zig +2507 -0
  60. package/packages/core/rt/rt.zig +0 -1986
  61. package/packages/core/src/emitter.ts +0 -11898
@@ -16,20 +16,32 @@
16
16
  //! delimiter row + body rows onto `table`/`data_row`/`data_cell` widgets;
17
17
  //! `:---`/`:--:`/`---:` delimiter cells set per-column start/center/end
18
18
  //! text alignment, header cells render bold, and every cell runs the full
19
- //! inline span grammar including links), and `<details>`/`<summary>`.
19
+ //! inline span grammar including links), a safe presentational HTML subset,
20
+ //! and `<details>`/`<summary>`.
20
21
  //! Supported inlines: `**bold**`/`__bold__`, `*italic*`/`_italic_`,
21
22
  //! `` `code` ``, `~~strikethrough~~`, `[text](url)` links, `<url>`
22
23
  //! autolinks, bare `http(s)://` URLs at word boundaries (GFM-style
23
24
  //! autolink extension, trailing punctuation trimmed), `#123` issue
24
25
  //! references (opt-in via `Options.issue_link_base`, since resolving a
25
- //! ref needs repo context), and `![alt](url)` images (rendered as their
26
- //! alt text).
26
+ //! ref needs repo context), and `![alt](url)` images. Leading images whose
27
+ //! source appears in `Options.images` render from the caller's registered
28
+ //! `ImageId`; unresolved and mid-paragraph images retain their alt-text
29
+ //! fallback. GitHub-style HTML covers the matching native presentation:
30
+ //! emphasis/strong/strike/underline/code spans, anchors, line breaks,
31
+ //! headings, paragraphs, blockquotes, horizontal rules, registered images
32
+ //! (or image alt text),
33
+ //! harmless structural wrappers, comments, and common HTML entities.
34
+ //! Attributes other than `href`, `src`, `alt`, image `width`/`height`, and
35
+ //! block `align` are ignored; there is no DOM, CSS, script execution, or
36
+ //! implicit remote image loading. Fetch/decode remains an application effect
37
+ //! (`fx.loadImage`); Markdown only resolves the bounded model-owned mapping.
27
38
  //!
28
39
  //! Deliberately unsupported in v1 (rendered as plain paragraph text, never
29
40
  //! a build failure): setext headings, indented code blocks, backslash
30
41
  //! escapes (except `\|` inside table rows, which GFM needs to put a pipe
31
- //! in a cell), reference-style links, raw HTML other than
32
- //! details/summary, and footnotes. Malformed input degrades to literal
42
+ //! in a cell), reference-style links (their definitions are recognized and
43
+ //! hidden, but references stay literal), HTML with no native presentation
44
+ //! (scripts, styles, embeds, and forms), and footnotes. Malformed input degrades to literal
33
45
  //! text — a pipe block whose delimiter row is missing or does not match
34
46
  //! the header's column count renders as plain paragraphs, and tables
35
47
  //! wider than `max_markdown_table_columns` degrade the same way rather
@@ -73,9 +85,19 @@ pub const max_markdown_blocks_per_container: usize = 64;
73
85
  pub const max_markdown_list_items_per_list: usize = 64;
74
86
  pub const max_markdown_list_depth: usize = 4;
75
87
  pub const max_markdown_details_per_document: usize = 16;
88
+ pub const max_markdown_html_block_depth: usize = 8;
76
89
  pub const max_markdown_table_columns: usize = 8;
77
90
  /// Rows per table including the header; trailing rows drop deterministically.
78
91
  pub const max_markdown_table_rows: usize = 64;
92
+ /// Registered source-to-image mappings a document will inspect. This mirrors
93
+ /// the runtime's registered-image slot bound and keeps hostile model slices
94
+ /// from turning every inline image into an unbounded lookup.
95
+ pub const max_markdown_images: usize = 16;
96
+ /// Image sources discovered for the documented `fx.loadImage` workflow use
97
+ /// the effect channel's URL bound. Keeping the copy here model-owned lets the
98
+ /// collector decode HTML entities before either network loading or renderer
99
+ /// lookup, so both sides use one canonical source string.
100
+ pub const max_markdown_image_source_bytes: usize = 2048;
79
101
  /// Joined bytes per paragraph or blockquote (consecutive source lines
80
102
  /// collapse into one text widget). Sized generously past real GitHub
81
103
  /// prose — paragraphs beyond a couple of KiB are pathological input —
@@ -90,6 +112,152 @@ pub const max_markdown_paragraph_bytes: usize = 8192;
90
112
  /// sizes stay derived from live tokens.
91
113
  pub const heading_scales = [_]f32{ 2.0, 1.5, 1.25 };
92
114
 
115
+ /// One image the application has already decoded and registered with the
116
+ /// canvas runtime. Markdown deliberately does not perform I/O from a view:
117
+ /// apps load `source` through `fx.loadImage`, retain the successful id and
118
+ /// dimensions in their model, then pass that model-owned mapping here.
119
+ pub const ResolvedImage = struct {
120
+ source: []const u8,
121
+ image: canvas.ImageId,
122
+ width: f32,
123
+ height: f32,
124
+ };
125
+
126
+ /// One canonical image source copied into caller-owned collection storage.
127
+ /// `value()` remains valid while this record remains alive; consume or copy
128
+ /// the slice before the caller's storage goes out of scope.
129
+ pub const CollectedImageSource = struct {
130
+ bytes: [max_markdown_image_source_bytes]u8 = undefined,
131
+ len: usize = 0,
132
+
133
+ pub fn value(self: *const CollectedImageSource) []const u8 {
134
+ return self.bytes[0..self.len];
135
+ }
136
+ };
137
+
138
+ /// Collect distinct leading image sources the renderer can replace with native
139
+ /// image leaves, into caller-owned bounded storage. Fenced blocks, inline code,
140
+ /// comments, mid-paragraph images, and unsupported HTML tags stay inert,
141
+ /// matching the renderer's security posture and avoiding effects for sources
142
+ /// that can only use the alt-text fallback. Sources are HTML-entity-decoded
143
+ /// into `output`, so the URL loaded and the key later matched by the renderer
144
+ /// are byte-identical. An app can use this during `update` to issue
145
+ /// `fx.loadImage` effects, then pass successful mappings back through
146
+ /// `Options.images` on the next view.
147
+ pub fn collectImageSources(source: []const u8, output: []CollectedImageSource) []const CollectedImageSource {
148
+ var lines = LineIterator{ .source = source };
149
+ var len: usize = 0;
150
+ var in_fence = false;
151
+ var paragraph_open = false;
152
+ var blockquote_open = false;
153
+ var html_state = ImageDiscoveryHtmlState{};
154
+ while (lines.next()) |line| {
155
+ const trimmed = std.mem.trim(u8, line, " \t");
156
+
157
+ // HTML comments, code/pre blocks, and unsupported elements remain
158
+ // opaque across physical lines. Scan them before considering Markdown
159
+ // block prefixes so hidden `<img>` lines can never become effects.
160
+ if (html_state.active()) {
161
+ _ = imageDiscoveryVisiblePrefix(line, &html_state);
162
+ continue;
163
+ }
164
+ if (std.mem.startsWith(u8, trimmed, "```")) {
165
+ in_fence = !in_fence;
166
+ paragraph_open = false;
167
+ blockquote_open = false;
168
+ continue;
169
+ }
170
+ if (in_fence) continue;
171
+
172
+ const visible = imageDiscoveryVisiblePrefix(line, &html_state);
173
+ const visible_trimmed = std.mem.trim(u8, visible, " \t");
174
+ if (visible_trimmed.len == 0) {
175
+ if (trimmed.len == 0) {
176
+ paragraph_open = false;
177
+ blockquote_open = false;
178
+ } else if (startsStandaloneInertHtmlBlock(trimmed)) {
179
+ // Comments and `<pre>` lower as standalone blocks. Once
180
+ // their multiline body ends, the next source line starts a
181
+ // fresh renderable block and may expose a leading image.
182
+ paragraph_open = false;
183
+ } else {
184
+ // A comment/opaque element on an otherwise nonblank line is
185
+ // still part of the surrounding paragraph. Do not let the
186
+ // next physical line masquerade as a leading image.
187
+ paragraph_open = true;
188
+ }
189
+ continue;
190
+ }
191
+
192
+ if (isLinkReferenceDefinition(visible)) {
193
+ paragraph_open = false;
194
+ blockquote_open = false;
195
+ continue;
196
+ }
197
+
198
+ if (headingLevel(visible_trimmed)) |level| {
199
+ appendLeadingImageSource(output, &len, std.mem.trim(u8, visible_trimmed[level..], " \t#"));
200
+ paragraph_open = false;
201
+ blockquote_open = false;
202
+ if (len >= output.len) break;
203
+ continue;
204
+ }
205
+ if (listMarker(visible)) |marker| {
206
+ appendLeadingImageSource(output, &len, marker.content);
207
+ paragraph_open = false;
208
+ blockquote_open = false;
209
+ if (len >= output.len) break;
210
+ continue;
211
+ }
212
+ if (std.mem.startsWith(u8, visible_trimmed, ">")) {
213
+ var inner = visible_trimmed[1..];
214
+ if (std.mem.startsWith(u8, inner, " ")) inner = inner[1..];
215
+ inner = std.mem.trim(u8, inner, " \t");
216
+ if (!blockquote_open and inner.len > 0) appendLeadingImageSource(output, &len, inner);
217
+ if (inner.len > 0) blockquote_open = true;
218
+ paragraph_open = false;
219
+ if (len >= output.len) break;
220
+ continue;
221
+ }
222
+ blockquote_open = false;
223
+
224
+ if (visible.len == line.len and collectTableImageSources(&lines, visible, output, &len, &html_state)) {
225
+ paragraph_open = false;
226
+ if (len >= output.len) break;
227
+ continue;
228
+ }
229
+
230
+ if (collectHtmlBlockImageSource(visible_trimmed, output, &len, &paragraph_open)) {
231
+ if (len >= output.len) break;
232
+ continue;
233
+ }
234
+
235
+ if (isHorizontalRule(visible_trimmed)) {
236
+ paragraph_open = false;
237
+ continue;
238
+ }
239
+ if (!paragraph_open) appendLeadingImageSource(output, &len, visible);
240
+ paragraph_open = true;
241
+ if (len >= output.len) break;
242
+ }
243
+ return output[0..len];
244
+ }
245
+
246
+ fn appendLeadingImageSource(output: []CollectedImageSource, len: *usize, text: []const u8) void {
247
+ const image = parseLeadingInlineImage(text) orelse return;
248
+ appendDistinctImageSource(output, len, image.source);
249
+ }
250
+
251
+ fn appendDistinctImageSource(output: []CollectedImageSource, len: *usize, source: []const u8) void {
252
+ if (source.len == 0 or len.* >= output.len) return;
253
+ const decoded = decodeHtmlEntitiesInto(source, &output[len.*].bytes) orelse return;
254
+ for (output[0..len.*]) |*existing| {
255
+ if (std.mem.eql(u8, existing.value(), decoded)) return;
256
+ }
257
+ output[len.*].len = decoded.len;
258
+ len.* += 1;
259
+ }
260
+
93
261
  pub fn Markdown(comptime Msg: type) type {
94
262
  return struct {
95
263
  pub const Ui = ui_builder.Ui(Msg);
@@ -116,6 +284,12 @@ pub fn Markdown(comptime Msg: type) type {
116
284
  /// keeps refs as plain text (they need repo context to
117
285
  /// resolve, so there is no default).
118
286
  issue_link_base: ?[]const u8 = null,
287
+ /// Source-to-registered-ImageId mappings owned by the caller's
288
+ /// model. A matching leading Markdown image or HTML `<img src>`
289
+ /// renders only when the id and dimensions are valid; otherwise
290
+ /// its alt text remains visible. At most `max_markdown_images`
291
+ /// entries are inspected.
292
+ images: []const ResolvedImage = &.{},
119
293
  };
120
294
 
121
295
  /// Comptime message constructor for `on_details`:
@@ -149,6 +323,28 @@ pub fn Markdown(comptime Msg: type) type {
149
323
  ui: *Ui,
150
324
  options: Options,
151
325
  details_count: usize = 0,
326
+ /// GitHub permits `align` on a few safe block wrappers. A
327
+ /// standalone `<div align="center">` commonly wraps several
328
+ /// README blocks, so remember that presentation until its
329
+ /// closing wrapper rather than requiring a browser layout tree.
330
+ html_alignment: ?canvas.TextAlign = null,
331
+ html_block_scope_stack: [16]HtmlBlockScope = undefined,
332
+ html_block_scope_depth: usize = 0,
333
+ html_block_scope_overflow_depth: usize = 0,
334
+ html_block_depth: usize = 0,
335
+
336
+ const HtmlBlockScope = struct {
337
+ name: []const u8,
338
+ previous_alignment: ?canvas.TextAlign,
339
+ list_kind: ?HtmlListKind = null,
340
+ next_ordinal: usize = 1,
341
+ };
342
+
343
+ const HtmlPresentationSnapshot = struct {
344
+ alignment: ?canvas.TextAlign,
345
+ scope_depth: usize,
346
+ overflow_depth: usize,
347
+ };
152
348
 
153
349
  fn allocNodes(self: *Builder) []Node {
154
350
  return self.ui.arena.alloc(Node, max_markdown_blocks_per_container) catch {
@@ -168,6 +364,21 @@ pub fn Markdown(comptime Msg: type) type {
168
364
  _ = lines.next();
169
365
  break;
170
366
  }
367
+
368
+ const scope_close = if (self.activeHtmlBlockScopeName()) |name|
369
+ findUnbalancedHtmlClosingTag(line, name)
370
+ else if (self.html_block_scope_overflow_depth > 0)
371
+ findUnbalancedHtmlScopeClosingTag(line)
372
+ else
373
+ null;
374
+ if (scope_close) |match| {
375
+ _ = lines.next();
376
+ self.appendHtmlLineFragment(nodes, &len, line[0..match.start]);
377
+ const suffix = line[match.end..];
378
+ if (suffix.len > 0) lines.prepend(suffix);
379
+ _ = self.closeHtmlBlockScope(match.tag);
380
+ continue;
381
+ }
171
382
  if (trimmed.len == 0) {
172
383
  _ = lines.next();
173
384
  continue;
@@ -180,10 +391,32 @@ pub fn Markdown(comptime Msg: type) type {
180
391
  return nodes[0..len];
181
392
  }
182
393
 
394
+ fn appendHtmlLineFragment(self: *Builder, nodes: []Node, len: *usize, fragment: []const u8) void {
395
+ var fragment_lines = LineIterator{ .source = fragment };
396
+ while (fragment_lines.peek()) |line| {
397
+ if (std.mem.trim(u8, line, " \t").len == 0) {
398
+ _ = fragment_lines.next();
399
+ continue;
400
+ }
401
+ const node = self.parseBlock(&fragment_lines) orelse continue;
402
+ if (len.* >= nodes.len) return;
403
+ nodes[len.*] = node;
404
+ len.* += 1;
405
+ }
406
+ }
407
+
183
408
  fn parseBlock(self: *Builder, lines: *LineIterator) ?Node {
184
409
  const line = lines.peek() orelse return null;
185
410
  const trimmed = std.mem.trim(u8, line, " \t");
186
411
 
412
+ // Definitions are block syntax even when no reference uses
413
+ // them. GitHub bots use that property for hidden metadata
414
+ // (`[vc]: #...`): consume the definition without needing to
415
+ // implement reference-link resolution.
416
+ if (isLinkReferenceDefinition(line)) {
417
+ _ = lines.next();
418
+ return null;
419
+ }
187
420
  if (std.mem.startsWith(u8, trimmed, "```")) return self.parseCodeFence(lines);
188
421
  if (headingLevel(trimmed)) |level| {
189
422
  _ = lines.next();
@@ -196,6 +429,11 @@ pub fn Markdown(comptime Msg: type) type {
196
429
  if (std.mem.startsWith(u8, trimmed, ">")) return self.parseBlockquote(lines);
197
430
  if (listMarker(line)) |_| return self.parseList(lines, 0, 0);
198
431
  if (std.ascii.startsWithIgnoreCase(trimmed, "<details")) return self.parseDetails(lines);
432
+ switch (self.parseHtmlBlock(lines, trimmed)) {
433
+ .not_html => {},
434
+ .skipped => return null,
435
+ .node => |node| return node,
436
+ }
199
437
  if (isTableStart(lines)) return self.parseTable(lines);
200
438
  return self.parseParagraph(lines);
201
439
  }
@@ -204,9 +442,10 @@ pub fn Markdown(comptime Msg: type) type {
204
442
 
205
443
  fn heading(self: *Builder, level: usize, content: []const u8) Node {
206
444
  const scale = heading_scales[@min(level, heading_scales.len) - 1];
207
- var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
208
- const parsed = self.parseInline(content, .{ .weight = .bold, .scale = scale }, &spans);
209
- return self.ui.paragraph(.{ .on_link = self.options.on_link }, parsed);
445
+ return self.inlineParagraphNode(content, .{ .weight = .bold, .scale = scale }, .{
446
+ .on_link = self.options.on_link,
447
+ .text_alignment = self.html_alignment orelse .start,
448
+ });
210
449
  }
211
450
 
212
451
  fn parseParagraph(self: *Builder, lines: *LineIterator) ?Node {
@@ -223,7 +462,13 @@ pub fn Markdown(comptime Msg: type) type {
223
462
  /// paragraph break rules only apply once the block has
224
463
  /// content). Tables interrupt paragraphs (GFM): a header
225
464
  /// line followed by a matching delimiter row starts a table.
226
- fn joinPiece(lines: *LineIterator, kind: JoinKind, joined_len: usize) ?[]const u8 {
465
+ fn joinPiece(
466
+ self: *Builder,
467
+ lines: *LineIterator,
468
+ kind: JoinKind,
469
+ joined_len: usize,
470
+ opaque_html: *HtmlOpaqueState,
471
+ ) ?[]const u8 {
227
472
  const line = lines.peek() orelse return null;
228
473
  const trimmed = std.mem.trim(u8, line, " \t");
229
474
  switch (kind) {
@@ -234,8 +479,24 @@ pub fn Markdown(comptime Msg: type) type {
234
479
  return std.mem.trim(u8, inner, " \t");
235
480
  },
236
481
  .paragraph => {
237
- if (trimmed.len == 0) return null;
238
- if (joined_len > 0 and (startsNewBlock(line) or isTableStart(lines))) return null;
482
+ // Unsupported elements are literal opaque regions,
483
+ // even when they contain blank lines or block-shaped
484
+ // allowlisted tags. Keep collecting until the outer
485
+ // unsupported element closes so `parseInline` sees and
486
+ // preserves the region as one unit.
487
+ if (!opaque_html.active()) {
488
+ if (trimmed.len == 0) return null;
489
+ }
490
+ if (joined_len > 0 and !opaque_html.active()) {
491
+ const closes_scope = if (self.activeHtmlBlockScopeName()) |name|
492
+ findUnbalancedHtmlClosingTag(line, name) != null
493
+ else if (self.html_block_scope_overflow_depth > 0)
494
+ findUnbalancedHtmlScopeClosingTag(line) != null
495
+ else
496
+ false;
497
+ if (closes_scope or startsNewBlock(line) or isTableStart(lines)) return null;
498
+ }
499
+ updateHtmlOpaqueState(line, opaque_html);
239
500
  return trimmed;
240
501
  },
241
502
  }
@@ -252,7 +513,8 @@ pub fn Markdown(comptime Msg: type) type {
252
513
  // Pass 1: measure the block's extent and joined size.
253
514
  var probe = lines.*;
254
515
  var total: usize = 0;
255
- while (joinPiece(&probe, kind, total)) |piece| {
516
+ var probe_opaque = HtmlOpaqueState{};
517
+ while (self.joinPiece(&probe, kind, total, &probe_opaque)) |piece| {
256
518
  _ = probe.next();
257
519
  if (total > 0) total += 1;
258
520
  total += piece.len;
@@ -271,7 +533,8 @@ pub fn Markdown(comptime Msg: type) type {
271
533
  // Pass 2: identical walk, copying until the cap.
272
534
  var len: usize = 0;
273
535
  var joined: usize = 0;
274
- while (joinPiece(lines, kind, joined)) |piece| {
536
+ var opaque_html = HtmlOpaqueState{};
537
+ while (self.joinPiece(lines, kind, joined, &opaque_html)) |piece| {
275
538
  _ = lines.next();
276
539
  if (joined > 0 and len < out.len) {
277
540
  out[len] = ' ';
@@ -287,9 +550,10 @@ pub fn Markdown(comptime Msg: type) type {
287
550
  }
288
551
 
289
552
  fn paragraphNode(self: *Builder, text: []const u8, base: TextSpan) Node {
290
- var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
291
- const parsed = self.parseInline(text, base, &spans);
292
- return self.ui.paragraph(.{ .on_link = self.options.on_link }, parsed);
553
+ return self.inlineParagraphNode(text, base, .{
554
+ .on_link = self.options.on_link,
555
+ .text_alignment = self.html_alignment orelse .start,
556
+ });
293
557
  }
294
558
 
295
559
  fn parseCodeFence(self: *Builder, lines: *LineIterator) ?Node {
@@ -317,8 +581,42 @@ pub fn Markdown(comptime Msg: type) type {
317
581
  fn paragraphWithOptions(self: *Builder, text: []const u8, options_in: Ui.ElementOptions) Node {
318
582
  var options = options_in;
319
583
  options.on_link = self.options.on_link;
584
+ if (self.html_alignment) |alignment| options.text_alignment = alignment;
585
+ return self.inlineParagraphNode(text, .{}, options);
586
+ }
587
+
588
+ fn inlineParagraphNode(self: *Builder, text: []const u8, base: TextSpan, options: Ui.ElementOptions) Node {
589
+ if (self.resolvedLeadingImage(text)) |resolved| {
590
+ var children: [2]Node = undefined;
591
+ var child_len: usize = 0;
592
+ children[child_len] = self.resolvedImageNode(resolved);
593
+ child_len += 1;
594
+
595
+ const suffix = std.mem.trimStart(u8, text[resolved.consumed..], " \t");
596
+ if (suffix.len > 0) {
597
+ var suffix_spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
598
+ const parsed_suffix = self.parseInline(suffix, base, &suffix_spans);
599
+ children[child_len] = self.ui.paragraph(.{
600
+ .grow = 1,
601
+ .on_link = options.on_link,
602
+ .text_alignment = options.text_alignment,
603
+ .style = options.style,
604
+ .style_tokens = options.style_tokens,
605
+ }, parsed_suffix);
606
+ child_len += 1;
607
+ }
608
+
609
+ return self.ui.row(.{
610
+ .grow = options.grow,
611
+ .padding = options.padding,
612
+ .gap = 6,
613
+ .main = imageMainAlignment(options.text_alignment),
614
+ .cross = .center,
615
+ }, .{children[0..child_len]});
616
+ }
617
+
320
618
  var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
321
- const parsed = self.parseInline(text, .{}, &spans);
619
+ const parsed = self.parseInline(text, base, &spans);
322
620
  return self.ui.paragraph(options, parsed);
323
621
  }
324
622
 
@@ -372,6 +670,325 @@ pub fn Markdown(comptime Msg: type) type {
372
670
  return self.ui.row(.{ .gap = 8 }, .{ indent, lead_top, content });
373
671
  }
374
672
 
673
+ const HtmlBlockResult = union(enum) {
674
+ not_html,
675
+ skipped,
676
+ node: Node,
677
+ };
678
+
679
+ /// Lower the small block-shaped portion of GitHub's safe HTML
680
+ /// vocabulary onto native widgets. Inline-shaped tags are left
681
+ /// to `parseInline`; unsupported tags fall through literally.
682
+ fn parseHtmlBlock(self: *Builder, lines: *LineIterator, trimmed: []const u8) HtmlBlockResult {
683
+ if (std.mem.startsWith(u8, trimmed, "<!--")) {
684
+ if (consumeHtmlCommentBlock(lines)) return .skipped;
685
+ return .not_html;
686
+ }
687
+
688
+ const opening = parseHtmlTagAt(trimmed, 0) orelse return .not_html;
689
+ if (opening.closing or !isHtmlBlockTag(opening)) {
690
+ if (opening.consumed == trimmed.len and opening.closing and isHtmlStructuralTag(opening)) {
691
+ if (!self.closeHtmlBlockScope(opening)) return .not_html;
692
+ _ = lines.next();
693
+ return .skipped;
694
+ }
695
+ return .not_html;
696
+ }
697
+
698
+ if (opening.kind == .horizontal_rule) {
699
+ consumeHtmlOpeningLine(lines, trimmed, opening);
700
+ return .{ .node = self.ui.separator(.{}) };
701
+ }
702
+
703
+ if (opening.kind == .blockquote) {
704
+ const block_start = lines.*;
705
+ consumeHtmlOpeningLine(lines, trimmed, opening);
706
+ if (opening.self_closing) return .skipped;
707
+ if (self.html_block_depth >= max_markdown_html_block_depth) {
708
+ skipHtmlElement(lines, opening.name);
709
+ return .skipped;
710
+ }
711
+ const element = self.collectHtmlElementLines(lines, opening.name);
712
+ if (!element.closed) {
713
+ lines.* = block_start;
714
+ return .not_html;
715
+ }
716
+ const presentation = self.htmlPresentationSnapshot();
717
+ defer self.restoreHtmlPresentation(presentation);
718
+ if (htmlTagAlignment(opening)) |alignment| self.html_alignment = alignment;
719
+ self.html_block_depth += 1;
720
+ defer self.html_block_depth -= 1;
721
+ var content_lines = LineIterator{ .source = element.content };
722
+ const blocks = self.parseBlocks(&content_lines, .document);
723
+ return .{ .node = self.ui.row(.{ .gap = 10 }, .{
724
+ self.ui.el(.separator, .{ .frame = geometry.RectF.init(0, 0, 3, 0) }, .{}),
725
+ self.ui.column(.{ .gap = 12, .grow = 1 }, blocks),
726
+ }) };
727
+ }
728
+
729
+ if (opening.kind == .preformatted) {
730
+ const block_start = lines.*;
731
+ consumeHtmlOpeningLine(lines, trimmed, opening);
732
+ if (opening.self_closing) return .skipped;
733
+ const element = self.collectHtmlElementLines(lines, opening.name);
734
+ if (!element.closed) {
735
+ lines.* = block_start;
736
+ return .not_html;
737
+ }
738
+ const content = std.mem.trim(u8, element.content, "\r\n");
739
+ const code = std.mem.trim(u8, unwrapHtmlCode(content), "\r\n");
740
+ return .{ .node = self.ui.code(.{}, self.decodeHtmlEntities(code)) };
741
+ }
742
+
743
+ if (opening.kind == .heading or opening.kind == .paragraph or opening.kind == .list_item) {
744
+ const block_start = lines.*;
745
+ consumeHtmlOpeningLine(lines, trimmed, opening);
746
+ if (opening.self_closing) return .skipped;
747
+ const element = self.collectHtmlElementLines(lines, opening.name);
748
+ if (!element.closed) {
749
+ lines.* = block_start;
750
+ return .not_html;
751
+ }
752
+ const content = self.collapseHtmlWhitespace(element.content);
753
+ const alignment = htmlTagAlignment(opening) orelse self.html_alignment orelse .start;
754
+ return switch (opening.kind) {
755
+ .heading => .{ .node = self.htmlHeading(opening.heading_level, content, alignment) },
756
+ .paragraph => .{ .node = self.htmlParagraph(content, alignment) },
757
+ .list_item => .{ .node = self.htmlListItem(opening, content) },
758
+ else => unreachable,
759
+ };
760
+ }
761
+
762
+ if (singleLineHtmlElement(trimmed, opening)) |element| {
763
+ const alignment = htmlTagAlignment(opening) orelse self.html_alignment orelse .start;
764
+ return switch (opening.kind) {
765
+ .list => blk: {
766
+ _ = lines.next();
767
+ const presentation = self.htmlPresentationSnapshot();
768
+ defer self.restoreHtmlPresentation(presentation);
769
+ self.openHtmlBlockScope(opening);
770
+ var content_lines = LineIterator{ .source = element.content };
771
+ const blocks = self.parseBlocks(&content_lines, .document);
772
+ break :blk .{ .node = self.ui.column(.{ .gap = 4 }, blocks) };
773
+ },
774
+ .container, .table, .table_section, .table_row, .table_cell => blk: {
775
+ _ = lines.next();
776
+ break :blk .{ .node = self.htmlParagraph(element.content, alignment) };
777
+ },
778
+ else => .not_html,
779
+ };
780
+ }
781
+
782
+ // A structural tag on its own line is presentation-only.
783
+ // Keep its alignment/heading scope for the Markdown blocks
784
+ // between the opener and closer, then emit no empty widget.
785
+ if (opening.consumed == trimmed.len and isHtmlStructuralTag(opening)) {
786
+ _ = lines.next();
787
+ if (opening.self_closing) return .skipped;
788
+ self.openHtmlBlockScope(opening);
789
+ return .skipped;
790
+ }
791
+ return .not_html;
792
+ }
793
+
794
+ fn openHtmlBlockScope(self: *Builder, tag: HtmlTag) void {
795
+ if (!isHtmlBlockScopeTag(tag) or tag.self_closing) return;
796
+ if (self.html_block_scope_depth < self.html_block_scope_stack.len) {
797
+ self.html_block_scope_stack[self.html_block_scope_depth] = .{
798
+ .name = tag.name,
799
+ .previous_alignment = self.html_alignment,
800
+ .list_kind = htmlListKind(tag),
801
+ };
802
+ self.html_block_scope_depth += 1;
803
+ } else {
804
+ self.html_block_scope_overflow_depth += 1;
805
+ return;
806
+ }
807
+ if (htmlTagAlignment(tag)) |alignment| self.html_alignment = alignment;
808
+ }
809
+
810
+ fn activeHtmlBlockScopeName(self: *Builder) ?[]const u8 {
811
+ if (self.html_block_scope_overflow_depth > 0 or self.html_block_scope_depth == 0) return null;
812
+ return self.html_block_scope_stack[self.html_block_scope_depth - 1].name;
813
+ }
814
+
815
+ fn activeHtmlListScope(self: *Builder) ?*HtmlBlockScope {
816
+ if (self.html_block_scope_overflow_depth > 0) return null;
817
+ var index = self.html_block_scope_depth;
818
+ while (index > 0) {
819
+ index -= 1;
820
+ const scope = &self.html_block_scope_stack[index];
821
+ if (scope.list_kind != null) return scope;
822
+ }
823
+ return null;
824
+ }
825
+
826
+ fn closeHtmlBlockScope(self: *Builder, tag: HtmlTag) bool {
827
+ if (!isHtmlBlockScopeTag(tag)) return true;
828
+ if (self.html_block_scope_overflow_depth > 0) {
829
+ self.html_block_scope_overflow_depth -= 1;
830
+ return true;
831
+ }
832
+ if (self.html_block_scope_depth == 0) return false;
833
+ const scope = self.html_block_scope_stack[self.html_block_scope_depth - 1];
834
+ if (!std.ascii.eqlIgnoreCase(scope.name, tag.name)) return false;
835
+ self.html_block_scope_depth -= 1;
836
+ self.html_alignment = scope.previous_alignment;
837
+ return true;
838
+ }
839
+
840
+ fn htmlPresentationSnapshot(self: *Builder) HtmlPresentationSnapshot {
841
+ return .{
842
+ .alignment = self.html_alignment,
843
+ .scope_depth = self.html_block_scope_depth,
844
+ .overflow_depth = self.html_block_scope_overflow_depth,
845
+ };
846
+ }
847
+
848
+ fn restoreHtmlPresentation(self: *Builder, snapshot: HtmlPresentationSnapshot) void {
849
+ self.html_alignment = snapshot.alignment;
850
+ self.html_block_scope_depth = snapshot.scope_depth;
851
+ self.html_block_scope_overflow_depth = snapshot.overflow_depth;
852
+ }
853
+
854
+ /// Consume lines through the matching closer for an opening tag
855
+ /// that the caller has already removed. The returned arena slice
856
+ /// contains only the element body; any bytes after the closer are
857
+ /// prepended so ordinary block parsing resumes on them.
858
+ const CollectedHtmlElement = struct {
859
+ content: []const u8,
860
+ closed: bool,
861
+ };
862
+
863
+ fn collectHtmlElementLines(self: *Builder, lines: *LineIterator, name: []const u8) CollectedHtmlElement {
864
+ var probe = lines.*;
865
+ var probe_depth: usize = 1;
866
+ var probe_opaque = HtmlOpaqueState{};
867
+ var total: usize = 0;
868
+ var closed = false;
869
+ while (probe.next()) |line| {
870
+ const scan = scanHtmlElementLine(line, name, &probe_depth, &probe_opaque);
871
+ total = @min(max_markdown_paragraph_bytes, total +| scan.content_end);
872
+ if (scan.closing_end) |closing_end| {
873
+ const suffix = line[closing_end..];
874
+ if (suffix.len > 0) probe.prepend(suffix);
875
+ closed = true;
876
+ break;
877
+ }
878
+ total = @min(max_markdown_paragraph_bytes, total +| 1);
879
+ }
880
+ if (!closed) return .{ .content = &.{}, .closed = false };
881
+
882
+ const out = self.ui.arena.alloc(u8, total) catch {
883
+ self.ui.failed = true;
884
+ lines.* = probe;
885
+ return .{ .content = &.{}, .closed = true };
886
+ };
887
+ var depth: usize = 1;
888
+ var opaque_html = HtmlOpaqueState{};
889
+ var len: usize = 0;
890
+ while (lines.next()) |line| {
891
+ const scan = scanHtmlElementLine(line, name, &depth, &opaque_html);
892
+ if (scan.content_end > 0 and len < out.len) {
893
+ const take = @min(scan.content_end, out.len - len);
894
+ @memcpy(out[len..][0..take], line[0..take]);
895
+ len += take;
896
+ }
897
+ if (scan.closing_end) |closing_end| {
898
+ const suffix = line[closing_end..];
899
+ if (suffix.len > 0) lines.prepend(suffix);
900
+ break;
901
+ }
902
+ if (len < out.len) {
903
+ out[len] = '\n';
904
+ len += 1;
905
+ }
906
+ }
907
+ return .{ .content = out[0..len], .closed = true };
908
+ }
909
+
910
+ /// HTML collapses source line boundaries in phrasing content.
911
+ /// Keep within-line bytes exact (including attribute values), but
912
+ /// turn CR/LF boundaries into spaces before inline lowering.
913
+ fn collapseHtmlWhitespace(self: *Builder, raw: []const u8) []const u8 {
914
+ const trimmed = std.mem.trim(u8, raw, " \t\r\n");
915
+ if (std.mem.indexOfAny(u8, trimmed, "\r\n") == null) return trimmed;
916
+ const out = self.ui.arena.alloc(u8, trimmed.len) catch {
917
+ self.ui.failed = true;
918
+ return trimmed;
919
+ };
920
+ var len: usize = 0;
921
+ var index: usize = 0;
922
+ while (index < trimmed.len) : (index += 1) {
923
+ if (trimmed[index] == '\r') {
924
+ if (index + 1 < trimmed.len and trimmed[index + 1] == '\n') index += 1;
925
+ out[len] = ' ';
926
+ } else if (trimmed[index] == '\n') {
927
+ out[len] = ' ';
928
+ } else {
929
+ out[len] = trimmed[index];
930
+ }
931
+ len += 1;
932
+ }
933
+ return out[0..len];
934
+ }
935
+
936
+ fn htmlHeading(self: *Builder, level: usize, content: []const u8, alignment: canvas.TextAlign) Node {
937
+ const scale = heading_scales[@min(level, heading_scales.len) - 1];
938
+ return self.inlineParagraphNode(content, .{ .weight = .bold, .scale = scale }, .{
939
+ .on_link = self.options.on_link,
940
+ .text_alignment = alignment,
941
+ });
942
+ }
943
+
944
+ fn htmlParagraph(self: *Builder, content: []const u8, alignment: canvas.TextAlign) Node {
945
+ return self.htmlParagraphWithOptions(content, alignment, .{});
946
+ }
947
+
948
+ fn htmlParagraphWithOptions(
949
+ self: *Builder,
950
+ content: []const u8,
951
+ alignment: canvas.TextAlign,
952
+ options_in: Ui.ElementOptions,
953
+ ) Node {
954
+ return self.htmlParagraphWithBase(content, alignment, options_in, .{});
955
+ }
956
+
957
+ fn htmlParagraphWithBase(
958
+ self: *Builder,
959
+ content: []const u8,
960
+ alignment: canvas.TextAlign,
961
+ options_in: Ui.ElementOptions,
962
+ base: TextSpan,
963
+ ) Node {
964
+ var options = options_in;
965
+ options.on_link = self.options.on_link;
966
+ options.text_alignment = alignment;
967
+ return self.inlineParagraphNode(content, base, options);
968
+ }
969
+
970
+ fn htmlListItem(self: *Builder, tag: HtmlTag, content: []const u8) Node {
971
+ if (std.ascii.eqlIgnoreCase(tag.name, "dt")) {
972
+ return self.htmlParagraphWithBase(content, self.html_alignment orelse .start, .{}, .{ .weight = .bold });
973
+ }
974
+ if (std.ascii.eqlIgnoreCase(tag.name, "dd")) {
975
+ return self.ui.row(.{ .gap = 8 }, .{
976
+ self.ui.el(.stack, .{ .width = 16 }, .{}),
977
+ self.htmlParagraphWithBase(content, self.html_alignment orelse .start, .{ .grow = 1 }, .{}),
978
+ });
979
+ }
980
+
981
+ var marker = ListMarker{ .kind = .bullet, .indent = 0, .label = "", .content = content };
982
+ if (self.activeHtmlListScope()) |scope| {
983
+ if (scope.list_kind == .ordered) {
984
+ marker.kind = .ordered;
985
+ marker.label = self.ui.fmt("{d}.", .{scope.next_ordinal});
986
+ scope.next_ordinal +|= 1;
987
+ }
988
+ }
989
+ return self.listItemNode(marker, 0);
990
+ }
991
+
375
992
  fn parseDetails(self: *Builder, lines: *LineIterator) ?Node {
376
993
  _ = lines.next(); // <details ...>
377
994
  const ordinal = self.details_count;
@@ -395,10 +1012,18 @@ pub fn Markdown(comptime Msg: type) type {
395
1012
  }
396
1013
  }
397
1014
 
398
- var header = self.ui.listItem(.{
1015
+ const indicator = if (expanded) "▾" else "▸";
1016
+ const summary_node = self.paragraphWithOptions(summary, .{ .grow = 1 });
1017
+ const header_label = self.ui.fmt("{s} {s}", .{ indicator, summary_node.widget.text });
1018
+ var header = self.ui.el(.list_item, .{
399
1019
  .key = .{ .int = @intCast(ordinal) },
400
1020
  .on_press = if (self.options.on_details) |make| make(ordinal) else null,
401
- }, self.ui.fmt("{s} {s}", .{ if (expanded) "▾" else "▸", summary }));
1021
+ .gap = 6,
1022
+ .semantics = .{ .label = header_label },
1023
+ }, .{
1024
+ self.ui.text(.{}, indicator),
1025
+ summary_node,
1026
+ });
402
1027
  header.widget.state.expanded = expanded;
403
1028
 
404
1029
  if (!expanded) {
@@ -454,12 +1079,43 @@ pub fn Markdown(comptime Msg: type) type {
454
1079
  return self.ui.el(.data_row, .{}, .{cells});
455
1080
  }
456
1081
 
457
- /// One cell: a `data_cell` widget carrying inline spans (the
458
- /// full inline grammar, links included), per-column text
459
- /// alignment from the delimiter row, and bold header styling.
1082
+ /// One cell: ordinarily a `data_cell` widget carrying inline
1083
+ /// spans (the full inline grammar, links included). A resolved
1084
+ /// leading image becomes a real image leaf beside the remaining
1085
+ /// span paragraph, while the cell retains its gridcell semantics,
1086
+ /// padding, alignment, and chrome.
460
1087
  fn tableCellNode(self: *Builder, content: []const u8, alignment: canvas.TextAlign, is_header: bool) Node {
461
1088
  const text = self.unescapeTablePipes(content);
462
1089
  const base: TextSpan = if (is_header) .{ .weight = .bold } else .{};
1090
+ if (self.resolvedLeadingImage(text)) |resolved| {
1091
+ var children: [2]Node = undefined;
1092
+ var child_len: usize = 0;
1093
+ children[child_len] = self.resolvedImageNode(resolved);
1094
+ child_len += 1;
1095
+
1096
+ const suffix = std.mem.trimStart(u8, text[resolved.consumed..], " \t");
1097
+ if (suffix.len > 0) {
1098
+ var suffix_spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
1099
+ const parsed_suffix = self.parseInline(suffix, base, &suffix_spans);
1100
+ children[child_len] = self.ui.paragraph(.{
1101
+ .grow = 1,
1102
+ .on_link = self.options.on_link,
1103
+ .text_alignment = alignment,
1104
+ }, parsed_suffix);
1105
+ child_len += 1;
1106
+ }
1107
+
1108
+ var cell = self.ui.el(.data_cell, .{
1109
+ .grow = 1,
1110
+ .padding = 8,
1111
+ .gap = 6,
1112
+ .main = imageMainAlignment(alignment),
1113
+ .cross = .center,
1114
+ }, .{children[0..child_len]});
1115
+ cell.widget.text_alignment = alignment;
1116
+ return cell;
1117
+ }
1118
+
463
1119
  var spans: [text_spans.max_text_spans_per_paragraph]TextSpan = undefined;
464
1120
  const parsed = self.parseInline(text, base, &spans);
465
1121
  var cell = self.ui.paragraph(.{
@@ -472,6 +1128,57 @@ pub fn Markdown(comptime Msg: type) type {
472
1128
  return cell;
473
1129
  }
474
1130
 
1131
+ const ResolvedLeadingImage = struct {
1132
+ mapping: ResolvedImage,
1133
+ consumed: usize,
1134
+ alt: []const u8,
1135
+ link: []const u8,
1136
+ width: f32,
1137
+ height: f32,
1138
+ };
1139
+
1140
+ fn resolvedLeadingImage(self: *Builder, text: []const u8) ?ResolvedLeadingImage {
1141
+ const parsed = parseLeadingInlineImage(text) orelse return null;
1142
+ const source = self.decodeHtmlEntities(parsed.source);
1143
+ const mapping = self.findResolvedImage(source) orelse return null;
1144
+ const alt = self.decodeHtmlEntities(parsed.alt);
1145
+ const link = self.decodeHtmlEntities(parsed.link);
1146
+ const dimensions = resolvedInlineImageDimensions(mapping, parsed.width, parsed.height);
1147
+ return .{
1148
+ .mapping = mapping,
1149
+ .consumed = parsed.consumed,
1150
+ .alt = alt,
1151
+ .link = link,
1152
+ .width = dimensions.width,
1153
+ .height = dimensions.height,
1154
+ };
1155
+ }
1156
+
1157
+ fn resolvedImageNode(self: *Builder, resolved: ResolvedLeadingImage) Node {
1158
+ return self.ui.image(.{
1159
+ .image = resolved.mapping.image,
1160
+ .width = resolved.width,
1161
+ .height = resolved.height,
1162
+ .semantics = .{
1163
+ .role = if (resolved.link.len > 0) .link else .image,
1164
+ .label = resolved.alt,
1165
+ .focusable = resolved.link.len > 0,
1166
+ },
1167
+ .on_press = if (resolved.link.len > 0 and self.options.on_link != null)
1168
+ self.options.on_link.?(resolved.link)
1169
+ else
1170
+ null,
1171
+ });
1172
+ }
1173
+
1174
+ fn findResolvedImage(self: *const Builder, source: []const u8) ?ResolvedImage {
1175
+ for (self.options.images[0..@min(self.options.images.len, max_markdown_images)]) |image| {
1176
+ if (image.image == 0 or !validImageDimension(image.width) or !validImageDimension(image.height)) continue;
1177
+ if (std.mem.eql(u8, image.source, source)) return image;
1178
+ }
1179
+ return null;
1180
+ }
1181
+
475
1182
  /// `\|` is the one backslash escape tables need (a literal
476
1183
  /// pipe inside a cell); everything else keeps the mapper's
477
1184
  /// no-escapes policy.
@@ -513,12 +1220,13 @@ pub fn Markdown(comptime Msg: type) type {
513
1220
  /// the text as one unstyled span.
514
1221
  fn parseInline(self: *Builder, text: []const u8, base: TextSpan, spans: *[text_spans.max_text_spans_per_paragraph]TextSpan) []const TextSpan {
515
1222
  var len: usize = 0;
516
- var bold = false;
517
- var italic = false;
518
- var strike = false;
1223
+ var style = InlineStyleState{};
519
1224
  var literal_start: usize = 0;
520
1225
  var index: usize = 0;
521
1226
  var scan_cache = ScanCache{};
1227
+ var consumed_html = false;
1228
+ var html_open_tags: [text_spans.max_text_spans_per_paragraph]HtmlInlineOpenTag = undefined;
1229
+ var html_open_depth: usize = 0;
522
1230
 
523
1231
  while (index < text.len) {
524
1232
  if (len + 2 >= spans.len) break;
@@ -526,25 +1234,25 @@ pub fn Markdown(comptime Msg: type) type {
526
1234
 
527
1235
  if (rest[0] == '`') {
528
1236
  if (std.mem.indexOfScalar(u8, rest[1..], '`')) |close| {
529
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
530
- appendSpan(spans, &len, spanWith(base, .{ .text = rest[1 .. 1 + close], .monospace = true }));
1237
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1238
+ appendStyledSpan(spans, &len, base, style, .{ .text = rest[1 .. 1 + close], .monospace = true });
531
1239
  index += close + 2;
532
1240
  literal_start = index;
533
1241
  continue;
534
1242
  }
535
1243
  } else if (std.mem.startsWith(u8, rest, "**") or std.mem.startsWith(u8, rest, "__")) {
536
1244
  const delim = rest[0..2];
537
- if (bold or hasCloser(rest[2..], delim)) {
538
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
539
- bold = !bold;
1245
+ if (style.markdown_bold or hasCloser(rest[2..], delim)) {
1246
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1247
+ style.markdown_bold = !style.markdown_bold;
540
1248
  index += 2;
541
1249
  literal_start = index;
542
1250
  continue;
543
1251
  }
544
1252
  } else if (std.mem.startsWith(u8, rest, "~~")) {
545
- if (strike or hasCloser(rest[2..], "~~")) {
546
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
547
- strike = !strike;
1253
+ if (style.markdown_strike or hasCloser(rest[2..], "~~")) {
1254
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1255
+ style.markdown_strike = !style.markdown_strike;
548
1256
  index += 2;
549
1257
  literal_start = index;
550
1258
  continue;
@@ -552,21 +1260,21 @@ pub fn Markdown(comptime Msg: type) type {
552
1260
  } else if (rest[0] == '*' or rest[0] == '_') {
553
1261
  const delim = rest[0..1];
554
1262
  const boundary_ok = rest[0] == '*' or index == 0 or !isWordByte(text[index - 1]);
555
- const emphasis_ok = if (italic)
1263
+ const emphasis_ok = if (style.markdown_italic)
556
1264
  true
557
1265
  else
558
1266
  rest.len > 1 and !isInlineSpace(rest[1]) and hasCloser(rest[1..], delim);
559
1267
  if (boundary_ok and emphasis_ok) {
560
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
561
- italic = !italic;
1268
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1269
+ style.markdown_italic = !style.markdown_italic;
562
1270
  index += 1;
563
1271
  literal_start = index;
564
1272
  continue;
565
1273
  }
566
1274
  } else if (rest[0] == '[') {
567
1275
  if (parseLinkAt(text, index, &scan_cache)) |link| {
568
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
569
- appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
1276
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1277
+ appendStyledSpan(spans, &len, base, style, .{ .text = link.text, .link = link.target });
570
1278
  index += link.consumed;
571
1279
  literal_start = index;
572
1280
  continue;
@@ -574,24 +1282,79 @@ pub fn Markdown(comptime Msg: type) type {
574
1282
  } else if (rest[0] == '!' and rest.len > 1 and rest[1] == '[') {
575
1283
  if (parseLinkAt(text, index + 1, &scan_cache)) |image| {
576
1284
  // Images render as their alt text in v1.
577
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
578
- appendSpan(spans, &len, spanWith(base, .{ .text = image.text }));
1285
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1286
+ appendStyledSpan(spans, &len, base, style, .{ .text = image.text });
579
1287
  index += image.consumed + 1;
580
1288
  literal_start = index;
581
1289
  continue;
582
1290
  }
583
1291
  } else if (rest[0] == '<') {
584
- if (parseAutolinkAt(text, index, &scan_cache)) |link| {
585
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
586
- appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
1292
+ if (parseHtmlCommentAt(text, index, &scan_cache)) |comment| {
1293
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1294
+ consumed_html = true;
1295
+ index += comment.consumed;
1296
+ literal_start = index;
1297
+ continue;
1298
+ } else if (parseAutolinkAt(text, index, &scan_cache)) |link| {
1299
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1300
+ appendStyledSpan(spans, &len, base, style, .{ .text = link.text, .link = link.target });
587
1301
  index += link.consumed;
588
1302
  literal_start = index;
589
1303
  continue;
1304
+ } else if (parseHtmlTagAt(text, index)) |tag| {
1305
+ const requires_closer = htmlTagRequiresClosing(tag);
1306
+ const accepted = if (tag.closing)
1307
+ requires_closer and html_open_depth > 0 and
1308
+ std.ascii.eqlIgnoreCase(html_open_tags[html_open_depth - 1].name, tag.name)
1309
+ else if (tag.self_closing or !requires_closer)
1310
+ true
1311
+ else
1312
+ html_open_depth < html_open_tags.len and
1313
+ hasMatchingHtmlClosingTag(text, index + tag.consumed, tag.name);
1314
+ if (!accepted) {
1315
+ // Keep malformed/stray syntax in the pending
1316
+ // literal run, but skip its bytes as a unit so
1317
+ // Markdown-looking attribute text stays inert.
1318
+ index += tag.consumed;
1319
+ continue;
1320
+ }
1321
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1322
+ consumed_html = true;
1323
+ self.applyHtmlTag(spans, &len, base, &style, tag);
1324
+ if (tag.closing) {
1325
+ html_open_depth -= 1;
1326
+ } else if (requires_closer and !tag.self_closing) {
1327
+ html_open_tags[html_open_depth] = .{ .name = tag.name };
1328
+ html_open_depth += 1;
1329
+ }
1330
+ index += tag.consumed;
1331
+ literal_start = index;
1332
+ continue;
1333
+ } else if (parseHtmlTagSyntaxAt(text, index)) |tag| {
1334
+ // Unsupported HTML is one opaque literal region:
1335
+ // do not style allowlisted descendants or decode
1336
+ // entities inside scripts, styles, embeds, forms,
1337
+ // or unknown wrappers.
1338
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1339
+ const end = unsupportedHtmlElementEnd(text, index, tag);
1340
+ appendStyledSpan(spans, &len, base, style, .{ .text = text[index..end] });
1341
+ index = end;
1342
+ literal_start = index;
1343
+ continue;
1344
+ }
1345
+ } else if (rest[0] == '&') {
1346
+ if (self.decodeHtmlEntity(rest)) |entity| {
1347
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1348
+ appendStyledSpan(spans, &len, base, style, .{ .text = entity.text });
1349
+ consumed_html = true;
1350
+ index += entity.consumed;
1351
+ literal_start = index;
1352
+ continue;
590
1353
  }
591
1354
  } else if (rest[0] == 'h' and atAutolinkBoundary(text, index)) {
592
1355
  if (parseBareUrlAt(rest)) |link| {
593
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
594
- appendSpan(spans, &len, spanWith(base, .{ .text = link.text, .link = link.target }));
1356
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1357
+ appendStyledSpan(spans, &len, base, style, .{ .text = link.text, .link = link.target });
595
1358
  index += link.consumed;
596
1359
  literal_start = index;
597
1360
  continue;
@@ -599,11 +1362,11 @@ pub fn Markdown(comptime Msg: type) type {
599
1362
  } else if (rest[0] == '#' and atAutolinkBoundary(text, index)) {
600
1363
  if (self.options.issue_link_base) |issue_base| {
601
1364
  if (parseIssueRefAt(rest)) |ref| {
602
- flushLiteral(spans, &len, text[literal_start..index], base, bold, italic, strike);
603
- appendSpan(spans, &len, spanWith(base, .{
1365
+ flushLiteral(spans, &len, text[literal_start..index], base, style);
1366
+ appendStyledSpan(spans, &len, base, style, .{
604
1367
  .text = rest[0..ref.consumed],
605
1368
  .link = self.ui.fmt("{s}{s}", .{ issue_base, ref.digits }),
606
- }));
1369
+ });
607
1370
  index += ref.consumed;
608
1371
  literal_start = index;
609
1372
  continue;
@@ -614,28 +1377,159 @@ pub fn Markdown(comptime Msg: type) type {
614
1377
  }
615
1378
  // Tail (including everything after a span-capacity stop),
616
1379
  // styled with the state at the stop point.
617
- flushLiteral(spans, &len, text[literal_start..], base, bold, italic, strike);
618
- if (len == 0) {
1380
+ flushLiteral(spans, &len, text[literal_start..], base, style);
1381
+ if (len == 0 and !consumed_html) {
619
1382
  spans[0] = spanWith(base, .{ .text = text });
620
1383
  len = 1;
621
1384
  }
622
1385
  return spans[0..len];
623
1386
  }
624
1387
 
1388
+ const InlineStyleState = struct {
1389
+ markdown_bold: bool = false,
1390
+ markdown_italic: bool = false,
1391
+ markdown_strike: bool = false,
1392
+ html_bold: usize = 0,
1393
+ html_italic: usize = 0,
1394
+ html_strike: usize = 0,
1395
+ html_underline: usize = 0,
1396
+ html_monospace: usize = 0,
1397
+ html_mark: usize = 0,
1398
+ html_small: usize = 0,
1399
+ html_heading_level: ?usize = null,
1400
+ html_link: []const u8 = "",
1401
+ };
1402
+
1403
+ const HtmlInlineOpenTag = struct {
1404
+ name: []const u8,
1405
+ };
1406
+
1407
+ fn applyHtmlTag(
1408
+ self: *Builder,
1409
+ spans: *[text_spans.max_text_spans_per_paragraph]TextSpan,
1410
+ len: *usize,
1411
+ base: TextSpan,
1412
+ style: *InlineStyleState,
1413
+ tag: HtmlTag,
1414
+ ) void {
1415
+ const active = !tag.self_closing;
1416
+ switch (tag.kind) {
1417
+ .bold => updateHtmlDepth(&style.html_bold, tag.closing, active),
1418
+ .italic => updateHtmlDepth(&style.html_italic, tag.closing, active),
1419
+ .strike => updateHtmlDepth(&style.html_strike, tag.closing, active),
1420
+ .underline => updateHtmlDepth(&style.html_underline, tag.closing, active),
1421
+ .monospace, .preformatted => updateHtmlDepth(&style.html_monospace, tag.closing, active),
1422
+ .mark => updateHtmlDepth(&style.html_mark, tag.closing, active),
1423
+ .small => updateHtmlDepth(&style.html_small, tag.closing, active),
1424
+ .heading => style.html_heading_level = if (tag.closing or tag.self_closing) null else tag.heading_level,
1425
+ .link => {
1426
+ if (tag.closing or tag.self_closing) {
1427
+ style.html_link = "";
1428
+ } else {
1429
+ const href = htmlAttribute(tag, "href") orelse "";
1430
+ style.html_link = self.decodeHtmlEntities(href);
1431
+ }
1432
+ },
1433
+ .line_break => if (!tag.closing) appendStyledSpan(spans, len, base, style.*, .{ .text = "\n" }),
1434
+ .word_break => if (!tag.closing) appendStyledSpan(spans, len, base, style.*, .{ .text = "\u{200b}" }),
1435
+ .image => if (!tag.closing) {
1436
+ if (htmlAttribute(tag, "alt")) |alt| {
1437
+ appendStyledSpan(spans, len, base, style.*, .{ .text = self.decodeHtmlEntities(alt) });
1438
+ }
1439
+ },
1440
+ .quote => if (!tag.self_closing) appendStyledSpan(spans, len, base, style.*, .{ .text = if (tag.closing) "”" else "“" }),
1441
+ .list_item => if (!tag.self_closing) appendStyledSpan(spans, len, base, style.*, .{ .text = if (tag.closing) "\n" else "• " }),
1442
+ .table_cell => if (tag.closing) appendStyledSpan(spans, len, base, style.*, .{ .text = "\t" }),
1443
+ .table_row => if (tag.closing) appendStyledSpan(spans, len, base, style.*, .{ .text = "\n" }),
1444
+ .horizontal_rule => if (!tag.closing) appendStyledSpan(spans, len, base, style.*, .{ .text = "\n" }),
1445
+ .paragraph, .blockquote, .list, .table, .table_section, .container => {},
1446
+ }
1447
+ }
1448
+
1449
+ fn decodeHtmlEntities(self: *Builder, text: []const u8) []const u8 {
1450
+ if (std.mem.indexOfScalar(u8, text, '&') == null) return text;
1451
+ const out = self.ui.arena.alloc(u8, text.len) catch {
1452
+ self.ui.failed = true;
1453
+ return text;
1454
+ };
1455
+ var source_index: usize = 0;
1456
+ var out_len: usize = 0;
1457
+ while (source_index < text.len) {
1458
+ if (text[source_index] == '&') {
1459
+ if (self.decodeHtmlEntity(text[source_index..])) |entity| {
1460
+ @memcpy(out[out_len..][0..entity.text.len], entity.text);
1461
+ out_len += entity.text.len;
1462
+ source_index += entity.consumed;
1463
+ continue;
1464
+ }
1465
+ }
1466
+ out[out_len] = text[source_index];
1467
+ out_len += 1;
1468
+ source_index += 1;
1469
+ }
1470
+ return out[0..out_len];
1471
+ }
1472
+
1473
+ fn decodeHtmlEntity(self: *Builder, rest: []const u8) ?DecodedHtmlEntity {
1474
+ if (std.mem.startsWith(u8, rest, "&amp;")) return .{ .text = "&", .consumed = 5 };
1475
+ if (std.mem.startsWith(u8, rest, "&lt;")) return .{ .text = "<", .consumed = 4 };
1476
+ if (std.mem.startsWith(u8, rest, "&gt;")) return .{ .text = ">", .consumed = 4 };
1477
+ if (std.mem.startsWith(u8, rest, "&quot;")) return .{ .text = "\"", .consumed = 6 };
1478
+ if (std.mem.startsWith(u8, rest, "&apos;")) return .{ .text = "'", .consumed = 6 };
1479
+ if (std.mem.startsWith(u8, rest, "&nbsp;")) return .{ .text = "\u{a0}", .consumed = 6 };
1480
+ if (!std.mem.startsWith(u8, rest, "&#")) return null;
1481
+
1482
+ const semi = std.mem.indexOfScalar(u8, rest[2..@min(rest.len, 14)], ';') orelse return null;
1483
+ const body_end = semi + 2;
1484
+ var digits = rest[2..body_end];
1485
+ var radix: u8 = 10;
1486
+ if (digits.len > 1 and (digits[0] == 'x' or digits[0] == 'X')) {
1487
+ radix = 16;
1488
+ digits = digits[1..];
1489
+ }
1490
+ if (digits.len == 0) return null;
1491
+ const codepoint = std.fmt.parseUnsigned(u21, digits, radix) catch return null;
1492
+ if (codepoint == 0 or codepoint > 0x10ffff or (codepoint >= 0xd800 and codepoint <= 0xdfff)) return null;
1493
+ const bytes = self.ui.arena.alloc(u8, 4) catch {
1494
+ self.ui.failed = true;
1495
+ return null;
1496
+ };
1497
+ const encoded = std.unicode.utf8Encode(codepoint, bytes) catch return null;
1498
+ return .{ .text = bytes[0..encoded], .consumed = body_end + 1 };
1499
+ }
1500
+
625
1501
  fn flushLiteral(
626
1502
  spans: *[text_spans.max_text_spans_per_paragraph]TextSpan,
627
1503
  len: *usize,
628
1504
  slice: []const u8,
629
1505
  base: TextSpan,
630
- bold: bool,
631
- italic: bool,
632
- strike: bool,
1506
+ style: InlineStyleState,
633
1507
  ) void {
634
1508
  if (slice.len == 0) return;
635
- var span = spanWith(base, .{ .text = slice });
636
- if (bold) span.weight = .bold;
637
- if (italic) span.italic = true;
638
- if (strike) span.strikethrough = true;
1509
+ appendStyledSpan(spans, len, base, style, .{ .text = slice });
1510
+ }
1511
+
1512
+ fn appendStyledSpan(
1513
+ spans: *[text_spans.max_text_spans_per_paragraph]TextSpan,
1514
+ len: *usize,
1515
+ base: TextSpan,
1516
+ style: InlineStyleState,
1517
+ overrides: TextSpan,
1518
+ ) void {
1519
+ var span = spanWith(base, overrides);
1520
+ // An empty-alt image inside an HTML anchor has no native
1521
+ // presentation. Do not turn that zero-byte placeholder into
1522
+ // an empty focusable link in the accessibility tree.
1523
+ if (span.text.len == 0) return;
1524
+ if (style.markdown_bold or style.html_bold > 0 or style.html_heading_level != null) span.weight = .bold;
1525
+ if (style.markdown_italic or style.html_italic > 0) span.italic = true;
1526
+ if (style.markdown_strike or style.html_strike > 0) span.strikethrough = true;
1527
+ if (style.html_underline > 0) span.underline = true;
1528
+ if (style.html_monospace > 0) span.monospace = true;
1529
+ if (style.html_mark > 0) span.background = .surface_pressed;
1530
+ if (style.html_small > 0) span.scale = if (span.scale > 0) span.scale * 0.875 else 0.875;
1531
+ if (style.html_heading_level) |level| span.scale = heading_scales[@min(level, heading_scales.len) - 1];
1532
+ if (span.link.len == 0 and style.html_link.len > 0) span.link = style.html_link;
639
1533
  appendSpan(spans, len, span);
640
1534
  }
641
1535
 
@@ -658,13 +1552,947 @@ pub fn Markdown(comptime Msg: type) type {
658
1552
  };
659
1553
  }
660
1554
 
1555
+ const LeadingInlineImage = struct {
1556
+ source: []const u8,
1557
+ alt: []const u8,
1558
+ link: []const u8 = "",
1559
+ width: ?f32 = null,
1560
+ height: ?f32 = null,
1561
+ consumed: usize,
1562
+ };
1563
+
1564
+ const InlineImageDimensions = struct { width: f32, height: f32 };
1565
+
1566
+ /// Recognize the presentation shape GitHub emits for a leading image: a
1567
+ /// Markdown image directly, an HTML `<img>`, or an image wrapped in harmless
1568
+ /// inline presentation tags such as `<a><sup>…</sup></a>`. Consuming the
1569
+ /// matching wrappers as one unit prevents their now-empty tags from leaking
1570
+ /// into the text paragraph beside the native image leaf.
1571
+ fn parseLeadingInlineImage(text: []const u8) ?LeadingInlineImage {
1572
+ var cursor: usize = 0;
1573
+ while (cursor < text.len and isInlineSpace(text[cursor])) cursor += 1;
1574
+
1575
+ if (cursor + 1 < text.len and text[cursor] == '!' and text[cursor + 1] == '[') {
1576
+ var cache = ScanCache{};
1577
+ const parsed = parseLinkAt(text, cursor + 1, &cache) orelse return null;
1578
+ return .{
1579
+ .source = parsed.target,
1580
+ .alt = parsed.text,
1581
+ .consumed = cursor + parsed.consumed + 1,
1582
+ };
1583
+ }
1584
+
1585
+ var wrappers: [8][]const u8 = undefined;
1586
+ var wrapper_len: usize = 0;
1587
+ var link: []const u8 = "";
1588
+ while (cursor < text.len) {
1589
+ const tag = parseHtmlTagAt(text, cursor) orelse return null;
1590
+ if (tag.closing) return null;
1591
+ if (tag.kind == .image) {
1592
+ const source = htmlAttribute(tag, "src") orelse return null;
1593
+ const alt = htmlAttribute(tag, "alt") orelse "";
1594
+ cursor += tag.consumed;
1595
+ while (wrapper_len > 0) {
1596
+ while (cursor < text.len and isInlineSpace(text[cursor])) cursor += 1;
1597
+ const closing = parseHtmlTagAt(text, cursor) orelse return null;
1598
+ if (!closing.closing or !std.ascii.eqlIgnoreCase(closing.name, wrappers[wrapper_len - 1])) return null;
1599
+ cursor += closing.consumed;
1600
+ wrapper_len -= 1;
1601
+ }
1602
+ return .{
1603
+ .source = source,
1604
+ .alt = alt,
1605
+ .link = link,
1606
+ .width = htmlImageDimension(tag, "width"),
1607
+ .height = htmlImageDimension(tag, "height"),
1608
+ .consumed = cursor,
1609
+ };
1610
+ }
1611
+ const wrapper_allowed = switch (tag.kind) {
1612
+ .link, .small, .bold, .italic, .strike, .underline, .mark, .container => true,
1613
+ else => false,
1614
+ };
1615
+ if (!wrapper_allowed or tag.self_closing or wrapper_len >= wrappers.len) return null;
1616
+ if (tag.kind == .link) link = htmlAttribute(tag, "href") orelse "";
1617
+ wrappers[wrapper_len] = tag.name;
1618
+ wrapper_len += 1;
1619
+ cursor += tag.consumed;
1620
+ while (cursor < text.len and isInlineSpace(text[cursor])) cursor += 1;
1621
+ }
1622
+ return null;
1623
+ }
1624
+
1625
+ /// Decode the entity forms accepted by the renderer into caller-owned storage.
1626
+ /// Entity decoding never expands the input, but the explicit capacity check
1627
+ /// keeps the public source bound honest even for a pathological URL.
1628
+ fn decodeHtmlEntitiesInto(text: []const u8, output: []u8) ?[]const u8 {
1629
+ var source_index: usize = 0;
1630
+ var out_len: usize = 0;
1631
+ while (source_index < text.len) {
1632
+ if (text[source_index] == '&') {
1633
+ const rest = text[source_index..];
1634
+ const named: ?[]const u8 = if (std.mem.startsWith(u8, rest, "&amp;"))
1635
+ "&"
1636
+ else if (std.mem.startsWith(u8, rest, "&lt;"))
1637
+ "<"
1638
+ else if (std.mem.startsWith(u8, rest, "&gt;"))
1639
+ ">"
1640
+ else if (std.mem.startsWith(u8, rest, "&quot;"))
1641
+ "\""
1642
+ else if (std.mem.startsWith(u8, rest, "&apos;"))
1643
+ "'"
1644
+ else if (std.mem.startsWith(u8, rest, "&nbsp;"))
1645
+ "\u{a0}"
1646
+ else
1647
+ null;
1648
+ if (named) |decoded| {
1649
+ if (out_len + decoded.len > output.len) return null;
1650
+ @memcpy(output[out_len..][0..decoded.len], decoded);
1651
+ out_len += decoded.len;
1652
+ source_index += if (std.mem.startsWith(u8, rest, "&amp;"))
1653
+ 5
1654
+ else if (std.mem.startsWith(u8, rest, "&lt;") or std.mem.startsWith(u8, rest, "&gt;"))
1655
+ 4
1656
+ else
1657
+ 6;
1658
+ continue;
1659
+ }
1660
+
1661
+ if (std.mem.startsWith(u8, rest, "&#")) {
1662
+ const semi = std.mem.indexOfScalar(u8, rest[2..@min(rest.len, 14)], ';');
1663
+ if (semi) |relative_semi| {
1664
+ const body_end = relative_semi + 2;
1665
+ var digits = rest[2..body_end];
1666
+ var radix: u8 = 10;
1667
+ if (digits.len > 1 and (digits[0] == 'x' or digits[0] == 'X')) {
1668
+ radix = 16;
1669
+ digits = digits[1..];
1670
+ }
1671
+ if (digits.len > 0) {
1672
+ if (std.fmt.parseUnsigned(u21, digits, radix)) |codepoint| {
1673
+ if (codepoint != 0 and codepoint <= 0x10ffff and
1674
+ !(codepoint >= 0xd800 and codepoint <= 0xdfff))
1675
+ {
1676
+ var encoded_storage: [4]u8 = undefined;
1677
+ const encoded = std.unicode.utf8Encode(codepoint, &encoded_storage) catch 0;
1678
+ if (encoded > 0) {
1679
+ if (out_len + encoded > output.len) return null;
1680
+ @memcpy(output[out_len..][0..encoded], encoded_storage[0..encoded]);
1681
+ out_len += encoded;
1682
+ source_index += body_end + 1;
1683
+ continue;
1684
+ }
1685
+ }
1686
+ } else |_| {}
1687
+ }
1688
+ }
1689
+ }
1690
+ }
1691
+
1692
+ if (out_len >= output.len) return null;
1693
+ output[out_len] = text[source_index];
1694
+ out_len += 1;
1695
+ source_index += 1;
1696
+ }
1697
+ return output[0..out_len];
1698
+ }
1699
+
1700
+ fn htmlImageDimension(tag: HtmlTag, name: []const u8) ?f32 {
1701
+ const raw = htmlAttribute(tag, name) orelse return null;
1702
+ const value = std.fmt.parseFloat(f32, std.mem.trim(u8, raw, " \t")) catch return null;
1703
+ return if (validImageDimension(value)) value else null;
1704
+ }
1705
+
1706
+ fn validImageDimension(value: f32) bool {
1707
+ return std.math.isFinite(value) and value > 0;
1708
+ }
1709
+
1710
+ fn resolvedInlineImageDimensions(mapping: ResolvedImage, requested_width: ?f32, requested_height: ?f32) InlineImageDimensions {
1711
+ var width = requested_width orelse mapping.width;
1712
+ var height = requested_height orelse mapping.height;
1713
+ if (requested_width != null and requested_height == null) {
1714
+ height = width * mapping.height / mapping.width;
1715
+ } else if (requested_width == null and requested_height != null) {
1716
+ width = height * mapping.width / mapping.height;
1717
+ }
1718
+ // Inline source dimensions are presentation hints, not permission for an
1719
+ // untrusted document to manufacture unbounded layout extents. Scale both
1720
+ // axes together so either natural or author-requested proportions survive
1721
+ // the cap instead of turning a wide banner into a squashed rectangle.
1722
+ const scale = @min(@as(f32, 1), @min(512 / width, 512 / height));
1723
+ return .{ .width = width * scale, .height = height * scale };
1724
+ }
1725
+
1726
+ fn imageMainAlignment(alignment: canvas.TextAlign) canvas.WidgetMainAlignment {
1727
+ return switch (alignment) {
1728
+ .start => .start,
1729
+ .center => .center,
1730
+ .end => .end,
1731
+ };
1732
+ }
1733
+
1734
+ // ------------------------------------------------------------- safe HTML
1735
+
1736
+ /// The HTML vocabulary is deliberately presentational. Every accepted tag
1737
+ /// has a native text/widget lowering; everything else stays visible as
1738
+ /// literal source, so accepting Markdown never creates a DOM or an execution
1739
+ /// surface.
1740
+ const HtmlTagKind = enum {
1741
+ bold,
1742
+ italic,
1743
+ strike,
1744
+ underline,
1745
+ monospace,
1746
+ mark,
1747
+ small,
1748
+ link,
1749
+ image,
1750
+ line_break,
1751
+ word_break,
1752
+ quote,
1753
+ heading,
1754
+ horizontal_rule,
1755
+ paragraph,
1756
+ blockquote,
1757
+ preformatted,
1758
+ list,
1759
+ list_item,
1760
+ table,
1761
+ table_section,
1762
+ table_row,
1763
+ table_cell,
1764
+ container,
1765
+ };
1766
+
1767
+ const HtmlListKind = enum {
1768
+ unordered,
1769
+ ordered,
1770
+ definition,
1771
+ };
1772
+
1773
+ const HtmlTag = struct {
1774
+ kind: HtmlTagKind,
1775
+ name: []const u8,
1776
+ attributes: []const u8,
1777
+ closing: bool = false,
1778
+ self_closing: bool = false,
1779
+ heading_level: usize = 0,
1780
+ consumed: usize,
1781
+ };
1782
+
1783
+ const HtmlTagSyntax = struct {
1784
+ name: []const u8,
1785
+ attributes: []const u8,
1786
+ closing: bool = false,
1787
+ self_closing: bool = false,
1788
+ consumed: usize,
1789
+ };
1790
+
1791
+ const HtmlTagMatch = struct {
1792
+ start: usize,
1793
+ end: usize,
1794
+ tag: HtmlTag,
1795
+ };
1796
+
1797
+ /// State for source regions whose contents must remain opaque to tag matching.
1798
+ /// The unsupported-element name aliases the Markdown source, which outlives
1799
+ /// the streaming parse; comment state persists across source lines.
1800
+ const HtmlOpaqueState = struct {
1801
+ name: []const u8 = "",
1802
+ depth: usize = 0,
1803
+ comment: bool = false,
1804
+
1805
+ fn active(self: HtmlOpaqueState) bool {
1806
+ return self.depth > 0 or self.comment;
1807
+ }
1808
+
1809
+ fn elementActive(self: HtmlOpaqueState) bool {
1810
+ return self.depth > 0;
1811
+ }
1812
+ };
1813
+
1814
+ /// The source collector has no widget tree to consult, so it carries the
1815
+ /// subset of HTML state that makes image effects inert. Unsupported elements
1816
+ /// and comments reuse the renderer's opaque model; HTML code/pre tags have a
1817
+ /// small exact-name stack because their contents render as text, never images.
1818
+ const ImageDiscoveryHtmlState = struct {
1819
+ opaque_html: HtmlOpaqueState = .{},
1820
+ code_stack: [8][]const u8 = undefined,
1821
+ code_depth: usize = 0,
1822
+ code_overflow_depth: usize = 0,
1823
+
1824
+ fn active(self: ImageDiscoveryHtmlState) bool {
1825
+ return self.opaque_html.active() or self.code_depth > 0 or self.code_overflow_depth > 0;
1826
+ }
1827
+ };
1828
+
1829
+ fn isDetailsHtmlTagName(name: []const u8) bool {
1830
+ return std.ascii.eqlIgnoreCase(name, "details") or std.ascii.eqlIgnoreCase(name, "summary");
1831
+ }
1832
+
1833
+ fn startsStandaloneInertHtmlBlock(trimmed: []const u8) bool {
1834
+ if (std.mem.startsWith(u8, trimmed, "<!--")) return true;
1835
+ const tag = parseHtmlTagAt(trimmed, 0) orelse return false;
1836
+ return !tag.closing and tag.kind == .preformatted;
1837
+ }
1838
+
1839
+ /// Return the prefix of one physical line that is eligible for image-source
1840
+ /// discovery, while advancing multiline comment/unsupported/code state. Once
1841
+ /// an inert region begins, the rest of that line is conservatively excluded;
1842
+ /// a leading image before a trailing comment remains eligible.
1843
+ fn imageDiscoveryVisiblePrefix(line: []const u8, state: *ImageDiscoveryHtmlState) []const u8 {
1844
+ const started_inert = state.active();
1845
+ var first_inert: ?usize = if (started_inert) 0 else null;
1846
+ var cursor: usize = 0;
1847
+
1848
+ while (cursor < line.len) {
1849
+ if (state.opaque_html.comment) {
1850
+ if (first_inert == null) first_inert = cursor;
1851
+ const close = std.mem.indexOfPos(u8, line, cursor, "-->") orelse return line[0 .. first_inert orelse 0];
1852
+ state.opaque_html.comment = false;
1853
+ cursor = close + 3;
1854
+ continue;
1855
+ }
1856
+
1857
+ const start = std.mem.indexOfScalarPos(u8, line, cursor, '<') orelse break;
1858
+ if (std.mem.startsWith(u8, line[start..], "<!--")) {
1859
+ if (first_inert == null) first_inert = start;
1860
+ const close = std.mem.indexOfPos(u8, line, start + 4, "-->") orelse {
1861
+ state.opaque_html.comment = true;
1862
+ break;
1863
+ };
1864
+ cursor = close + 3;
1865
+ continue;
1866
+ }
1867
+
1868
+ const syntax = parseHtmlTagSyntaxAt(line, start) orelse {
1869
+ cursor = start + 1;
1870
+ continue;
1871
+ };
1872
+ cursor = start + syntax.consumed;
1873
+
1874
+ if (state.opaque_html.elementActive()) {
1875
+ if (first_inert == null) first_inert = start;
1876
+ if (!std.ascii.eqlIgnoreCase(syntax.name, state.opaque_html.name)) continue;
1877
+ if (syntax.closing) {
1878
+ state.opaque_html.depth -= 1;
1879
+ if (!state.opaque_html.elementActive()) state.opaque_html.name = "";
1880
+ } else if (!syntax.self_closing) {
1881
+ state.opaque_html.depth += 1;
1882
+ }
1883
+ continue;
1884
+ }
1885
+
1886
+ const classified = classifyHtmlTag(syntax.name);
1887
+ if (classified == null and !isDetailsHtmlTagName(syntax.name)) {
1888
+ if (first_inert == null) first_inert = start;
1889
+ if (!syntax.closing and !syntax.self_closing and !isHtmlVoidTagName(syntax.name)) {
1890
+ state.opaque_html = .{ .name = syntax.name, .depth = 1 };
1891
+ }
1892
+ continue;
1893
+ }
1894
+
1895
+ const code_like = if (classified) |tag|
1896
+ tag.kind == .monospace or tag.kind == .preformatted
1897
+ else
1898
+ false;
1899
+ if (!code_like) continue;
1900
+ if (first_inert == null) first_inert = start;
1901
+ if (syntax.self_closing) continue;
1902
+ if (syntax.closing) {
1903
+ if (state.code_overflow_depth > 0) {
1904
+ state.code_overflow_depth -= 1;
1905
+ } else if (state.code_depth > 0 and
1906
+ std.ascii.eqlIgnoreCase(state.code_stack[state.code_depth - 1], syntax.name))
1907
+ {
1908
+ state.code_depth -= 1;
1909
+ }
1910
+ } else if (state.code_depth < state.code_stack.len) {
1911
+ state.code_stack[state.code_depth] = syntax.name;
1912
+ state.code_depth += 1;
1913
+ } else {
1914
+ state.code_overflow_depth += 1;
1915
+ }
1916
+ }
1917
+ return line[0 .. first_inert orelse line.len];
1918
+ }
1919
+
1920
+ fn collectTableImageSources(
1921
+ lines: *LineIterator,
1922
+ header_line: []const u8,
1923
+ output: []CollectedImageSource,
1924
+ len: *usize,
1925
+ html_state: *ImageDiscoveryHtmlState,
1926
+ ) bool {
1927
+ const header = splitTableRow(header_line) orelse return false;
1928
+ const delimiter_line = lines.peek() orelse return false;
1929
+ const alignments = tableDelimiterAlignments(delimiter_line) orelse return false;
1930
+ if (alignments.len != header.len) return false;
1931
+
1932
+ for (header.cells) |cell| appendLeadingImageSource(output, len, cell);
1933
+ _ = lines.next(); // delimiter
1934
+ while (lines.peek()) |line| {
1935
+ const trimmed = std.mem.trim(u8, line, " \t");
1936
+ if (trimmed.len == 0 or std.mem.indexOfScalar(u8, trimmed, '|') == null) break;
1937
+ _ = lines.next();
1938
+ const visible = imageDiscoveryVisiblePrefix(line, html_state);
1939
+ if (splitTableRow(visible)) |row| {
1940
+ for (row.cells) |cell| appendLeadingImageSource(output, len, cell);
1941
+ }
1942
+ if (len.* >= output.len) break;
1943
+ }
1944
+ return true;
1945
+ }
1946
+
1947
+ /// Consume the block-shaped syntax that can expose a new leading-inline
1948
+ /// position on the same line. Multiline bodies are handled by the caller's
1949
+ /// paragraph state on subsequent lines.
1950
+ fn collectHtmlBlockImageSource(
1951
+ trimmed: []const u8,
1952
+ output: []CollectedImageSource,
1953
+ len: *usize,
1954
+ paragraph_open: *bool,
1955
+ ) bool {
1956
+ if (std.ascii.startsWithIgnoreCase(trimmed, "<summary>")) {
1957
+ var content = trimmed["<summary>".len..];
1958
+ if (std.ascii.indexOfIgnoreCase(content, "</summary>")) |close| content = content[0..close];
1959
+ appendLeadingImageSource(output, len, std.mem.trim(u8, content, " \t"));
1960
+ paragraph_open.* = false;
1961
+ return true;
1962
+ }
1963
+ if (parseHtmlTagSyntaxAt(trimmed, 0)) |syntax| {
1964
+ if (isDetailsHtmlTagName(syntax.name)) {
1965
+ paragraph_open.* = false;
1966
+ return true;
1967
+ }
1968
+ }
1969
+
1970
+ const opening = parseHtmlTagAt(trimmed, 0) orelse return false;
1971
+ if (!isHtmlBlockTag(opening)) return false;
1972
+ if (opening.kind == .horizontal_rule or opening.self_closing) {
1973
+ paragraph_open.* = false;
1974
+ return true;
1975
+ }
1976
+ if (opening.closing) {
1977
+ const suffix = std.mem.trimStart(u8, trimmed[opening.consumed..], " \t");
1978
+ if (suffix.len > 0) appendLeadingImageSource(output, len, suffix);
1979
+ paragraph_open.* = suffix.len > 0;
1980
+ return true;
1981
+ }
1982
+ if (singleLineHtmlElement(trimmed, opening)) |element| {
1983
+ appendLeadingImageSource(output, len, std.mem.trim(u8, element.content, " \t"));
1984
+ paragraph_open.* = false;
1985
+ return true;
1986
+ }
1987
+
1988
+ const suffix = std.mem.trimStart(u8, trimmed[opening.consumed..], " \t");
1989
+ if (suffix.len > 0) appendLeadingImageSource(output, len, suffix);
1990
+ paragraph_open.* = suffix.len > 0;
1991
+ return true;
1992
+ }
1993
+
1994
+ /// Return the next allowlisted tag while treating unsupported elements as
1995
+ /// opaque regions, carrying multiline-comment state across block scans, and
1996
+ /// skipping complete Markdown code spans so literal `</tag>` text cannot close
1997
+ /// a structural wrapper.
1998
+ fn nextHtmlTagMatch(
1999
+ source: []const u8,
2000
+ cursor: *usize,
2001
+ opaque_html: *HtmlOpaqueState,
2002
+ scan_cache: *ScanCache,
2003
+ ) ?HtmlTagMatch {
2004
+ while (cursor.* < source.len) {
2005
+ if (opaque_html.comment) {
2006
+ const close = std.mem.indexOfPos(u8, source, cursor.*, "-->") orelse {
2007
+ cursor.* = source.len;
2008
+ return null;
2009
+ };
2010
+ opaque_html.comment = false;
2011
+ cursor.* = close + 3;
2012
+ continue;
2013
+ }
2014
+
2015
+ const start = std.mem.indexOfScalarPos(u8, source, cursor.*, '<') orelse return null;
2016
+ if (!opaque_html.elementActive()) {
2017
+ if (ScanCache.nextScalar(&scan_cache.html_code_tick, source, cursor.*, '`')) |code_open| {
2018
+ if (code_open < start) {
2019
+ if (ScanCache.nextScalar(&scan_cache.html_code_tick, source, code_open + 1, '`')) |code_close| {
2020
+ cursor.* = code_close + 1;
2021
+ } else {
2022
+ // An unpaired backtick is literal in the inline grammar;
2023
+ // advance past it and keep looking for real HTML.
2024
+ cursor.* = code_open + 1;
2025
+ }
2026
+ continue;
2027
+ }
2028
+ }
2029
+ }
2030
+
2031
+ if (std.mem.startsWith(u8, source[start..], "<!--")) {
2032
+ const close = std.mem.indexOfPos(u8, source, start + 4, "-->") orelse {
2033
+ opaque_html.comment = true;
2034
+ cursor.* = source.len;
2035
+ return null;
2036
+ };
2037
+ cursor.* = close + 3;
2038
+ continue;
2039
+ }
2040
+ const syntax = parseHtmlTagSyntaxAt(source, start) orelse {
2041
+ cursor.* = start + 1;
2042
+ continue;
2043
+ };
2044
+ cursor.* = start + syntax.consumed;
2045
+
2046
+ if (opaque_html.elementActive()) {
2047
+ if (!std.ascii.eqlIgnoreCase(syntax.name, opaque_html.name)) continue;
2048
+ if (syntax.closing) {
2049
+ opaque_html.depth -= 1;
2050
+ if (!opaque_html.elementActive()) opaque_html.name = "";
2051
+ } else if (!syntax.self_closing) {
2052
+ opaque_html.depth += 1;
2053
+ }
2054
+ continue;
2055
+ }
2056
+
2057
+ if (classifyHtmlTag(syntax.name)) |classified| {
2058
+ const tag = HtmlTag{
2059
+ .kind = classified.kind,
2060
+ .name = syntax.name,
2061
+ .attributes = syntax.attributes,
2062
+ .closing = syntax.closing,
2063
+ .self_closing = syntax.self_closing,
2064
+ .heading_level = classified.heading_level,
2065
+ .consumed = syntax.consumed,
2066
+ };
2067
+ return .{ .start = start, .end = cursor.*, .tag = tag };
2068
+ }
2069
+
2070
+ if (!syntax.closing and !syntax.self_closing and !isHtmlVoidTagName(syntax.name)) {
2071
+ opaque_html.* = .{ .name = syntax.name, .depth = 1 };
2072
+ }
2073
+ }
2074
+ return null;
2075
+ }
2076
+
2077
+ fn updateHtmlOpaqueState(source: []const u8, opaque_html: *HtmlOpaqueState) void {
2078
+ var cursor: usize = 0;
2079
+ var scan_cache = ScanCache{};
2080
+ while (nextHtmlTagMatch(source, &cursor, opaque_html, &scan_cache)) |_| {}
2081
+ }
2082
+
2083
+ fn htmlTagRequiresClosing(tag: HtmlTag) bool {
2084
+ return switch (tag.kind) {
2085
+ .image, .line_break, .word_break, .horizontal_rule => false,
2086
+ else => true,
2087
+ };
2088
+ }
2089
+
2090
+ fn hasMatchingHtmlClosingTag(source: []const u8, from: usize, name: []const u8) bool {
2091
+ var cursor = from;
2092
+ var nested: usize = 0;
2093
+ var opaque_html = HtmlOpaqueState{};
2094
+ var scan_cache = ScanCache{};
2095
+ while (nextHtmlTagMatch(source, &cursor, &opaque_html, &scan_cache)) |match| {
2096
+ if (!std.ascii.eqlIgnoreCase(match.tag.name, name)) continue;
2097
+ if (!match.tag.closing) {
2098
+ if (!match.tag.self_closing) nested += 1;
2099
+ continue;
2100
+ }
2101
+ if (nested == 0) return true;
2102
+ nested -= 1;
2103
+ }
2104
+ return false;
2105
+ }
2106
+
2107
+ /// Find a closer for an already-open block scope, ignoring matching tags
2108
+ /// opened and closed wholly within this line.
2109
+ fn findUnbalancedHtmlClosingTag(source: []const u8, name: []const u8) ?HtmlTagMatch {
2110
+ var cursor: usize = 0;
2111
+ var nested: usize = 0;
2112
+ var opaque_html = HtmlOpaqueState{};
2113
+ var scan_cache = ScanCache{};
2114
+ while (nextHtmlTagMatch(source, &cursor, &opaque_html, &scan_cache)) |match| {
2115
+ if (!std.ascii.eqlIgnoreCase(match.tag.name, name)) continue;
2116
+ if (!match.tag.closing) {
2117
+ if (!match.tag.self_closing) nested += 1;
2118
+ continue;
2119
+ }
2120
+ if (nested == 0) return match;
2121
+ nested -= 1;
2122
+ }
2123
+ return null;
2124
+ }
2125
+
2126
+ fn findUnbalancedHtmlScopeClosingTag(source: []const u8) ?HtmlTagMatch {
2127
+ var cursor: usize = 0;
2128
+ var nested: usize = 0;
2129
+ var opaque_html = HtmlOpaqueState{};
2130
+ var scan_cache = ScanCache{};
2131
+ while (nextHtmlTagMatch(source, &cursor, &opaque_html, &scan_cache)) |match| {
2132
+ if (!isHtmlBlockScopeTag(match.tag)) continue;
2133
+ if (!match.tag.closing) {
2134
+ if (!match.tag.self_closing) nested += 1;
2135
+ continue;
2136
+ }
2137
+ if (nested == 0) return match;
2138
+ nested -= 1;
2139
+ }
2140
+ return null;
2141
+ }
2142
+
2143
+ const HtmlElementLineScan = struct {
2144
+ content_end: usize,
2145
+ closing_end: ?usize = null,
2146
+ };
2147
+
2148
+ fn scanHtmlElementLine(
2149
+ line: []const u8,
2150
+ name: []const u8,
2151
+ depth: *usize,
2152
+ opaque_html: *HtmlOpaqueState,
2153
+ ) HtmlElementLineScan {
2154
+ var cursor: usize = 0;
2155
+ var scan_cache = ScanCache{};
2156
+ while (nextHtmlTagMatch(line, &cursor, opaque_html, &scan_cache)) |match| {
2157
+ if (!std.ascii.eqlIgnoreCase(match.tag.name, name)) continue;
2158
+ if (!match.tag.closing) {
2159
+ if (!match.tag.self_closing) depth.* += 1;
2160
+ continue;
2161
+ }
2162
+ if (depth.* > 0) depth.* -= 1;
2163
+ if (depth.* == 0) return .{ .content_end = match.start, .closing_end = match.end };
2164
+ }
2165
+ return .{ .content_end = line.len };
2166
+ }
2167
+
2168
+ const HtmlComment = struct { consumed: usize };
2169
+ const DecodedHtmlEntity = struct { text: []const u8, consumed: usize };
2170
+
2171
+ const SingleLineHtmlElement = struct { content: []const u8 };
2172
+
2173
+ /// Parse one allowlisted tag at `source[index]`. The scan rejects another
2174
+ /// `<` outside a quoted attribute and caps a tag at 1 KiB, keeping a hostile
2175
+ /// wall of plausible openers linear and capacity-bounded.
2176
+ fn parseHtmlTagAt(source: []const u8, index: usize) ?HtmlTag {
2177
+ const syntax = parseHtmlTagSyntaxAt(source, index) orelse return null;
2178
+ const classified = classifyHtmlTag(syntax.name) orelse return null;
2179
+ return .{
2180
+ .kind = classified.kind,
2181
+ .name = syntax.name,
2182
+ .attributes = syntax.attributes,
2183
+ .closing = syntax.closing,
2184
+ .self_closing = syntax.self_closing,
2185
+ .heading_level = classified.heading_level,
2186
+ .consumed = syntax.consumed,
2187
+ };
2188
+ }
2189
+
2190
+ /// Parse one syntactically valid tag regardless of whether its name is in
2191
+ /// the safe presentation vocabulary. Unsupported elements use this shape to
2192
+ /// remain opaque literal source through their matching closer.
2193
+ fn parseHtmlTagSyntaxAt(source: []const u8, index: usize) ?HtmlTagSyntax {
2194
+ if (index >= source.len or source[index] != '<') return null;
2195
+ var cursor = index + 1;
2196
+ var closing = false;
2197
+ if (cursor < source.len and source[cursor] == '/') {
2198
+ closing = true;
2199
+ cursor += 1;
2200
+ }
2201
+ if (cursor >= source.len or !std.ascii.isAlphabetic(source[cursor])) return null;
2202
+
2203
+ const name_start = cursor;
2204
+ while (cursor < source.len and (std.ascii.isAlphanumeric(source[cursor]) or source[cursor] == '-')) cursor += 1;
2205
+ const name = source[name_start..cursor];
2206
+ if (cursor < source.len and source[cursor] != '>' and source[cursor] != '/' and !std.ascii.isWhitespace(source[cursor])) return null;
2207
+
2208
+ const attributes_start = cursor;
2209
+ const limit = @min(source.len, index + 1024);
2210
+ var quote: ?u8 = null;
2211
+ while (cursor < limit) : (cursor += 1) {
2212
+ const byte = source[cursor];
2213
+ if (quote) |delimiter| {
2214
+ if (byte == delimiter) quote = null;
2215
+ continue;
2216
+ }
2217
+ if (byte == '"' or byte == '\'') {
2218
+ quote = byte;
2219
+ continue;
2220
+ }
2221
+ if (byte == '<') return null;
2222
+ if (byte != '>') continue;
2223
+
2224
+ const attributes = source[attributes_start..cursor];
2225
+ const trimmed_attributes = std.mem.trim(u8, attributes, " \t\r\n");
2226
+ return .{
2227
+ .name = name,
2228
+ .attributes = attributes,
2229
+ .closing = closing,
2230
+ .self_closing = !closing and trimmed_attributes.len > 0 and trimmed_attributes[trimmed_attributes.len - 1] == '/',
2231
+ .consumed = cursor + 1 - index,
2232
+ };
2233
+ }
2234
+ return null;
2235
+ }
2236
+
2237
+ const ClassifiedHtmlTag = struct {
2238
+ kind: HtmlTagKind,
2239
+ heading_level: usize = 0,
2240
+ };
2241
+
2242
+ fn classifyHtmlTag(name: []const u8) ?ClassifiedHtmlTag {
2243
+ if (std.ascii.eqlIgnoreCase(name, "b") or std.ascii.eqlIgnoreCase(name, "strong")) return .{ .kind = .bold };
2244
+ if (std.ascii.eqlIgnoreCase(name, "i") or std.ascii.eqlIgnoreCase(name, "em") or
2245
+ std.ascii.eqlIgnoreCase(name, "var") or std.ascii.eqlIgnoreCase(name, "cite")) return .{ .kind = .italic };
2246
+ if (std.ascii.eqlIgnoreCase(name, "s") or std.ascii.eqlIgnoreCase(name, "strike") or std.ascii.eqlIgnoreCase(name, "del")) return .{ .kind = .strike };
2247
+ if (std.ascii.eqlIgnoreCase(name, "u") or std.ascii.eqlIgnoreCase(name, "ins")) return .{ .kind = .underline };
2248
+ if (std.ascii.eqlIgnoreCase(name, "code") or std.ascii.eqlIgnoreCase(name, "kbd") or
2249
+ std.ascii.eqlIgnoreCase(name, "samp") or std.ascii.eqlIgnoreCase(name, "tt")) return .{ .kind = .monospace };
2250
+ if (std.ascii.eqlIgnoreCase(name, "mark")) return .{ .kind = .mark };
2251
+ if (std.ascii.eqlIgnoreCase(name, "small") or std.ascii.eqlIgnoreCase(name, "sub") or std.ascii.eqlIgnoreCase(name, "sup")) return .{ .kind = .small };
2252
+ if (std.ascii.eqlIgnoreCase(name, "a")) return .{ .kind = .link };
2253
+ if (std.ascii.eqlIgnoreCase(name, "img")) return .{ .kind = .image };
2254
+ if (std.ascii.eqlIgnoreCase(name, "br")) return .{ .kind = .line_break };
2255
+ if (std.ascii.eqlIgnoreCase(name, "wbr")) return .{ .kind = .word_break };
2256
+ if (std.ascii.eqlIgnoreCase(name, "q")) return .{ .kind = .quote };
2257
+ if (name.len == 2 and (name[0] == 'h' or name[0] == 'H') and name[1] >= '1' and name[1] <= '6') {
2258
+ return .{ .kind = .heading, .heading_level = name[1] - '0' };
2259
+ }
2260
+ if (std.ascii.eqlIgnoreCase(name, "hr")) return .{ .kind = .horizontal_rule };
2261
+ if (std.ascii.eqlIgnoreCase(name, "p")) return .{ .kind = .paragraph };
2262
+ if (std.ascii.eqlIgnoreCase(name, "blockquote")) return .{ .kind = .blockquote };
2263
+ if (std.ascii.eqlIgnoreCase(name, "pre")) return .{ .kind = .preformatted };
2264
+ if (std.ascii.eqlIgnoreCase(name, "ol") or std.ascii.eqlIgnoreCase(name, "ul") or std.ascii.eqlIgnoreCase(name, "dl")) return .{ .kind = .list };
2265
+ if (std.ascii.eqlIgnoreCase(name, "li") or std.ascii.eqlIgnoreCase(name, "dt") or std.ascii.eqlIgnoreCase(name, "dd")) return .{ .kind = .list_item };
2266
+ if (std.ascii.eqlIgnoreCase(name, "table")) return .{ .kind = .table };
2267
+ if (std.ascii.eqlIgnoreCase(name, "thead") or std.ascii.eqlIgnoreCase(name, "tbody") or std.ascii.eqlIgnoreCase(name, "tfoot")) return .{ .kind = .table_section };
2268
+ if (std.ascii.eqlIgnoreCase(name, "tr")) return .{ .kind = .table_row };
2269
+ if (std.ascii.eqlIgnoreCase(name, "td") or std.ascii.eqlIgnoreCase(name, "th")) return .{ .kind = .table_cell };
2270
+ if (std.ascii.eqlIgnoreCase(name, "abbr") or std.ascii.eqlIgnoreCase(name, "bdo") or
2271
+ std.ascii.eqlIgnoreCase(name, "caption") or std.ascii.eqlIgnoreCase(name, "center") or
2272
+ std.ascii.eqlIgnoreCase(name, "div") or std.ascii.eqlIgnoreCase(name, "span") or
2273
+ std.ascii.eqlIgnoreCase(name, "section") or std.ascii.eqlIgnoreCase(name, "article") or
2274
+ std.ascii.eqlIgnoreCase(name, "header") or std.ascii.eqlIgnoreCase(name, "footer") or
2275
+ std.ascii.eqlIgnoreCase(name, "main") or std.ascii.eqlIgnoreCase(name, "figure") or
2276
+ std.ascii.eqlIgnoreCase(name, "figcaption") or std.ascii.eqlIgnoreCase(name, "time") or
2277
+ std.ascii.eqlIgnoreCase(name, "ruby") or std.ascii.eqlIgnoreCase(name, "rt") or
2278
+ std.ascii.eqlIgnoreCase(name, "rp")) return .{ .kind = .container };
2279
+ return null;
2280
+ }
2281
+
2282
+ fn unsupportedHtmlElementEnd(source: []const u8, index: usize, opening: HtmlTagSyntax) usize {
2283
+ const opening_end = index + opening.consumed;
2284
+ if (opening.closing or opening.self_closing or isHtmlVoidTagName(opening.name)) return opening_end;
2285
+
2286
+ var cursor = opening_end;
2287
+ var depth: usize = 1;
2288
+ var scan_cache = ScanCache{};
2289
+ while (std.mem.indexOfScalarPos(u8, source, cursor, '<')) |start| {
2290
+ if (parseHtmlCommentAt(source, start, &scan_cache)) |comment| {
2291
+ cursor = start + comment.consumed;
2292
+ continue;
2293
+ }
2294
+ const tag = parseHtmlTagSyntaxAt(source, start) orelse {
2295
+ cursor = start + 1;
2296
+ continue;
2297
+ };
2298
+ cursor = start + tag.consumed;
2299
+ if (!std.ascii.eqlIgnoreCase(tag.name, opening.name)) continue;
2300
+ if (tag.closing) {
2301
+ depth -= 1;
2302
+ if (depth == 0) return cursor;
2303
+ } else if (!tag.self_closing) {
2304
+ depth += 1;
2305
+ }
2306
+ }
2307
+ return source.len;
2308
+ }
2309
+
2310
+ fn isHtmlVoidTagName(name: []const u8) bool {
2311
+ return std.ascii.eqlIgnoreCase(name, "area") or std.ascii.eqlIgnoreCase(name, "base") or
2312
+ std.ascii.eqlIgnoreCase(name, "col") or std.ascii.eqlIgnoreCase(name, "embed") or
2313
+ std.ascii.eqlIgnoreCase(name, "input") or std.ascii.eqlIgnoreCase(name, "link") or
2314
+ std.ascii.eqlIgnoreCase(name, "meta") or std.ascii.eqlIgnoreCase(name, "param") or
2315
+ std.ascii.eqlIgnoreCase(name, "source") or std.ascii.eqlIgnoreCase(name, "track");
2316
+ }
2317
+
2318
+ fn parseHtmlCommentAt(source: []const u8, index: usize, cache: ?*ScanCache) ?HtmlComment {
2319
+ if (index > source.len or !std.mem.startsWith(u8, source[index..], "<!--")) return null;
2320
+ const close = if (cache) |scan|
2321
+ ScanCache.nextPattern(&scan.html_comment_close, source, index + 4, "-->")
2322
+ else
2323
+ std.mem.indexOfPos(u8, source, index + 4, "-->");
2324
+ const close_index = close orelse return null;
2325
+ return .{ .consumed = close_index + 3 - index };
2326
+ }
2327
+
2328
+ fn singleLineHtmlElement(line: []const u8, opening: HtmlTag) ?SingleLineHtmlElement {
2329
+ if (opening.closing or opening.self_closing) return null;
2330
+ const close_start = std.mem.lastIndexOfScalar(u8, line, '<') orelse return null;
2331
+ if (close_start < opening.consumed) return null;
2332
+ const closing = parseHtmlTagAt(line, close_start) orelse return null;
2333
+ if (!closing.closing or closing.consumed != line.len - close_start or
2334
+ !std.ascii.eqlIgnoreCase(opening.name, closing.name)) return null;
2335
+ return .{ .content = line[opening.consumed..close_start] };
2336
+ }
2337
+
2338
+ fn unwrapHtmlCode(content: []const u8) []const u8 {
2339
+ const opening = parseHtmlTagAt(content, 0) orelse return content;
2340
+ if (opening.kind != .monospace or opening.closing) return content;
2341
+ const element = singleLineHtmlElement(content, opening) orelse return content;
2342
+ return element.content;
2343
+ }
2344
+
2345
+ fn consumeHtmlOpeningLine(lines: *LineIterator, trimmed: []const u8, opening: HtmlTag) void {
2346
+ _ = lines.next();
2347
+ const suffix = trimmed[opening.consumed..];
2348
+ if (suffix.len > 0) lines.prepend(suffix);
2349
+ }
2350
+
2351
+ /// Consume a comment beginning on the current line through its closing
2352
+ /// marker, including intervening blank lines. The iterator is unchanged when
2353
+ /// no closer exists so malformed comments still degrade to literal text.
2354
+ fn consumeHtmlCommentBlock(lines: *LineIterator) bool {
2355
+ var probe = lines.*;
2356
+ const first = probe.next() orelse return false;
2357
+ const opening = std.mem.indexOf(u8, first, "<!--") orelse return false;
2358
+ if (std.mem.indexOfPos(u8, first, opening + 4, "-->")) |close| {
2359
+ const suffix = first[close + 3 ..];
2360
+ if (suffix.len > 0) probe.prepend(suffix);
2361
+ lines.* = probe;
2362
+ return true;
2363
+ }
2364
+ while (probe.next()) |line| {
2365
+ const close = std.mem.indexOf(u8, line, "-->") orelse continue;
2366
+ const suffix = line[close + 3 ..];
2367
+ if (suffix.len > 0) probe.prepend(suffix);
2368
+ lines.* = probe;
2369
+ return true;
2370
+ }
2371
+ return false;
2372
+ }
2373
+
2374
+ fn skipHtmlElement(lines: *LineIterator, name: []const u8) void {
2375
+ var depth: usize = 1;
2376
+ var opaque_html = HtmlOpaqueState{};
2377
+ while (lines.next()) |line| {
2378
+ const scan = scanHtmlElementLine(line, name, &depth, &opaque_html);
2379
+ if (scan.closing_end) |closing_end| {
2380
+ const suffix = line[closing_end..];
2381
+ if (suffix.len > 0) lines.prepend(suffix);
2382
+ return;
2383
+ }
2384
+ }
2385
+ }
2386
+
2387
+ fn isHtmlBlockTag(tag: HtmlTag) bool {
2388
+ return switch (tag.kind) {
2389
+ .heading, .horizontal_rule, .paragraph, .blockquote, .preformatted, .list, .list_item, .table, .table_section, .table_row, .table_cell => true,
2390
+ .container => isHtmlStructuralTag(tag),
2391
+ else => false,
2392
+ };
2393
+ }
2394
+
2395
+ fn isHtmlStructuralTag(tag: HtmlTag) bool {
2396
+ if (tag.kind != .container) return isHtmlBlockTagWithoutContainer(tag.kind);
2397
+ return std.ascii.eqlIgnoreCase(tag.name, "center") or std.ascii.eqlIgnoreCase(tag.name, "div") or
2398
+ std.ascii.eqlIgnoreCase(tag.name, "section") or std.ascii.eqlIgnoreCase(tag.name, "article") or
2399
+ std.ascii.eqlIgnoreCase(tag.name, "header") or std.ascii.eqlIgnoreCase(tag.name, "footer") or
2400
+ std.ascii.eqlIgnoreCase(tag.name, "main") or std.ascii.eqlIgnoreCase(tag.name, "figure") or
2401
+ std.ascii.eqlIgnoreCase(tag.name, "figcaption") or std.ascii.eqlIgnoreCase(tag.name, "caption");
2402
+ }
2403
+
2404
+ fn isHtmlBlockTagWithoutContainer(kind: HtmlTagKind) bool {
2405
+ return switch (kind) {
2406
+ .heading, .horizontal_rule, .paragraph, .blockquote, .preformatted, .list, .list_item, .table, .table_section, .table_row, .table_cell => true,
2407
+ else => false,
2408
+ };
2409
+ }
2410
+
2411
+ fn isHtmlBlockScopeTag(tag: HtmlTag) bool {
2412
+ // Complete elements (headings, paragraphs, blockquotes, pre, and list
2413
+ // items) are consumed by their dedicated collectors before reaching the
2414
+ // streaming scope path. Every remaining structural wrapper needs an exact
2415
+ // opener/closer entry so stray closing tags can stay literal.
2416
+ return isHtmlStructuralTag(tag);
2417
+ }
2418
+
2419
+ fn htmlListKind(tag: HtmlTag) ?HtmlListKind {
2420
+ if (tag.kind != .list) return null;
2421
+ if (std.ascii.eqlIgnoreCase(tag.name, "ol")) return .ordered;
2422
+ if (std.ascii.eqlIgnoreCase(tag.name, "dl")) return .definition;
2423
+ return .unordered;
2424
+ }
2425
+
2426
+ fn htmlTagAlignment(tag: HtmlTag) ?canvas.TextAlign {
2427
+ if (std.ascii.eqlIgnoreCase(tag.name, "center")) return .center;
2428
+ const value = htmlAttribute(tag, "align") orelse return null;
2429
+ if (std.ascii.eqlIgnoreCase(value, "center")) return .center;
2430
+ if (std.ascii.eqlIgnoreCase(value, "right") or std.ascii.eqlIgnoreCase(value, "end")) return .end;
2431
+ if (std.ascii.eqlIgnoreCase(value, "left") or std.ascii.eqlIgnoreCase(value, "start")) return .start;
2432
+ return null;
2433
+ }
2434
+
2435
+ /// Return one attribute value without exposing any other attribute to the
2436
+ /// widget engine. Quoted and unquoted values are accepted case-insensitively,
2437
+ /// matching the forms commonly found in README HTML.
2438
+ fn htmlAttribute(tag: HtmlTag, wanted: []const u8) ?[]const u8 {
2439
+ var cursor: usize = 0;
2440
+ while (cursor < tag.attributes.len) {
2441
+ while (cursor < tag.attributes.len and std.ascii.isWhitespace(tag.attributes[cursor])) cursor += 1;
2442
+ if (cursor >= tag.attributes.len or tag.attributes[cursor] == '/') break;
2443
+ const name_start = cursor;
2444
+ while (cursor < tag.attributes.len and (std.ascii.isAlphanumeric(tag.attributes[cursor]) or
2445
+ tag.attributes[cursor] == '-' or tag.attributes[cursor] == '_' or tag.attributes[cursor] == ':')) cursor += 1;
2446
+ if (cursor == name_start) {
2447
+ cursor += 1;
2448
+ continue;
2449
+ }
2450
+ const name = tag.attributes[name_start..cursor];
2451
+ while (cursor < tag.attributes.len and std.ascii.isWhitespace(tag.attributes[cursor])) cursor += 1;
2452
+ if (cursor >= tag.attributes.len or tag.attributes[cursor] != '=') continue;
2453
+ cursor += 1;
2454
+ while (cursor < tag.attributes.len and std.ascii.isWhitespace(tag.attributes[cursor])) cursor += 1;
2455
+ if (cursor >= tag.attributes.len) return null;
2456
+
2457
+ var value: []const u8 = undefined;
2458
+ if (tag.attributes[cursor] == '"' or tag.attributes[cursor] == '\'') {
2459
+ const quote = tag.attributes[cursor];
2460
+ cursor += 1;
2461
+ const value_start = cursor;
2462
+ while (cursor < tag.attributes.len and tag.attributes[cursor] != quote) cursor += 1;
2463
+ if (cursor >= tag.attributes.len) return null;
2464
+ value = tag.attributes[value_start..cursor];
2465
+ cursor += 1;
2466
+ } else {
2467
+ const value_start = cursor;
2468
+ while (cursor < tag.attributes.len and !std.ascii.isWhitespace(tag.attributes[cursor])) cursor += 1;
2469
+ value = tag.attributes[value_start..cursor];
2470
+ }
2471
+ if (std.ascii.eqlIgnoreCase(name, wanted)) return value;
2472
+ }
2473
+ return null;
2474
+ }
2475
+
2476
+ fn updateHtmlDepth(depth: *usize, closing: bool, active: bool) void {
2477
+ if (closing) {
2478
+ if (depth.* > 0) depth.* -= 1;
2479
+ } else if (active and depth.* < std.math.maxInt(usize)) {
2480
+ depth.* += 1;
2481
+ }
2482
+ }
2483
+
661
2484
  // ------------------------------------------------------------ line model
662
2485
 
663
2486
  const LineIterator = struct {
664
2487
  source: []const u8,
665
2488
  index: usize = 0,
2489
+ pending: ?[]const u8 = null,
666
2490
 
667
2491
  fn next(self: *LineIterator) ?[]const u8 {
2492
+ if (self.pending) |line| {
2493
+ self.pending = null;
2494
+ return line;
2495
+ }
668
2496
  if (self.index >= self.source.len) return null;
669
2497
  const start = self.index;
670
2498
  const end = std.mem.indexOfScalarPos(u8, self.source, start, '\n') orelse self.source.len;
@@ -672,6 +2500,11 @@ const LineIterator = struct {
672
2500
  return std.mem.trimEnd(u8, self.source[start..end], "\r");
673
2501
  }
674
2502
 
2503
+ fn prepend(self: *LineIterator, line: []const u8) void {
2504
+ std.debug.assert(self.pending == null);
2505
+ self.pending = line;
2506
+ }
2507
+
675
2508
  fn peek(self: *LineIterator) ?[]const u8 {
676
2509
  var copy = self.*;
677
2510
  return copy.next();
@@ -839,6 +2672,120 @@ fn listMarker(line: []const u8) ?ListMarker {
839
2672
  return null;
840
2673
  }
841
2674
 
2675
+ /// Recognize the common single-line form of a CommonMark link reference
2676
+ /// definition. Definitions are block metadata and never render by themselves,
2677
+ /// even when no reference uses their label. Reference-link resolution remains
2678
+ /// outside this widget's subset; recognizing the definition is still necessary
2679
+ /// to avoid exposing bot metadata such as Vercel's `[vc]: #hash:payload` line.
2680
+ fn isLinkReferenceDefinition(line: []const u8) bool {
2681
+ var cursor: usize = 0;
2682
+ while (cursor < line.len and line[cursor] == ' ') cursor += 1;
2683
+ if (cursor > 3 or cursor >= line.len or line[cursor] != '[') return false;
2684
+
2685
+ cursor += 1;
2686
+ var label_has_content = false;
2687
+ var closed_label = false;
2688
+ while (cursor < line.len) {
2689
+ const byte = line[cursor];
2690
+ if (byte == '\\' and cursor + 1 < line.len and isAsciiPunctuation(line[cursor + 1])) {
2691
+ label_has_content = label_has_content or !isInlineSpace(line[cursor + 1]);
2692
+ cursor += 2;
2693
+ continue;
2694
+ }
2695
+ if (byte == '[') return false;
2696
+ if (byte == ']') {
2697
+ closed_label = true;
2698
+ cursor += 1;
2699
+ break;
2700
+ }
2701
+ label_has_content = label_has_content or !isInlineSpace(byte);
2702
+ cursor += 1;
2703
+ }
2704
+ if (!closed_label or !label_has_content or cursor >= line.len or line[cursor] != ':') return false;
2705
+
2706
+ cursor += 1;
2707
+ cursor = skipInlineSpaces(line, cursor);
2708
+ cursor = parseLinkReferenceDestination(line, cursor) orelse return false;
2709
+ const destination_end = cursor;
2710
+ cursor = skipInlineSpaces(line, cursor);
2711
+ if (cursor == line.len) return true;
2712
+ if (cursor == destination_end) return false;
2713
+
2714
+ cursor = parseLinkReferenceTitle(line, cursor) orelse return false;
2715
+ return skipInlineSpaces(line, cursor) == line.len;
2716
+ }
2717
+
2718
+ fn parseLinkReferenceDestination(line: []const u8, start: usize) ?usize {
2719
+ if (start >= line.len) return null;
2720
+ var cursor = start;
2721
+ if (line[cursor] == '<') {
2722
+ cursor += 1;
2723
+ while (cursor < line.len) {
2724
+ const byte = line[cursor];
2725
+ if (byte == '\\' and cursor + 1 < line.len and isAsciiPunctuation(line[cursor + 1])) {
2726
+ cursor += 2;
2727
+ continue;
2728
+ }
2729
+ if (byte == '<' or byte == '\n' or byte == '\r') return null;
2730
+ if (byte == '>') return cursor + 1;
2731
+ cursor += 1;
2732
+ }
2733
+ return null;
2734
+ }
2735
+
2736
+ var paren_depth: usize = 0;
2737
+ while (cursor < line.len and !isInlineSpace(line[cursor])) {
2738
+ const byte = line[cursor];
2739
+ if (byte < 0x20 or byte == 0x7f or byte == '<') return null;
2740
+ if (byte == '\\' and cursor + 1 < line.len and isAsciiPunctuation(line[cursor + 1])) {
2741
+ cursor += 2;
2742
+ continue;
2743
+ }
2744
+ if (byte == '(') {
2745
+ paren_depth += 1;
2746
+ } else if (byte == ')') {
2747
+ if (paren_depth == 0) return null;
2748
+ paren_depth -= 1;
2749
+ }
2750
+ cursor += 1;
2751
+ }
2752
+ if (cursor == start or paren_depth != 0) return null;
2753
+ return cursor;
2754
+ }
2755
+
2756
+ fn parseLinkReferenceTitle(line: []const u8, start: usize) ?usize {
2757
+ if (start >= line.len) return null;
2758
+ const close: u8 = switch (line[start]) {
2759
+ '"' => '"',
2760
+ '\'' => '\'',
2761
+ '(' => ')',
2762
+ else => return null,
2763
+ };
2764
+ var cursor = start + 1;
2765
+ while (cursor < line.len) {
2766
+ if (line[cursor] == '\\' and cursor + 1 < line.len and isAsciiPunctuation(line[cursor + 1])) {
2767
+ cursor += 2;
2768
+ continue;
2769
+ }
2770
+ if (line[cursor] == close) return cursor + 1;
2771
+ cursor += 1;
2772
+ }
2773
+ return null;
2774
+ }
2775
+
2776
+ fn skipInlineSpaces(text: []const u8, start: usize) usize {
2777
+ var cursor = start;
2778
+ while (cursor < text.len and isInlineSpace(text[cursor])) cursor += 1;
2779
+ return cursor;
2780
+ }
2781
+
2782
+ fn isAsciiPunctuation(byte: u8) bool {
2783
+ return (byte >= 0x21 and byte <= 0x2f) or
2784
+ (byte >= 0x3a and byte <= 0x40) or
2785
+ (byte >= 0x5b and byte <= 0x60) or
2786
+ (byte >= 0x7b and byte <= 0x7e);
2787
+ }
2788
+
842
2789
  fn startsNewBlock(line: []const u8) bool {
843
2790
  const trimmed = std.mem.trim(u8, line, " \t");
844
2791
  if (trimmed.len == 0) return true;
@@ -848,6 +2795,10 @@ fn startsNewBlock(line: []const u8) bool {
848
2795
  if (std.mem.startsWith(u8, trimmed, ">")) return true;
849
2796
  if (listMarker(line) != null) return true;
850
2797
  if (std.ascii.startsWithIgnoreCase(trimmed, "<details")) return true;
2798
+ if (parseHtmlTagAt(trimmed, 0)) |tag| {
2799
+ if (isHtmlBlockTag(tag)) return true;
2800
+ }
2801
+ if (std.mem.startsWith(u8, trimmed, "<!--")) return true;
851
2802
  return false;
852
2803
  }
853
2804
 
@@ -876,6 +2827,8 @@ const ScanCache = struct {
876
2827
  /// quadratic rescans on interleaved `[`/`<` walls.
877
2828
  title_space: Slot = .{}, // ' '
878
2829
  scheme_sep: Slot = .{}, // "://"
2830
+ html_comment_close: Slot = .{}, // "-->"
2831
+ html_code_tick: Slot = .{}, // '`' while scanning tags outside code spans
879
2832
 
880
2833
  const Slot = struct {
881
2834
  valid: bool = false,