lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Rich text that paints more than its glyphs: underlined spans, and links
//! that are child nodes of their paragraph ([`crate::node::inline_link`]).
//!
//! Once the paragraph's box is known, its spans are laid out at the width the
//! paint lays them out at, which gives one box per span and laid-out line.
//! The links are placed on the boxes of their spans, and the paragraph paints
//! underlines under the boxes of underlined spans and the links' fills and
//! focus rings around the boxes of their words, so all of them follow
//! wrapping. Such a paragraph's line boxes are centered in its box, as
//! multi-span rich text already was, and painted from the top of the laid-out
//! text, so glyphs and the geometry painted around them agree.

#[cfg(feature = "markdown")]
use std::ops::Range;
use std::sync::Arc;

#[cfg(feature = "markdown")]
use super::transformed_quad_frame;
use super::{LayoutEngine, TextLayoutOutput};
use crate::{
  app::glyph_engine::{GlyphEngine, SpanBox},
  layout::{
    Offset, Size,
    layout_result::{ChildLayout, LayoutResult, SubtreeHolds},
    quad::RichTextSpan,
    text_style::TextAlign,
  },
  node::{
    node::Node,
    node_kind::{NodeKind, TextOverflow},
  },
};
#[cfg(feature = "markdown")]
use crate::{
  app::theme::MarkdownLinkState,
  layout::quad::{ClipRect, Quad, QuadContent},
  node::{
    border::{BorderPlacement, BorderRadius, ResolvedBorder, ResolvedBorders},
    color::Color,
    inline_link::InlineLink,
    transform::Transform2D,
  },
};

/// Where a paragraph's laid-out text lies in its box, for painting around it.
pub(crate) struct InlineTextLayout {
  /// The text's offset from the top of the paragraph's box.
  pub(crate) top: f32,
  pub(crate) text_height: f32,
  pub(crate) span_boxes: Arc<[SpanBox]>,
  /// The spans as they are laid out where the paragraph has objects: each object's as wide as its element
  /// ([`super::text_objects`]).
  pub(crate) spans: Option<Arc<[RichTextSpan]>>,
}

impl InlineTextLayout {
  pub(super) fn estimated_memory_bytes(&self) -> usize {
    std::mem::size_of::<Self>()
      + self.span_boxes.len() * std::mem::size_of::<SpanBox>()
      + self.spans.as_ref().map_or(0, |spans| {
        spans
          .iter()
          .map(|span| std::mem::size_of::<RichTextSpan>() + span.text.len())
          .sum()
      })
  }
}

/// A rectangle in the paragraph's coordinates.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct InlineRect {
  pub(crate) x: f32,
  pub(crate) y: f32,
  pub(crate) width: f32,
  pub(crate) height: f32,
}

#[cfg_attr(not(feature = "markdown"), allow(dead_code))]
impl InlineRect {
  fn contains(&self, x: f32, y: f32) -> bool {
    x >= self.x && x <= self.x + self.width && y >= self.y && y <= self.y + self.height
  }

  fn outset(&self, by: f32) -> Self {
    Self {
      x: self.x - by,
      y: self.y - by,
      width: self.width + 2.0 * by,
      height: self.height + 2.0 * by,
    }
  }
}

#[cfg(feature = "markdown")]
/// Where a link lies in its paragraph: one rectangle per laid-out line of its
/// words and of its target (its words and what follows them).
pub(crate) struct InlineLinkOutput {
  /// The link node's offset in its paragraph: the top-left of its first line.
  pub(crate) origin: Offset,
  pub(crate) label: Box<[InlineRect]>,
  pub(crate) target: Box<[InlineRect]>,
}

#[cfg(feature = "markdown")]
impl InlineLinkOutput {
  /// Whether `(x, y)`, relative to the link node's origin, is on the link.
  pub(crate) fn hits(&self, x: f32, y: f32) -> bool {
    let (x, y) = (x + self.origin.x, y + self.origin.y);
    self.target.iter().any(|rect| rect.contains(x, y))
  }

  pub(super) fn estimated_memory_bytes(&self) -> usize {
    (self.label.len() + self.target.len()) * std::mem::size_of::<InlineRect>()
  }
}

impl LayoutEngine {
  /// Places a rich-text paragraph's links and lays out the geometry its
  /// underlines and links paint with, once `result` holds its box.
  pub(super) fn lay_out_inline_text(&self, glyph_engine: &mut GlyphEngine, node: &Node, result: &mut LayoutResult) {
    let NodeKind::RichText { spans, generated, .. } = node.node_kind() else {
      return;
    };
    #[cfg(feature = "markdown")]
    let nothing = node.children().is_empty()
      && generated.is_empty()
      && !spans
        .iter()
        .any(|span| span.style.underline.is_some() || span.style.strikethrough.is_some());
    // Without the feature `markdown` a paragraph has no links: it lays out what it paints around its objects.
    #[cfg(not(feature = "markdown"))]
    let nothing = {
      let _ = generated;
      node.children().is_empty()
    };
    if nothing {
      return;
    }
    let objects = self.object_spans(glyph_engine, node, spans, result.size.width);
    let laid_out = objects
      .as_ref()
      .map_or(spans.as_slice(), |(widened, _)| widened.as_slice());
    let (text_size, span_boxes) = self.painted_span_boxes(glyph_engine, node, laid_out, result.size.width);
    let top = (result.size.height - text_size.height) * 0.5;
    let objects = objects.map(|(widened, objects)| (Arc::<[RichTextSpan]>::from(widened), objects));
    result.children = node
      .children()
      .iter()
      .enumerate()
      .map(|(index, child)| {
        let object = objects
          .as_ref()
          .and_then(|(_, objects)| objects.iter().find(|object| object.child == index));
        match object {
          Some(object) => self.object_child_layout(glyph_engine, child, object, &span_boxes, top),
          None => {
            child.layout_cache.mark_placed_by_parent();
            #[cfg(feature = "markdown")]
            {
              link_child_layout(child, &span_boxes, top)
            }
            #[cfg(not(feature = "markdown"))]
            dropped_child()
          }
        }
      })
      .collect();
    let inline = Arc::new(InlineTextLayout {
      top,
      text_height: text_size.height,
      span_boxes,
      spans: objects.map(|(widened, _)| widened),
    });
    if let Some(TextLayoutOutput::Text(output)) = result.text_layout.as_deref() {
      result.text_layout = Some(Arc::new(TextLayoutOutput::Text(output.with_inline(inline))));
      Self::restore_text_layout_output(node, result);
    }
  }

  /// The spans laid out as the paint lays them out: in device pixels at the
  /// paint's scale and at the width the paint wraps at (see the runtime's
  /// rich-text paint), in logical pixels again. The paint wraps at the box's
  /// width rounded up in device pixels, `ceil(width * scale)`, which at a
  /// fractional scale (1.25, 1.5) is not `ceil(width)` logical pixels: a word
  /// ending between the two wraps in the paint and not in a logical layout.
  fn painted_span_boxes(
    &self,
    glyph_engine: &mut GlyphEngine,
    node: &Node,
    spans: &[RichTextSpan],
    width: f32,
  ) -> (Size, Arc<[SpanBox]>) {
    let scale = self.paint_scale.get();
    let wrap = node.text_wrap && node.text_overflow == TextOverflow::Clip;
    let align = spans.first().map_or(TextAlign::Left, |span| span.style.text_align);
    let max_width = if (wrap || align != TextAlign::Left) && width > 0.0 {
      (width * scale).ceil()
    } else {
      f32::MAX
    };
    if scale == 1.0 {
      return glyph_engine.rich_text_span_boxes(spans, max_width, wrap);
    }
    let mut scaled = spans.to_vec();
    for span in &mut scaled {
      span.style.scale_pixels(scale);
    }
    let (size, boxes) = glyph_engine.rich_text_span_boxes(&scaled, max_width, wrap);
    let logical = boxes
      .iter()
      .map(|span_box| SpanBox {
        span: span_box.span,
        x: span_box.x / scale,
        width: span_box.width / scale,
        top: span_box.top / scale,
        height: span_box.height / scale,
        baseline: span_box.baseline / scale,
        underline_offset: span_box.underline_offset / scale,
        underline_thickness: span_box.underline_thickness / scale,
        strikethrough_offset: span_box.strikethrough_offset / scale,
        strikethrough_thickness: span_box.strikethrough_thickness / scale,
      })
      .collect();
    (Size::new(size.width / scale, size.height / scale), logical)
  }

  /// Where the spans a rich text draws as presentation (isolate marks,
  /// trailing runs) lie, in its box: a selection highlight leaves them out.
  pub(super) fn generated_span_rects(node: &Node, result: &LayoutResult) -> Vec<InlineRect> {
    let (NodeKind::RichText { generated, .. }, Some(inline)) = (node.node_kind(), inline_layout(result)) else {
      return Vec::new();
    };
    inline
      .span_boxes
      .iter()
      .filter(|span_box| {
        usize::try_from(span_box.span).is_ok_and(|span| generated.iter().any(|range| range.contains(&span)))
      })
      .map(|span_box| InlineRect {
        x: span_box.x,
        y: inline.top + span_box.top,
        width: span_box.width,
        height: span_box.height,
      })
      .collect()
  }

  /// The text's offset from the top of its box and its height, for a
  /// paragraph that paints underlines or links.
  pub(super) fn inline_text_frame(result: &LayoutResult) -> Option<(f32, f32)> {
    inline_layout(result).map(|inline| (inline.top, inline.text_height))
  }

  /// The paragraph's spans as painted: each link's words and trailing runs
  /// take the colors of its hover and focus states.
  pub(super) fn painted_rich_text_spans(
    &self,
    node: &Node,
    spans: &[RichTextSpan],
    result: &LayoutResult,
  ) -> Vec<RichTextSpan> {
    // A paragraph with objects is drawn as it was laid out: each object's span as wide as its element.
    #[cfg_attr(not(feature = "markdown"), allow(unused_mut))]
    let mut painted = match inline_layout(result).and_then(|inline| inline.spans.as_ref()) {
      Some(laid_out) if laid_out.len() == spans.len() => laid_out.to_vec(),
      _ => spans.to_vec(),
    };
    #[cfg(not(feature = "markdown"))]
    let _ = node;
    #[cfg(feature = "markdown")]
    let palette = self.palette.borrow();
    #[cfg(feature = "markdown")]
    let resolved = |color: &Option<crate::node::TextColor>| color.as_ref().and_then(|color| color.resolve(&palette));
    #[cfg(feature = "markdown")]
    for (link, state) in link_states(node) {
      for span in painted.get_mut(link.label.clone()).unwrap_or_default() {
        if let Some(color) = resolved(&state.color) {
          span.style.color = color;
        }
        if let (Some(color), Some(underline)) = (resolved(&state.underline_color), span.style.underline.as_mut()) {
          underline.color = Some(color);
        }
      }
      if let Some(color) = resolved(&state.trailing_color) {
        for span in painted.get_mut(link.trailing.clone()).unwrap_or_default() {
          span.style.color = color;
        }
      }
    }
    painted
  }

  #[cfg(feature = "markdown")]
  /// The fills behind the words of hovered and focused links.
  pub(super) fn push_inline_link_fills(
    &self,
    node: &Node,
    result: &LayoutResult,
    paint: InlinePaint,
    quads: &mut Vec<Quad>,
  ) {
    for ((link, state), child_layout) in link_states_with_layouts(node, result) {
      let color = state
        .background
        .as_ref()
        .and_then(|color| color.resolve(&self.palette.borrow()));
      let (Some(color), Some(output)) = (color, link_output(child_layout)) else {
        continue;
      };
      for rect in &output.label {
        quads.push(paint.rect(*rect, color, Some(link.look.radius), None));
      }
    }
  }

  #[cfg(feature = "markdown")]
  /// The underlines of underlined spans and the lines through struck ones,
  /// drawn in `spans`' painted colors. Lines of neighbouring spans that meet
  /// on a line of text are one: a link's words are several spans (emphasis,
  /// the joiners that keep it on one line) under one line.
  pub(super) fn inline_underlines(result: &LayoutResult, spans: &[RichTextSpan], paint: InlinePaint) -> Vec<Quad> {
    let Some(inline) = inline_layout(result) else {
      return Vec::new();
    };
    let style_of = |span_box: &SpanBox| spans.get(usize::try_from(span_box.span).ok()?).map(|span| &span.style);
    let piece = |(rect, color): (super::text_decorations::LineRect, Color)| {
      let rect = InlineRect {
        x: rect.x,
        y: rect.y,
        width: rect.width,
        height: rect.height,
      };
      (rect, color)
    };
    let mut lines = joined_lines(inline.span_boxes.iter().filter_map(|span_box| {
      super::text_decorations::underline_piece(style_of(span_box)?, span_box, inline.top).map(piece)
    }));
    lines.extend(joined_lines(inline.span_boxes.iter().filter_map(|span_box| {
      super::text_decorations::strikethrough_piece(style_of(span_box)?, span_box, inline.top).map(piece)
    })));
    lines
      .into_iter()
      .map(|(rect, color)| paint.rect(rect, color, None, None))
      .collect()
  }

  #[cfg(feature = "markdown")]
  /// The focus rings of links with keyboard focus, around each line of their
  /// words. They take the paragraph's clip, not its box, so they show in full.
  pub(super) fn push_inline_link_rings(
    &self,
    node: &Node,
    result: &LayoutResult,
    paint: InlinePaint,
    quads: &mut Vec<Quad>,
  ) {
    for (child, child_layout) in node.children().iter().zip(&result.children) {
      let (NodeKind::InlineLink { link }, Some(output)) = (child.node_kind(), link_output(child_layout)) else {
        continue;
      };
      let Some(ring) = link.look.focus_ring.as_ref().filter(|_| child.is_style_focus_visible()) else {
        continue;
      };
      let Some(color) = ring.color.resolve(&self.palette.borrow()) else {
        continue;
      };
      let border = ResolvedBorder {
        width: ring.width,
        color,
        placement: BorderPlacement::Inside,
        dash: [0.0; 2],
      };
      let borders = ResolvedBorders {
        top: Some(border),
        right: Some(border),
        bottom: Some(border),
        left: Some(border),
      };
      for rect in &output.label {
        let outer = rect.outset(ring.offset + ring.width);
        quads.push(paint.rect(
          outer,
          Color::new(0, 0, 0, 0),
          Some(BorderRadius::all(ring.radius)),
          Some(borders),
        ));
      }
    }
  }
}

#[cfg(feature = "markdown")]
/// Joins the lines that meet on a line of text in one color into one.
fn joined_lines(pieces: impl Iterator<Item = (InlineRect, Color)>) -> Vec<(InlineRect, Color)> {
  let mut lines: Vec<(InlineRect, Color)> = Vec::new();
  for (rect, color) in pieces {
    match lines.last_mut() {
      Some((last, last_color))
        if *last_color == color
          && last.y == rect.y
          && last.height == rect.height
          && (last.x + last.width - rect.x).abs() < 0.5 =>
      {
        last.width = rect.x + rect.width - last.x;
      }
      _ => lines.push((rect, color)),
    }
  }
  lines
}

#[cfg(feature = "markdown")]
/// Where and how a paragraph paints around its text.
#[derive(Clone, Copy)]
pub(super) struct InlinePaint {
  /// The paragraph's top-left.
  pub(super) x: f32,
  pub(super) y: f32,
  pub(super) transform: Transform2D,
  pub(super) clip: ClipRect,
  pub(super) opacity: f32,
}

#[cfg(feature = "markdown")]
impl InlinePaint {
  fn rect(self, rect: InlineRect, color: Color, radius: Option<BorderRadius>, border: Option<ResolvedBorders>) -> Quad {
    let (x, y, transform, transform_origin) = transformed_quad_frame(self.x + rect.x, self.y + rect.y, self.transform);
    Quad {
      x,
      y,
      width: rect.width,
      height: rect.height,
      opacity: self.opacity,
      transform,
      transform_origin,
      content: QuadContent::Rect { color, gradient: None },
      border_radius: radius,
      border,
      clip: self.clip,
    }
  }
}

/// The parts of the band `x..x + width` (at `y`, `height` tall) that none
/// of `rects` on the same line covers, as `(x, width)`.
pub(super) fn without_rects(x: f32, y: f32, width: f32, height: f32, rects: &[InlineRect]) -> Vec<(f32, f32)> {
  let mut pieces = vec![(x, x + width)];
  for rect in rects
    .iter()
    .filter(|rect| rect.width > 0.0 && rect.y < y + height && y < rect.y + rect.height)
  {
    let (cut_start, cut_end) = (rect.x, rect.x + rect.width);
    pieces = pieces
      .into_iter()
      .flat_map(|(start, end)| {
        [(start, end.min(cut_start)), (start.max(cut_end), end)]
          .into_iter()
          .filter(|(start, end)| end > start)
      })
      .collect();
  }
  pieces.into_iter().map(|(start, end)| (start, end - start)).collect()
}

fn inline_layout(result: &LayoutResult) -> Option<&InlineTextLayout> {
  match result.text_layout.as_deref()? {
    TextLayoutOutput::Text(output) => output.inline.as_deref(),
    _ => None,
  }
}

#[cfg(feature = "markdown")]
fn link_output(child_layout: &ChildLayout) -> Option<&InlineLinkOutput> {
  match child_layout.result.text_layout.as_deref()? {
    TextLayoutOutput::InlineLink(output) => Some(output),
    _ => None,
  }
}

#[cfg(feature = "markdown")]
/// The paragraph's links that are hovered or have keyboard focus, with the
/// look of that state.
fn link_states(node: &Node) -> impl Iterator<Item = (&InlineLink, MarkdownLinkState)> {
  node.children().iter().filter_map(|child| {
    let NodeKind::InlineLink { link } = child.node_kind() else {
      return None;
    };
    Some((link, link_states_of(child, link)?))
  })
}

#[cfg(feature = "markdown")]
fn link_states_with_layouts<'a>(
  node: &'a Node,
  result: &'a LayoutResult,
) -> impl Iterator<Item = ((&'a InlineLink, MarkdownLinkState), &'a ChildLayout)> {
  node
    .children()
    .iter()
    .zip(&result.children)
    .filter_map(|(child, layout)| {
      let NodeKind::InlineLink { link } = child.node_kind() else {
        return None;
      };
      let state = link_states_of(child, link)?;
      Some(((link, state), layout))
    })
}

#[cfg(feature = "markdown")]
/// The look of `child`'s state, focus over hover where both apply; `None` at
/// rest.
fn link_states_of(child: &Node, link: &InlineLink) -> Option<MarkdownLinkState> {
  let hovered = child.is_style_hovered().then(|| link.look.hovered.clone());
  let focused = child.is_style_focus_visible().then(|| link.look.focused.clone());
  match (hovered, focused) {
    (None, None) => None,
    (Some(state), None) | (None, Some(state)) => Some(state),
    (Some(hovered), Some(focused)) => Some(MarkdownLinkState {
      color: focused.color.or(hovered.color),
      underline_color: focused.underline_color.or(hovered.underline_color),
      background: focused.background.or(hovered.background),
      trailing_color: focused.trailing_color.or(hovered.trailing_color),
    }),
  }
}

impl LayoutEngine {
  /// An object's child laid out at its size and placed on its span: at the span's start, on the middle of its
  /// line. One whose span is not laid out takes no room and is not painted.
  fn object_child_layout(
    &self,
    glyph_engine: &mut GlyphEngine,
    child: &Node,
    object: &super::text_objects::TextObject,
    span_boxes: &[SpanBox],
    top: f32,
  ) -> ChildLayout {
    let Some(line) = span_boxes
      .iter()
      .find(|span_box| usize::try_from(span_box.span).is_ok_and(|span| span == object.span))
    else {
      child.layout_cache.mark_placed_by_parent();
      return dropped_child();
    };
    ChildLayout {
      offset: Offset {
        x: line.x,
        y: top + line.top + (line.height - object.size.height) * 0.5,
      },
      result: self.layout_node(glyph_engine, child, crate::layout::Constraints::tight(object.size)),
    }
  }
}

/// A child the paragraph does not place: it takes no room and is not painted.
fn dropped_child() -> ChildLayout {
  ChildLayout {
    offset: Offset::default(),
    result: Arc::new(LayoutResult {
      size: Size::default(),
      children: Vec::new(),
      text_layout: None,
      dropped: true,
      holds: SubtreeHolds::UNKNOWN,
      generation: 0,
      sticky_shifts: None,
      reach: crate::layout::layout_result::Reach::UNKNOWN,
    }),
  }
}

#[cfg(feature = "markdown")]
fn link_child_layout(child: &Node, span_boxes: &[SpanBox], top: f32) -> ChildLayout {
  let output = match child.node_kind() {
    NodeKind::InlineLink { link } => InlineLinkOutput {
      origin: Offset::default(),
      label: line_rects(span_boxes, &link.label, top),
      target: line_rects(span_boxes, &link.target, top),
    },
    _ => InlineLinkOutput {
      origin: Offset::default(),
      label: Box::default(),
      target: Box::default(),
    },
  };
  let first = output
    .label
    .first()
    .or(output.target.first())
    .copied()
    .unwrap_or_default();
  let origin = Offset { x: first.x, y: first.y };
  ChildLayout {
    offset: origin,
    result: Arc::new(LayoutResult {
      size: Size::new(first.width, first.height),
      children: Vec::new(),
      text_layout: Some(Arc::new(TextLayoutOutput::InlineLink(InlineLinkOutput {
        origin,
        ..output
      }))),
      dropped: false,
      holds: SubtreeHolds::UNKNOWN,
      generation: 0,
      sticky_shifts: None,
      reach: crate::layout::layout_result::Reach::UNKNOWN,
    }),
  }
}

#[cfg(feature = "markdown")]
/// One rectangle per laid-out line covering the boxes of `spans`, shifted
/// down by `top`.
fn line_rects(span_boxes: &[SpanBox], spans: &Range<usize>, top: f32) -> Box<[InlineRect]> {
  let mut rects: Vec<InlineRect> = Vec::new();
  let mut line_top = f32::NAN;
  for span_box in span_boxes
    .iter()
    .filter(|span_box| usize::try_from(span_box.span).is_ok_and(|span| spans.contains(&span)))
  {
    let rect = InlineRect {
      x: span_box.x,
      y: top + span_box.top,
      width: span_box.width,
      height: span_box.height,
    };
    match rects.last_mut() {
      Some(last) if span_box.top == line_top => {
        let right = (last.x + last.width).max(rect.x + rect.width);
        last.x = last.x.min(rect.x);
        last.width = right - last.x;
      }
      _ => rects.push(rect),
    }
    line_top = span_box.top;
  }
  rects.into_boxed_slice()
}