canvist_layout 0.2.2

Incremental text and block layout for the canvist editor: line breaking, bidi, hit testing, display lists, and SVG/HTML renderers
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
//! Building a display list from a laid-out document, in paint order.

use std::collections::BTreeSet;
use std::ops::Range;
use std::sync::Arc;

use canvist_model::BlockId;
use canvist_model::Selection;

use super::DecorationKind;
use super::DisplayItem;
use super::DisplayList;
use super::DisplayOptions;
use super::RectKind;
use super::SlotKind;
use super::TextRun;
use super::fade;
use super::fade::Fade;
use super::motion;
use crate::BlockStyle;
use crate::Caret;
use crate::Color;
use crate::DocumentLayout;
use crate::Rect;
use crate::TableRole;
use crate::document::Marker;
use crate::document::Origin;
use crate::document::Row;
use crate::document::RowKind;
use crate::document::Span;
use crate::style::StyleId;
use crate::text::ItemKind;
use crate::text::Line;
use crate::text::Piece;
use crate::text::RunStyle;
use crate::text::TextLayout;
use crate::text::slice;
#[cfg(feature = "ink")]
use crate::theme::INK_WIDTH;
use crate::theme::LeafStyle;
use crate::theme::MarkerKind;
use crate::theme::Motion;

impl DocumentLayout {
	/// Build the display list for `options.top..options.bottom`.
	///
	/// Only measured blocks are painted: call [`DocumentLayout::ensure`] for
	/// the same range first.
	#[must_use]
	pub fn display_list(&self, options: &DisplayOptions) -> DisplayList {
		let mut builder = Builder::new(self, options);
		let rows: Vec<usize> = self.rows_between(options.top, options.bottom).collect();

		builder.containers(&rows);

		for &index in &rows {
			builder.row_background(index);
		}

		for &index in &rows {
			builder.inline_backgrounds(index);
		}

		for (range, color) in &options.highlights {
			builder.selection(range, *color, RectKind::Range);
		}

		if let Some(selection) = &options.selection {
			builder.selection(
				selection,
				self.theme().chrome().selection,
				RectKind::Selection,
			);
		}

		for &index in &rows {
			builder.row_content(index);
		}

		builder.placeholders(&rows, &options.placeholders);
		builder.finish(options.caret)
	}
}

/// How opaque placeholder text is, relative to the block's text colour.
const PLACEHOLDER_ALPHA: f32 = 0.4;

/// A decoration line's thickness as a fraction of the font size, before
/// rounding up to at least one pixel.
const DECORATION_THICKNESS: f32 = 1.0 / 16.0;

/// How far below the baseline an underline sits, as a fraction of the font
/// size.
const UNDERLINE_OFFSET: f32 = 0.1;

/// How far above the baseline a strikethrough sits, as a fraction of the
/// font size: roughly the middle of lowercase letters.
const STRIKE_OFFSET: f32 = 0.3;

/// How far below the baseline a squiggle sits, as a fraction of the font
/// size. It sits lower than an underline to leave room for its waves.
const SQUIGGLE_OFFSET: f32 = 0.15;

/// The vertical extent of one line of text.
#[derive(Clone, Copy)]
struct LineBox {
	top: f32,
	height: f32,
	baseline: f32,
}

struct Builder<'a> {
	layout: &'a DocumentLayout,
	list: DisplayList,
	/// The animation clock, when kinetic text should move.
	time: Option<f32>,
	/// Text fading into ink: see [`DisplayOptions::settling`].
	settling: &'a [(BlockId, Range<u32>, f32)],
	/// Decorations and slots, painted above all text.
	foreground: Vec<DisplayItem>,
}

impl<'a> Builder<'a> {
	/// An empty list carrying `layout`'s fonts, bounded by the full document
	/// width between `options.top` and `options.bottom`.
	fn new(layout: &'a DocumentLayout, options: &'a DisplayOptions) -> Self {
		let height = options.bottom - options.top;
		let bounds = Rect::new(0.0, options.top, layout.options().width, height);

		Self {
			layout,
			list: DisplayList {
				fonts: layout.cache().fonts().fonts().to_vec(),
				items: Vec::new(),
				bounds,
				animated: false,
				points: Vec::new(),
			},
			time: options.time,
			settling: &options.settling,
			foreground: Vec::new(),
		}
	}
}

impl Builder<'_> {
	/// Paint decorations and slots above all text, then the caret on top.
	fn finish(mut self, caret: Option<Caret>) -> DisplayList {
		self.list.items.append(&mut self.foreground);

		if let Some(rect) = caret.and_then(|caret| self.layout.caret_rect(caret)) {
			self.list.items.push(DisplayItem::Rect {
				rect,
				color: self.layout.theme().chrome().caret,
				radius: 0.0,
				kind: RectKind::Caret,
				block: None,
			});
		}

		self.list
	}

	fn push_rect(&mut self, rect: Rect, color: Color, radius: f32, kind: RectKind, block: BlockId) {
		self.list.items.push(DisplayItem::Rect {
			rect,
			color,
			radius,
			kind,
			block: Some(block),
		});
	}

	/// The background and left border `style` gives the box `rect`.
	fn push_box(&mut self, rect: Rect, style: &BlockStyle, block: BlockId) {
		if let Some(color) = style.background {
			self.push_rect(rect, color, style.radius, RectKind::Background, block);
		}

		if let Some(border) = style.border_left {
			let bar = Rect::new(rect.x, rect.y, border.width, rect.height);
			self.push_rect(bar, border.color, 0.0, RectKind::Border, block);
		}
	}

	/// Backgrounds and borders of every container enclosing a visible row,
	/// outermost first.
	fn containers(&mut self, rows: &[usize]) {
		let layout = self.layout;
		let mut tables = Vec::new();

		for index in visible_spans(layout, rows) {
			let span = &layout.spans()[index as usize];
			let style = layout.styles().get(span.style);

			self.push_box(layout.span_rect(span), style, span.block);

			if let Some(TableRole::Table { rule }) = style.table {
				tables.push((index, rule));
			}
		}

		for (index, rule) in tables {
			let block = layout.spans()[index as usize].block;

			for line in layout.grid_lines(index, self.list.bounds) {
				self.push_rect(line, rule.color, 0.0, RectKind::Border, block);
			}
		}
	}

	fn row_background(&mut self, index: usize) {
		let layout = self.layout;
		let row = &layout.rows()[index];
		let style = layout.style_of(row);
		let rect = layout.row_rect(index);

		self.push_box(rect, style, row.block);

		if row.kind != RowKind::Leaf {
			return;
		}

		let origin = layout.origin(index);
		let content = Rect::new(
			origin.x,
			origin.y,
			crate::document::content_width(style, row.width),
			rect.height - style.padding.vertical(),
		);

		match style.leaf {
			LeafStyle::Rule { color, .. } => {
				self.push_rect(content, color, 0.0, RectKind::Rule, row.block);
			}
			LeafStyle::Slot { .. } => {
				self.foreground.push(DisplayItem::Slot {
					kind: SlotKind::Block,
					block: row.block,
					offset: None,
					rect: content,
				});
			}
			#[cfg(feature = "ink")]
			LeafStyle::Ink { stroke, .. } => self.ink(row, content, stroke, style.text.color),
			#[cfg(not(feature = "ink"))]
			LeafStyle::Ink { .. } => {}
		}
	}

	/// The strokes of an ink drawing filling `content`, scaled from drawing
	/// units, in `color` and `width` drawing units where a stroke sets
	/// neither.
	#[cfg(feature = "ink")]
	fn ink(&mut self, row: &Row, content: Rect, width: f32, color: Color) {
		let Some(drawing) = &row.ink else {
			return;
		};
		let scale = content.width / INK_WIDTH;

		for stroke in &drawing.strokes {
			let start = self.list.points.len() as u32;
			self.list.points.extend(
				stroke
					.points
					.chunks_exact(2)
					.flat_map(|point| [content.x + point[0] * scale, content.y + point[1] * scale]),
			);
			let points = start..self.list.points.len() as u32;
			let width = stroke.width.unwrap_or(width) * scale;

			self.list.items.push(DisplayItem::Stroke {
				bounds: stroke_bounds(self.list.stroke_points(&points), width),
				points,
				width,
				color: stroke.color.unwrap_or(color),
				block: row.block,
			});
		}
	}

	/// Inline backgrounds of row `index`, such as inline code, painted below
	/// all text so neighbouring pieces never cover each other's glyphs.
	fn inline_backgrounds(&mut self, index: usize) {
		let layout = self.layout;
		let row = &layout.rows()[index];
		let Some(text) = &row.layout else {
			return;
		};
		let origin = layout.origin(index);

		for line in &text.lines {
			let backgrounds = line
				.pieces
				.iter()
				.filter_map(|piece| piece_background(text, line, piece, origin));

			for (rect, color) in backgrounds {
				self.push_rect(rect, color, 0.0, RectKind::Highlight, row.block);
			}
		}
	}

	fn selection(&mut self, selection: &Selection, color: Color, kind: RectKind) {
		for rect in self.layout.selection_rects(selection) {
			self.list.items.push(DisplayItem::Rect {
				rect,
				color,
				radius: 0.0,
				kind,
				block: None,
			});
		}
	}

	fn row_content(&mut self, index: usize) {
		let layout = self.layout;
		let row = &layout.rows()[index];

		self.markers(index, row);

		let Some(text) = &row.layout else {
			return;
		};
		let origin = layout.origin(index);
		let (fades, animated) = fade::fades(row.block, text, self.settling, self.time);
		self.list.animated |= animated;

		for (index, line) in text.lines.iter().enumerate() {
			for piece in &line.pieces {
				self.piece(row.block, text, (index, line), piece, origin, &fades);
			}
		}
	}

	/// Draw one piece: its text run and decorations, or a slot for an
	/// unlabelled embed.
	fn piece(
		&mut self,
		block: BlockId,
		text: &TextLayout,
		(line_index, line): (usize, &Line),
		piece: &Piece,
		origin: Origin,
		fades: &[Fade],
	) {
		let item = &text.items[piece.item as usize];
		let baseline = origin.y + line.top + line.baseline;
		let x = origin.x + piece.x;

		if let ItemKind::Embed(embed) = &item.kind
			&& embed.label.is_none()
		{
			self.foreground.push(DisplayItem::Slot {
				kind: SlotKind::Embed(embed.kind),
				block,
				offset: Some(text.in_document(item.range.start)),
				rect: Rect::new(
					x,
					baseline - embed.ascent,
					embed.width,
					embed.ascent + embed.descent,
				),
			});

			return;
		}

		let Some((source, range, style)) = run_source(text, piece) else {
			return;
		};
		let baseline = baseline - style.style.baseline_shift;
		let motion = style.style.motion;

		if motion != Motion::None {
			self.list.animated = true;

			if let (Some(time), false, true) = (self.time, piece.rtl, cfg!(feature = "kinetic")) {
				let glyphs = Glyphs {
					block,
					text,
					line: (line_index, line),
					origin,
					baseline,
				};
				self.kinetic(&glyphs, piece, style, time);
				self.decorations(block, style, x, baseline, piece.width);
				return;
			}
		}

		let run = TextRun {
			block,
			source,
			range,
			font: style.font,
			x,
			baseline,
			width: piece.width,
			color: style.style.color,
			letter_spacing: style.style.letter_spacing,
			rtl: piece.rtl,
			bounds: Rect::new(x, origin.y + line.top, piece.width, line.height),
		};

		if fades.is_empty() || !matches!(item.kind, ItemKind::Text { .. }) {
			self.list.items.push(DisplayItem::Text(run));
		} else {
			let parts = fade::split(run, item, &text.text, fades);
			self.list
				.items
				.extend(parts.into_iter().map(DisplayItem::Text));
		}

		self.decorations(block, style, x, baseline, piece.width);
	}

	/// Draw a moving piece one grapheme at a time, each where `motion` puts
	/// it at `time`. Kept out of line: inlined, it slows every still piece.
	#[cold]
	#[inline(never)]
	fn kinetic(&mut self, glyphs: &Glyphs<'_>, piece: &Piece, style: &RunStyle, time: f32) {
		use unicode_segmentation::UnicodeSegmentation;

		let text = glyphs.text;
		let (line_index, line) = glyphs.line;
		let source = slice(&text.text, &piece.range);
		let caret = |offset: u32| {
			glyphs.origin.x + text.caret_x(line_index, offset, crate::Affinity::Downstream)
		};

		for (index, (start, grapheme)) in source.grapheme_indices(true).enumerate() {
			if grapheme.trim().is_empty() {
				continue;
			}

			let start = piece.range.start + start as u32;
			let end = start + grapheme.len() as u32;
			let x = caret(start);
			let width = caret(end) - x;
			let ((dx, dy), color) = motion::glyph(
				style.style.motion,
				time,
				index,
				style.style.font.size,
				style.style.color,
			);

			self.list.items.push(DisplayItem::Text(TextRun {
				block: glyphs.block,
				source: text.text.clone(),
				range: start..end,
				font: style.font,
				x: x + dx,
				baseline: glyphs.baseline + dy,
				width,
				color,
				letter_spacing: style.style.letter_spacing,
				rtl: false,
				bounds: Rect::new(x + dx, glyphs.origin.y + line.top + dy, width, line.height),
			}));
		}
	}

	/// Draw each placeholder in its block, if the block is visible, empty,
	/// and laid out. The text starts at the block's left edge on its first
	/// line, in the block's text colour at [`PLACEHOLDER_ALPHA`]. It is not
	/// measured, so its width is the block's.
	fn placeholders(&mut self, rows: &[usize], placeholders: &[(BlockId, Arc<str>)]) {
		if placeholders.is_empty() {
			return;
		}

		let layout = self.layout;

		for &index in rows {
			let row = &layout.rows()[index];
			let Some((_, text)) = placeholders.iter().find(|(block, _)| *block == row.block) else {
				continue;
			};
			let Some(empty) = row.layout.as_ref().filter(|layout| layout.text.is_empty()) else {
				continue;
			};
			let style = &empty.styles[0];
			let line = self.first_line_box(index, layout.style_of(row));
			let origin = layout.origin(index);
			let width = crate::document::content_width(layout.style_of(row), row.width);
			let color = style.style.color;
			let alpha = (f32::from(color.a) * PLACEHOLDER_ALPHA).round() as u8;

			self.list.items.push(DisplayItem::Text(TextRun {
				block: row.block,
				source: text.clone(),
				range: 0..text.len() as u32,
				font: style.font,
				x: origin.x,
				baseline: line.baseline,
				width,
				color: Color::rgba(color.r, color.g, color.b, alpha),
				letter_spacing: style.style.letter_spacing,
				rtl: false,
				bounds: Rect::new(origin.x, line.top, width, line.height),
			}));
		}
	}

	/// Push the decoration lines `style` asks for under a run of `width` at
	/// `x`.
	fn decorations(&mut self, block: BlockId, style: &RunStyle, x: f32, baseline: f32, width: f32) {
		let decorations = style.style.decorations;
		let size = style.style.font.size;
		let thickness = (size * DECORATION_THICKNESS).max(1.0);
		let color = decorations.color.unwrap_or(style.style.color);
		let lines = [
			(
				decorations.underline,
				DecorationKind::Underline,
				baseline + size * UNDERLINE_OFFSET,
			),
			(
				decorations.strike,
				DecorationKind::Strike,
				baseline - size * STRIKE_OFFSET,
			),
			(
				decorations.squiggle,
				DecorationKind::Squiggle,
				baseline + size * SQUIGGLE_OFFSET,
			),
		];

		for (_, kind, y) in lines.into_iter().filter(|line| line.0) {
			self.foreground.push(DisplayItem::Decoration {
				kind,
				x,
				y,
				width,
				thickness,
				color,
				block,
			});
		}
	}

	/// Markers of list items whose first row is `index`.
	fn markers(&mut self, index: usize, row: &Row) {
		let layout = self.layout;

		if let Some(marker) = &row.marker {
			let edge = row.x + border_width(layout.style_of(row));
			self.marker(index, row.block, row.style, edge, marker);
		}

		let mut span = row.span;

		while let Some(current) = span {
			let candidate: &Span = &layout.spans()[current as usize];

			if candidate.first_row as usize != index {
				break;
			}

			if let Some(marker) = &candidate.marker {
				let edge = candidate.x + border_width(layout.styles().get(candidate.style));
				self.marker(index, candidate.block, candidate.style, edge, marker);
			}

			span = candidate.parent;
		}
	}

	/// Draw `marker` to the left of `edge`, the list item's padding-box left
	/// edge (where CSS places `right: 100%`), on the first line of row
	/// `index`.
	fn marker(&mut self, index: usize, block: BlockId, style: StyleId, edge: f32, marker: &Marker) {
		let layout = self.layout;
		let style = layout.styles().get(style);
		let line = self.first_line_box(index, style);
		let right = edge - layout.theme().markers().gap;

		if marker.kind == MarkerKind::Task {
			self.checkbox(block, marker.checked, right, line);
		} else {
			self.marker_label(block, marker, style, right, line);
		}
	}

	/// The first line of row `index`, or one line of `style`'s text at the
	/// top of its content box while the row is unmeasured.
	fn first_line_box(&self, index: usize, style: &BlockStyle) -> LineBox {
		let layout = self.layout;
		let origin = layout.origin(index);
		let first = layout.rows()[index]
			.layout
			.as_ref()
			.and_then(|text| text.lines.first());

		match first {
			Some(line) => {
				LineBox {
					top: origin.y + line.top,
					height: line.height,
					baseline: origin.y + line.top + line.baseline,
				}
			}
			None => {
				LineBox {
					top: origin.y,
					height: style.text.line_height_px(),
					baseline: origin.y + style.text.font.size,
				}
			}
		}
	}

	/// Reserve a task item's checkbox slot, ending at `right` and centred on
	/// `line`.
	fn checkbox(&mut self, block: BlockId, checked: bool, right: f32, line: LineBox) {
		let size = self.layout.theme().markers().checkbox;

		self.foreground.push(DisplayItem::Slot {
			kind: SlotKind::Checkbox { checked },
			block,
			offset: None,
			rect: Rect::new(
				right - size,
				line.top + (line.height - size) / 2.0,
				size,
				size,
			),
		});
	}

	/// Draw a marker's text ending at `right` on `line`'s baseline. Markers
	/// with no text, or whose text has not been measured, are skipped.
	fn marker_label(
		&mut self,
		block: BlockId,
		marker: &Marker,
		style: &BlockStyle,
		right: f32,
		line: LineBox,
	) {
		let layout = self.layout;
		let Some(text) = layout.marker_text(marker) else {
			return;
		};

		let cache = layout.cache();
		let Some(font) = cache.fonts().find(&style.text.font) else {
			return;
		};
		let Some(width) = cache.get(font, &text).map(|measured| measured.width) else {
			return;
		};
		let color = layout.theme().markers().color.unwrap_or(style.text.color);

		self.list.items.push(DisplayItem::Text(TextRun {
			block,
			range: 0..text.len() as u32,
			source: text,
			font,
			x: right - width,
			baseline: line.baseline,
			width,
			color,
			letter_spacing: 0.0,
			rtl: false,
			bounds: Rect::new(right - width, line.top, width, line.height),
		}));
	}
}

/// Every container enclosing one of `rows`, by span index. Spans are
/// numbered in document order, so ascending order puts outer containers
/// first.
fn visible_spans(layout: &DocumentLayout, rows: &[usize]) -> BTreeSet<u32> {
	let mut visible = BTreeSet::new();

	for &index in rows {
		let mut span = layout.rows()[index].span;

		// Stop at the first container already seen: its ancestors are too.
		while let Some(current) = span
			&& visible.insert(current)
		{
			span = layout.spans()[current as usize].parent;
		}
	}

	visible
}

/// The inline background behind `piece`, such as inline code or a
/// highlight, with its colour.
fn piece_background(
	text: &TextLayout,
	line: &Line,
	piece: &Piece,
	origin: Origin,
) -> Option<(Rect, Color)> {
	let item = &text.items[piece.item as usize];

	// A labelled embed draws its label, so its background follows the
	// label's style.
	let style = match &item.kind {
		ItemKind::Embed(embed) => embed.label.as_ref().map_or(item.style, |label| label.style),
		_ => item.style,
	};

	let run = &text.styles[style as usize];
	let color = run.style.background?;

	if piece.width <= 0.0 || item.kind == ItemKind::Break {
		return None;
	}

	let baseline = origin.y + line.top + line.baseline - run.style.baseline_shift;
	let rect = Rect::new(
		origin.x + piece.x,
		baseline - run.metrics.ascent,
		piece.width,
		run.metrics.ascent + run.metrics.descent,
	);

	Some((rect, color))
}

/// The text `piece` draws, as a `range` of a shared `source`, and its style.
/// Embeds draw their label. Whitespace-only text, tabs, breaks, and
/// unlabelled embeds draw no text.
fn run_source<'a>(
	text: &'a TextLayout,
	piece: &Piece,
) -> Option<(Arc<str>, Range<u32>, &'a RunStyle)> {
	let item = &text.items[piece.item as usize];

	match &item.kind {
		ItemKind::Text { .. } => {
			let blank = slice(&text.text, &piece.range)
				.bytes()
				.all(|byte| byte == b' ');
			let style = &text.styles[item.style as usize];

			(!blank).then(|| (text.text.clone(), piece.range.clone(), style))
		}
		ItemKind::Embed(embed) => {
			embed.label.as_ref().map(|label| {
				let range = 0..label.text.len() as u32;

				(
					label.text.clone(),
					range,
					&text.styles[label.style as usize],
				)
			})
		}
		ItemKind::Tab | ItemKind::Break => None,
	}
}

/// The box around a stroke's points, widened by half its width.
#[cfg(feature = "ink")]
fn stroke_bounds(points: &[f32], width: f32) -> Rect {
	let (mut left, mut top, mut right, mut bottom) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);

	for point in points.chunks_exact(2) {
		left = left.min(point[0]);
		right = right.max(point[0]);
		top = top.min(point[1]);
		bottom = bottom.max(point[1]);
	}

	if left > right {
		return Rect::default();
	}

	let half = width / 2.0;
	Rect::new(
		left - half,
		top - half,
		right - left + width,
		bottom - top + width,
	)
}

/// Where the glyphs of a moving piece sit: its block, text, line, row
/// origin, and baseline.
struct Glyphs<'a> {
	block: BlockId,
	text: &'a TextLayout,
	line: (usize, &'a Line),
	origin: Origin,
	baseline: f32,
}

/// The width of a style's left border.
fn border_width(style: &BlockStyle) -> f32 {
	style.border_left.map_or(0.0, |border| border.width)
}