sinomo-ui-widgets 0.6.1

Built-in widget library for SUI.
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! Painting text in a rect: one line, a wrapped paragraph, or a paragraph
//! laid out during measurement.

use sui_core::{Color, Point, Rect, Size};
use sui_layout::LayoutContext;
use sui_runtime::{MeasureCtx, PaintCtx, window_render_options};
use sui_text::{
    TextAlign, TextDocument, TextLayout, TextLayoutRequest, TextMeasurement, TextStyle, TextWrap,
};
use unicode_segmentation::UnicodeSegmentation;

pub(crate) struct AlignedTextLayout {
    pub(crate) rect: Rect,
    origin: Point,
    layout: TextLayout,
    color: Color,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HorizontalTextAlignmentMode {
    Advance,
    Optical,
}

#[derive(Debug, Clone, Copy)]
struct HorizontalPlacement {
    rect_x: f32,
    rect_width: f32,
    origin_x: f32,
}

pub(crate) fn aligned_text_rect_for_text(
    ctx: &PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    line_height: f32,
    horizontal_alignment: f32,
) -> Rect {
    aligned_text_rect_for_text_with_mode(
        ctx,
        rect,
        text,
        style,
        line_height,
        horizontal_alignment,
        HorizontalTextAlignmentMode::Advance,
    )
}

pub(crate) fn aligned_text_rect_for_text_with_mode(
    ctx: &PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    line_height: f32,
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
) -> Rect {
    if let Some(aligned) = aligned_text_layout_for_text_with_mode(
        ctx,
        rect,
        text,
        style,
        line_height,
        horizontal_alignment,
        horizontal_mode,
    ) {
        return aligned.rect;
    }

    let fallback_measurement = || TextMeasurement {
        width: text.chars().count() as f32 * style.font_size * 0.56,
        height: style.line_height,
        bounds: Rect::ZERO,
        ascent: style.font_size,
        descent: 0.0,
        cap_height: Some(style.font_size),
    };
    let measurement = ctx
        .measure_text(text.to_string(), style.clone())
        .ok()
        .unwrap_or_else(fallback_measurement);
    let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
    let height = line_height.max(measurement.height).min(rect.height());
    let y = vertically_centered_text_rect_y(ctx, rect, measurement, height);

    Rect::new(placement.rect_x, y, placement.rect_width, height)
}

pub(crate) fn aligned_text_layout_for_text_with_mode(
    ctx: &PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    line_height: f32,
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
) -> Option<AlignedTextLayout> {
    aligned_text_layout_for_text_with_mode_and_wrap(
        ctx,
        rect,
        text,
        style,
        line_height,
        horizontal_alignment,
        horizontal_mode,
        TextWrap::Word,
    )
}

fn aligned_text_layout_for_text_with_mode_and_wrap(
    ctx: &PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    line_height: f32,
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
    wrap: TextWrap,
) -> Option<AlignedTextLayout> {
    let color = style.color;
    let mut layout_style = style.clone();
    layout_style.color = Color::WHITE;
    let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
    let paragraph_align = paragraph_alignment(horizontal_alignment, horizontal_mode);
    for paragraph in &mut document.paragraphs {
        paragraph.style.align = paragraph_align;
        paragraph.style.wrap = wrap;
    }
    let layout = ctx
        .layout_text_document(
            TextLayoutRequest::new(document)
                .with_box_size(Size::new(rect.width().max(1.0), rect.height().max(1.0))),
        )
        .ok()?;
    let measurement = layout.measurement();
    let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
    let aligned_rect = aligned_text_rect_for_layout_with_mode(
        ctx,
        rect,
        &layout,
        line_height,
        horizontal_alignment,
        horizontal_mode,
    );
    Some(AlignedTextLayout {
        origin: Point::new(placement.origin_x, aligned_rect.y()),
        rect: aligned_rect,
        layout,
        color,
    })
}

/// Where text goes vertically in the rect it is painted into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerticalAlign {
    /// The first line starts at the top.
    Top,
    /// A single line centers on its capital letters, or on its ascent when
    /// optical text centering is off. Several lines center their line boxes,
    /// so a rect exactly as tall as the text leaves it where it was laid out.
    #[default]
    Center,
    /// The last line ends at the bottom.
    Bottom,
}

/// Where text goes in the rect it is painted into.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextPlacement {
    pub horizontal: TextAlign,
    pub vertical: VerticalAlign,
}

impl TextPlacement {
    pub const fn new(horizontal: TextAlign, vertical: VerticalAlign) -> Self {
        Self {
            horizontal,
            vertical,
        }
    }

    /// At the start, centered vertically: labels in controls.
    pub const START: Self = Self::new(TextAlign::Start, VerticalAlign::Center);
    /// Centered both ways.
    pub const CENTER: Self = Self::new(TextAlign::Center, VerticalAlign::Center);
    /// At the end, centered vertically.
    pub const END: Self = Self::new(TextAlign::End, VerticalAlign::Center);
    /// From the top start corner: running text.
    pub const TOP_START: Self = Self::new(TextAlign::Start, VerticalAlign::Top);
}

impl From<TextAlign> for TextPlacement {
    /// Centered vertically.
    fn from(horizontal: TextAlign) -> Self {
        Self::new(horizontal, VerticalAlign::Center)
    }
}

/// Where along the rect a line or block goes, from 0 (left) to 1 (right).
pub(crate) const fn alignment_fraction(align: TextAlign) -> f32 {
    match align {
        TextAlign::Start | TextAlign::Left | TextAlign::Justified => 0.0,
        TextAlign::Center => 0.5,
        TextAlign::End | TextAlign::Right => 1.0,
    }
}

/// Lays text out: implemented by the measure and paint contexts, and by
/// [`LayoutContext`].
pub trait TextShaper {
    fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout>;
}

impl TextShaper for LayoutContext {
    fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
        self.layout_document(request)
    }
}

impl TextShaper for MeasureCtx {
    fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
        self.layout().layout_document(request)
    }
}

impl TextShaper for PaintCtx {
    fn shape_document(&self, request: TextLayoutRequest) -> sui_core::Result<TextLayout> {
        self.layout_text_document(request)
    }
}

/// Text wrapped to a width and laid out once, to measure and then paint.
///
/// Lay a paragraph out in `measure` and keep it on the widget. `paint` draws
/// the layout that was measured, so the painted lines always fit the size the
/// widget reported.
///
/// ```ignore
/// fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
///     self.paragraph = Paragraph::new(
///         ctx,
///         &self.text,
///         &self.style,
///         TextAlign::Start,
///         constraints.max.width,
///     );
///     constraints.clamp(self.paragraph.size())
/// }
///
/// fn paint(&self, ctx: &mut PaintCtx) {
///     self.paragraph.paint(ctx, ctx.bounds(), VerticalAlign::Top);
/// }
/// ```
#[derive(Debug, Clone, Default)]
pub struct Paragraph {
    text: String,
    style: TextStyle,
    align: TextAlign,
    layout: Option<TextLayout>,
    /// The width lines were aligned in.
    box_width: f32,
}

impl Paragraph {
    /// Lay out `text` wrapped to `max_width`, or unwrapped when it is
    /// infinite, with each line aligned by `align`.
    pub fn new(
        shaper: &(impl TextShaper + ?Sized),
        text: impl Into<String>,
        style: &TextStyle,
        align: TextAlign,
        max_width: f32,
    ) -> Self {
        let text = text.into();
        let width = if max_width.is_finite() {
            max_width.max(1.0)
        } else {
            f32::INFINITY
        };
        let request = |paragraph_align| {
            // Shape in white and paint in the style's color, so the layout is
            // shared across colors.
            let mut layout_style = style.clone();
            layout_style.color = Color::WHITE;
            let mut document = TextDocument::from_plain_text(text.clone(), layout_style);
            for paragraph in &mut document.paragraphs {
                paragraph.style.align = paragraph_align;
                paragraph.style.wrap = TextWrap::Word;
            }
            TextLayoutRequest::new(document).with_box_size(Size::new(width, f32::INFINITY))
        };
        // Lines laid out from the left edge are placed by their ink, which
        // keeps a single line optically aligned. Several lines aligned
        // otherwise are aligned by the layout itself.
        let mut layout = shaper.shape_document(request(TextAlign::Left)).ok();
        if !matches!(align, TextAlign::Left | TextAlign::Start)
            && layout
                .as_ref()
                .is_some_and(|layout| layout.lines().len() > 1)
        {
            layout = shaper.shape_document(request(align)).ok().or(layout);
        }
        let box_width = layout
            .as_ref()
            .map_or(0.0, |layout| layout.box_size().width);
        Self {
            text,
            style: style.clone(),
            align,
            layout,
            box_width,
        }
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    /// The size the text takes: its widest line by the height of its lines.
    pub fn size(&self) -> Size {
        self.layout.as_ref().map_or_else(
            || Size::new(0.0, self.style.line_height),
            |layout| {
                let measurement = layout.measurement();
                Size::new(measurement.width, measurement.height)
            },
        )
    }

    pub fn line_count(&self) -> usize {
        self.layout
            .as_ref()
            .map_or(0, |layout| layout.lines().len())
    }

    /// Paint into `rect`, placed vertically by `vertical` and horizontally by
    /// the alignment the paragraph was laid out with.
    pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, vertical: VerticalAlign) {
        self.paint_with_color(ctx, rect, vertical, self.style.color);
    }

    /// Paint like [`paint`](Self::paint), in `color` instead of the style's,
    /// for a color that can change without laying the text out again.
    pub fn paint_with_color(
        &self,
        ctx: &mut PaintCtx,
        rect: Rect,
        vertical: VerticalAlign,
        color: Color,
    ) {
        let Some(layout) = &self.layout else {
            if !self.text.is_empty() {
                let style = TextStyle {
                    color,
                    ..self.style.clone()
                };
                ctx.draw_text(rect, self.text.clone(), style);
            }
            return;
        };
        let origin = paragraph_origin(
            ctx,
            rect,
            layout,
            alignment_fraction(self.align),
            self.box_width,
            vertical,
        );
        ctx.draw_text_layout_with_color(origin, layout, color);
    }
}

/// Where to draw `layout` so it sits in `rect`. Lines laid out from the left
/// edge are placed by their ink, a single line centers on its capitals, and a
/// block of lines is placed by its line boxes. A block taller than `rect`
/// starts at its top, and in a rect with room for one line its first line is
/// placed like a single line.
pub(crate) fn paragraph_origin(
    ctx: &PaintCtx,
    rect: Rect,
    layout: &TextLayout,
    horizontal: f32,
    box_width: f32,
    vertical: VerticalAlign,
) -> Point {
    let measurement = layout.measurement();
    let lines = layout.lines();
    let left_aligned = lines.len() <= 1
        || layout
            .paragraphs()
            .iter()
            .all(|paragraph| matches!(paragraph.style.align, TextAlign::Left | TextAlign::Start));
    let x = if left_aligned {
        horizontal_placement(
            rect,
            measurement,
            horizontal,
            HorizontalTextAlignmentMode::Optical,
        )
        .origin_x
    } else {
        rect.x() + (rect.width() - box_width) * horizontal
    };
    // A rect with room for one line shows the first line, placed as if it
    // were alone, so a one-line slot places text the same whether it wraps
    // or not.
    let (height, lone_line) = match lines {
        [line] => (measurement.height, Some(line)),
        [first, second, ..] if rect.height() < second.rect.max_y() => {
            (first.rect.max_y(), Some(first))
        }
        _ => (measurement.height, None),
    };
    let room = (rect.height() - height).max(0.0);
    let y = match vertical {
        VerticalAlign::Top => rect.y(),
        VerticalAlign::Bottom => rect.y() + room,
        VerticalAlign::Center => match lone_line {
            Some(line) => {
                rect.y() + rect.height() * 0.5 - line.baseline - visual_center(ctx, measurement)
            }
            None => rect.y() + room * 0.5,
        },
    };
    Point::new(x, y)
}

/// Paint `text` in `rect`, wrapped to its width and placed by `placement`.
///
/// Pass a [`TextAlign`] for text centered vertically, or a
/// [`TextPlacement`] to place it at the top or bottom. To measure text
/// before painting it, lay it out as a [`Paragraph`] instead.
pub fn paint_text(
    ctx: &mut PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    placement: impl Into<TextPlacement>,
) {
    let placement = placement.into();
    let paragraph = Paragraph::new(ctx, text, style, placement.horizontal, rect.width());
    paragraph.paint(ctx, rect, placement.vertical);
}

/// Paint `text` on one line in `rect`, never wrapping: centered vertically on
/// its capital letters and placed horizontally by `align`.
pub fn paint_text_line(
    ctx: &mut PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    align: TextAlign,
) {
    let horizontal = alignment_fraction(align);
    let horizontal_mode = HorizontalTextAlignmentMode::Optical;
    if let Some(aligned) = aligned_text_layout_for_text_with_mode_and_wrap(
        ctx,
        rect,
        text,
        style,
        style.line_height,
        horizontal,
        horizontal_mode,
        TextWrap::NoWrap,
    ) {
        ctx.draw_text_layout_with_color(aligned.origin, &aligned.layout, aligned.color);
        return;
    }

    let fallback_rect = aligned_text_rect_for_text_with_mode(
        ctx,
        rect,
        text,
        style,
        style.line_height,
        horizontal,
        horizontal_mode,
    );
    ctx.draw_text(fallback_rect, text.to_string(), style.clone());
}

/// What a widget does with a label too wide for its space.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextOverflow {
    /// Paint the label as the widget always has, cut off at the edge of its
    /// space.
    #[default]
    Clip,
    /// Paint the label on one line, ending in "…" where it is cut, as an
    /// [`ElidedLine`] does.
    Ellipsis,
}

const ELLIPSIS: &str = "\u{2026}";

/// How far past its width a line may measure and still count as fitting, so
/// rounding doesn't elide text that fits.
const FIT_TOLERANCE: f32 = 0.01;

/// One line of text fitted to a width, ending in "…" when it is cut.
///
/// Text that fits is kept whole. Longer text keeps as much of its start as
/// fits, cut between characters, followed by "…", so it never ends in a
/// glyph cut in half. A width too narrow even for "…" keeps the first
/// character, which [`paint`](Self::paint) clips, so the text never
/// disappears without a trace. Of text with line breaks, the first line is
/// shown, followed by "…".
///
/// Fit the line in `measure` or `arrange` and keep it, or fit and paint it in
/// one go with [`paint_text_line_elided`]. Give accessibility the full text,
/// not the shown one.
#[derive(Debug, Clone, Default)]
pub struct ElidedLine {
    text: String,
    style: TextStyle,
    elided: bool,
    width: f32,
}

impl ElidedLine {
    /// Fit `text` on one line `max_width` wide. An infinite width keeps the
    /// whole first line.
    pub fn new(
        shaper: &(impl TextShaper + ?Sized),
        text: &str,
        style: &TextStyle,
        max_width: f32,
    ) -> Self {
        let line_end = text.find(['\n', '\r']);
        let line = &text[..line_end.unwrap_or(text.len())];
        let more_lines = line_end.is_some();
        let fitted = |text: String, elided: bool, width: f32| Self {
            text,
            style: style.clone(),
            elided,
            width,
        };
        let fits = |width: f32| width <= max_width + FIT_TOLERANCE;
        let Some(full) = single_line_layout(shaper, line, style) else {
            // Without a layout nothing can be measured, so show the line.
            return fitted(line.to_string(), more_lines, 0.0);
        };
        let full_width = full.measurement().width;
        if !more_lines && (!max_width.is_finite() || fits(full_width)) {
            return fitted(line.to_string(), false, full_width);
        }
        let width_of = |text: &str| {
            single_line_layout(shaper, text, style).map(|layout| layout.measurement().width)
        };
        let ellipsis_width = width_of(ELLIPSIS).unwrap_or(0.0);

        // The width of each character, from the clusters of the whole line,
        // to guess how many fit before the "…".
        let boundaries = line
            .grapheme_indices(true)
            .map(|(start, _)| start)
            .chain([line.len()])
            .collect::<Vec<_>>();
        let mut widths = vec![0.0_f32; boundaries.len() - 1];
        for cluster in full.clusters() {
            let index = boundaries
                .partition_point(|&boundary| boundary <= cluster.byte_range.start)
                .saturating_sub(1);
            if let Some(width) = widths.get_mut(index) {
                *width += cluster.rect.width();
            }
        }
        let budget = max_width - ellipsis_width;
        let mut kept = 0;
        let mut kept_width = 0.0;
        for width in &widths {
            if kept_width + width > budget + FIT_TOLERANCE {
                break;
            }
            kept_width += width;
            kept += 1;
        }
        if !more_lines {
            // The whole line didn't fit, so at least its last character goes.
            kept = kept.min(widths.len().saturating_sub(1));
        }

        // Kerning and shaping across the cut can make the guess too wide, so
        // measure it and give up characters until it fits.
        while kept > 0 {
            let start = line[..boundaries[kept]].trim_end();
            if start.is_empty() {
                break;
            }
            let shown = format!("{start}{ELLIPSIS}");
            match width_of(&shown) {
                Some(width) if fits(width) => return fitted(shown, true, width),
                Some(_) => kept -= 1,
                None => return fitted(shown, true, 0.0),
            }
        }
        if fits(ellipsis_width) || line.is_empty() {
            return fitted(ELLIPSIS.to_string(), true, ellipsis_width);
        }
        let first = line.graphemes(true).next().unwrap_or(line);
        fitted(first.to_string(), true, width_of(first).unwrap_or(0.0))
    }

    /// The text shown: all of it, or its start followed by "…".
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Whether some of the text is not shown.
    pub fn is_elided(&self) -> bool {
        self.elided
    }

    /// The width the shown text takes.
    pub fn width(&self) -> f32 {
        self.width
    }

    /// Paint the line in `rect` as [`paint_text_line`] does, clipped to the
    /// rect's width when even the "…" didn't fit.
    pub fn paint(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign) {
        self.paint_with_color(ctx, rect, align, self.style.color);
    }

    /// Paint like [`paint`](Self::paint), in `color` instead of the style's.
    pub fn paint_with_color(&self, ctx: &mut PaintCtx, rect: Rect, align: TextAlign, color: Color) {
        let style = TextStyle {
            color,
            ..self.style.clone()
        };
        let overflows = self.width > rect.width() + FIT_TOLERANCE;
        if overflows {
            // Clip the sides only, so tall glyphs in a tight rect keep their
            // ink.
            let slack = style.line_height.max(rect.height());
            ctx.push_clip_rect(Rect::new(
                rect.x(),
                rect.y() - slack,
                rect.width().max(0.0),
                rect.height() + slack * 2.0,
            ));
        }
        paint_text_line(ctx, rect, &self.text, &style, align);
        if overflows {
            ctx.pop_clip();
        }
    }
}

/// Paint `text` on one line in `rect` as [`paint_text_line`] does, fitted to
/// the rect's width as an [`ElidedLine`]: cut text ends in "…" rather than in
/// a glyph cut in half.
pub fn paint_text_line_elided(
    ctx: &mut PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    align: TextAlign,
) {
    ElidedLine::new(ctx, text, style, rect.width()).paint(ctx, rect, align);
}

/// `text` laid out on one unwrapped line, to measure.
fn single_line_layout(
    shaper: &(impl TextShaper + ?Sized),
    text: &str,
    style: &TextStyle,
) -> Option<TextLayout> {
    let mut layout_style = style.clone();
    layout_style.color = Color::WHITE;
    let mut document = TextDocument::from_plain_text(text.to_string(), layout_style);
    for paragraph in &mut document.paragraphs {
        paragraph.style.align = TextAlign::Left;
        paragraph.style.wrap = TextWrap::NoWrap;
    }
    shaper.shape_document(TextLayoutRequest::new(document)).ok()
}

pub(crate) fn paint_aligned_text_contained(
    ctx: &mut PaintCtx,
    rect: Rect,
    text: &str,
    style: &TextStyle,
    line_height: f32,
    horizontal_alignment: f32,
) {
    let horizontal_mode = HorizontalTextAlignmentMode::Optical;
    if let Some(aligned) = aligned_text_layout_for_text_with_mode(
        ctx,
        rect,
        text,
        style,
        line_height,
        horizontal_alignment,
        horizontal_mode,
    ) {
        let painted = painted_layout_rect(aligned.origin, &aligned.layout);
        let offset = containment_offset(painted, rect);
        ctx.draw_text_layout_with_color(aligned.origin + offset, &aligned.layout, aligned.color);
        return;
    }

    let fallback_rect = aligned_text_rect_for_text_with_mode(
        ctx,
        rect,
        text,
        style,
        line_height,
        horizontal_alignment,
        horizontal_mode,
    );
    ctx.draw_text(
        fallback_rect.translate(containment_offset(fallback_rect, rect)),
        text.to_string(),
        style.clone(),
    );
}

fn painted_layout_rect(origin: Point, layout: &TextLayout) -> Rect {
    let measurement = layout.measurement();
    let bounds = measurement.bounds;
    let width = if bounds.width().is_finite() && bounds.width() > 0.0 {
        bounds.width()
    } else {
        measurement.width
    };
    Rect::new(
        origin.x + bounds.x(),
        origin.y + ((layout.box_size().height - measurement.height).max(0.0) * 0.5),
        width,
        layout.style().line_height.max(measurement.height),
    )
}

fn containment_offset(inner: Rect, outer: Rect) -> sui_core::Vector {
    fn axis_offset(inner_min: f32, inner_max: f32, outer_min: f32, outer_max: f32) -> f32 {
        let inner_size = inner_max - inner_min;
        let outer_size = outer_max - outer_min;
        if inner_size > outer_size || inner_min < outer_min {
            outer_min - inner_min
        } else if inner_max > outer_max {
            outer_max - inner_max
        } else {
            0.0
        }
    }

    sui_core::Vector::new(
        axis_offset(inner.x(), inner.max_x(), outer.x(), outer.max_x()),
        axis_offset(inner.y(), inner.max_y(), outer.y(), outer.max_y()),
    )
}

/// Paint one unwrapped line using SUI's shared optical baseline alignment path.
/// Greedy word-wrap `text` to `max_width`, using `measure` for run widths.
///
/// Explicit newlines are preserved. Words longer than `max_width` are kept on
/// their own line rather than split, which matches common UI metadata wrapping.
pub fn wrap_text_lines(
    text: &str,
    max_width: f32,
    mut measure: impl FnMut(&str) -> f32,
) -> Vec<String> {
    let mut lines = Vec::new();
    let space_width = measure(" ");

    for paragraph in text.split('\n') {
        if paragraph.is_empty() {
            lines.push(String::new());
            continue;
        }

        let mut current = String::new();
        let mut current_width = 0.0_f32;
        for word in paragraph.split(' ') {
            let word_width = measure(word);
            if current.is_empty() {
                current.push_str(word);
                current_width = word_width;
            } else if current_width + space_width + word_width <= max_width {
                current.push(' ');
                current.push_str(word);
                current_width += space_width + word_width;
            } else {
                lines.push(std::mem::take(&mut current));
                current.push_str(word);
                current_width = word_width;
            }
        }
        lines.push(current);
    }

    lines
}

fn paragraph_alignment(
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
) -> TextAlign {
    if horizontal_mode == HorizontalTextAlignmentMode::Optical {
        return TextAlign::Left;
    }

    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
    if horizontal_alignment <= 0.0 {
        TextAlign::Left
    } else if horizontal_alignment >= 1.0 {
        TextAlign::Right
    } else {
        TextAlign::Center
    }
}

pub(crate) fn aligned_text_rect_for_layout(
    ctx: &PaintCtx,
    rect: Rect,
    layout: &TextLayout,
    line_height: f32,
    horizontal_alignment: f32,
) -> Rect {
    aligned_text_rect_for_layout_with_mode(
        ctx,
        rect,
        layout,
        line_height,
        horizontal_alignment,
        HorizontalTextAlignmentMode::Advance,
    )
}

pub(crate) fn aligned_text_rect_for_layout_with_mode(
    ctx: &PaintCtx,
    rect: Rect,
    layout: &TextLayout,
    line_height: f32,
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
) -> Rect {
    let measurement = layout.measurement();
    let placement = horizontal_placement(rect, measurement, horizontal_alignment, horizontal_mode);
    let height = line_height.max(measurement.height).min(rect.height());
    let y = layout
        .lines()
        .first()
        .map(|line| {
            rect.y() + (rect.height() * 0.5) - line.baseline - visual_center(ctx, measurement)
        })
        .unwrap_or_else(|| vertically_centered_text_rect_y(ctx, rect, measurement, height));

    Rect::new(placement.rect_x, y, placement.rect_width, height)
}

fn horizontal_placement(
    rect: Rect,
    measurement: TextMeasurement,
    horizontal_alignment: f32,
    horizontal_mode: HorizontalTextAlignmentMode,
) -> HorizontalPlacement {
    let horizontal_alignment = horizontal_alignment.clamp(0.0, 1.0);
    let (width, origin_shift) = match horizontal_mode {
        HorizontalTextAlignmentMode::Advance => (measurement.width, 0.0),
        HorizontalTextAlignmentMode::Optical => {
            let bounds = measurement.bounds;
            if bounds.width().is_finite() && bounds.width() > 0.0 {
                (bounds.width(), -bounds.x())
            } else {
                (measurement.width, 0.0)
            }
        }
    };
    let rect_width = width.min(rect.width()).max(0.0);
    let rect_x = rect.x() + ((rect.width() - rect_width).max(0.0) * horizontal_alignment);

    HorizontalPlacement {
        rect_x,
        rect_width,
        origin_x: rect_x + origin_shift,
    }
}

pub(crate) fn vertically_centered_text_rect_y(
    ctx: &PaintCtx,
    rect: Rect,
    measurement: TextMeasurement,
    height: f32,
) -> f32 {
    let visual_center = visual_center(ctx, measurement);
    let baseline = rect.y() + (rect.height() * 0.5) - visual_center;
    let leading_above = ((height - (measurement.ascent + measurement.descent)).max(0.0)) * 0.5;

    baseline - measurement.ascent - leading_above
}

fn visual_center(ctx: &PaintCtx, measurement: TextMeasurement) -> f32 {
    let optical_centering = window_render_options(ctx.window_id())
        .map(|options| options.optical_vertical_text_alignment_enabled)
        .unwrap_or(true);
    let top = if optical_centering {
        -measurement.cap_height.unwrap_or(measurement.ascent)
    } else {
        -measurement.ascent
    };
    let bottom = if optical_centering {
        measurement.descent * 0.5
    } else {
        measurement.descent
    };
    (top + bottom) * 0.5
}

#[cfg(test)]
mod tests {
    use super::wrap_text_lines;
    use std::{cell::RefCell, rc::Rc};

    use sui_core::{Color, Point, Rect, Size};
    use sui_layout::Constraints;
    use sui_runtime::{Application, MeasureCtx, PaintCtx, Widget, WindowBuilder};
    use sui_scene::SceneCommand;
    use sui_text::{TextAlign, TextStyle};

    use super::{
        ELLIPSIS, ElidedLine, HorizontalTextAlignmentMode, Paragraph, TextPlacement, VerticalAlign,
        aligned_text_layout_for_text_with_mode, paint_text, paint_text_line_elided,
    };
    use unicode_segmentation::UnicodeSegmentation;

    type Paint = Box<dyn Fn(&mut PaintCtx)>;
    type Measure = Box<dyn Fn(&mut MeasureCtx)>;

    /// A widget that runs `measure` and `paint` callbacks in a 400 × 600 window.
    struct Probe {
        measure: Option<Measure>,
        paint: Paint,
    }

    impl Widget for Probe {
        fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
            if let Some(measure) = &self.measure {
                measure(ctx);
            }
            constraints.clamp(Size::new(400.0, 600.0))
        }

        fn paint(&self, ctx: &mut PaintCtx) {
            (self.paint)(ctx);
        }
    }

    /// Where each drawn text ended up: its text, its first baseline, the x of
    /// its layout origin, and its size.
    #[derive(Debug, Clone, PartialEq)]
    struct Drawn {
        text: String,
        origin: Point,
        first_baseline: f32,
        size: Size,
        line_starts: Vec<f32>,
    }

    fn render(probe: Probe) -> Vec<Drawn> {
        let mut runtime = Application::new()
            .window(WindowBuilder::new().title("Text").root(probe))
            .build()
            .unwrap();
        let window_id = runtime.window_ids()[0];
        let output = runtime.render(window_id).unwrap();
        let registry = output.frame.text_layout_registry.as_ref();
        let mut drawn = Vec::new();
        output.frame.scene.visit_commands(&mut |command| {
            if let SceneCommand::DrawShapedText(text) = command
                && let Some(layout) = text.resolve(registry)
            {
                drawn.push(Drawn {
                    text: layout.text().to_string(),
                    origin: text.origin,
                    first_baseline: text.origin.y + layout.lines()[0].baseline,
                    size: Size::new(layout.measurement().width, layout.measurement().height),
                    line_starts: layout.lines().iter().map(|line| line.rect.x()).collect(),
                });
            }
        });
        drawn
    }

    fn style() -> TextStyle {
        TextStyle::new(Color::BLACK)
    }

    const PARAGRAPH: &str = "several words that wrap onto more than one line of text here";

    #[test]
    fn a_single_line_is_placed_as_before() {
        // The previous single-line path, kept for text fields and buttons,
        // against the new one: same baseline, same optical horizontal place.
        for (align, fraction) in [
            (TextAlign::Start, 0.0),
            (TextAlign::Center, 0.5),
            (TextAlign::End, 1.0),
        ] {
            let drawn = render(Probe {
                measure: None,
                paint: Box::new(move |ctx| {
                    let rect = Rect::new(20.0, 30.0, 300.0, 44.0);
                    paint_text(ctx, rect, "Label", &style(), align);
                    let before = aligned_text_layout_for_text_with_mode(
                        ctx,
                        rect.translate(sui_core::Vector::new(0.0, 100.0)),
                        "Label",
                        &style(),
                        style().line_height,
                        fraction,
                        HorizontalTextAlignmentMode::Optical,
                    )
                    .unwrap();
                    ctx.draw_text_layout_with_color(before.origin, &before.layout, Color::BLACK);
                }),
            });
            let [now, before] = &drawn[..] else {
                panic!("two texts are drawn: {drawn:?}");
            };
            assert!(
                (now.origin.x - before.origin.x).abs() < 0.001,
                "{align:?}: {now:?} vs {before:?}"
            );
            assert!(
                (now.first_baseline + 100.0 - before.first_baseline).abs() < 0.001,
                "{align:?}: {now:?} vs {before:?}"
            );
        }
    }

    #[test]
    fn several_lines_are_placed_as_a_block() {
        let rect = Rect::new(10.0, 20.0, 160.0, 300.0);
        let placed = |vertical| {
            render(Probe {
                measure: None,
                paint: Box::new(move |ctx| {
                    paint_text(
                        ctx,
                        rect,
                        PARAGRAPH,
                        &style(),
                        TextPlacement::new(TextAlign::Start, vertical),
                    );
                }),
            })
            .remove(0)
        };

        let top = placed(VerticalAlign::Top);
        assert!(top.line_starts.len() > 2, "{top:?}");
        let height = top.size.height;
        assert!((top.origin.y - rect.y()).abs() < 0.001, "{top:?}");
        let center = placed(VerticalAlign::Center);
        assert!(
            (center.origin.y - (rect.y() + (rect.height() - height) * 0.5)).abs() < 0.001,
            "{center:?}"
        );
        let bottom = placed(VerticalAlign::Bottom);
        assert!(
            (bottom.origin.y - (rect.max_y() - height)).abs() < 0.001,
            "{bottom:?}"
        );

        // A block taller than its rect starts at the top instead of rising
        // above it.
        let shorter = Rect::new(10.0, 20.0, 160.0, height * 0.9);
        let overflowing = render(Probe {
            measure: None,
            paint: Box::new(move |ctx| {
                paint_text(ctx, shorter, PARAGRAPH, &style(), TextAlign::Start);
            }),
        })
        .remove(0);
        assert!(
            (overflowing.origin.y - shorter.y()).abs() < 0.001,
            "{overflowing:?}"
        );

        // In a rect with room for one line, the first line sits where it
        // would on its own.
        let one_line = Rect::new(10.0, 20.0, 160.0, 12.0);
        let drawn = render(Probe {
            measure: None,
            paint: Box::new(move |ctx| {
                paint_text(ctx, one_line, PARAGRAPH, &style(), TextAlign::Start);
                paint_text(ctx, one_line, "several", &style(), TextAlign::Start);
            }),
        });
        let [wrapped, alone] = &drawn[..] else {
            panic!("two texts are drawn: {drawn:?}");
        };
        assert!(wrapped.line_starts.len() > 1, "{wrapped:?}");
        assert!(
            (wrapped.first_baseline - alone.first_baseline).abs() < 0.001,
            "{wrapped:?} vs {alone:?}"
        );
    }

    #[test]
    fn centered_lines_are_centered_one_by_one() {
        let drawn = render(Probe {
            measure: None,
            paint: Box::new(|ctx| {
                paint_text(
                    ctx,
                    Rect::new(0.0, 0.0, 160.0, 300.0),
                    PARAGRAPH,
                    &style(),
                    TextAlign::Center,
                );
            }),
        })
        .remove(0);
        let first = drawn.line_starts[0];
        assert!(
            drawn
                .line_starts
                .iter()
                .any(|start| (start - first).abs() > 1.0),
            "lines of different widths start at different places: {drawn:?}"
        );
    }

    #[test]
    fn a_paragraph_paints_the_layout_it_measured() {
        let measured = Rc::new(RefCell::new(Paragraph::default()));
        let laid_out = Rc::clone(&measured);
        let painted = Rc::clone(&measured);
        let drawn = render(Probe {
            measure: Some(Box::new(move |ctx| {
                *laid_out.borrow_mut() =
                    Paragraph::new(ctx, PARAGRAPH, &style(), TextAlign::Start, 160.0);
            })),
            paint: Box::new(move |ctx| {
                let paragraph = painted.borrow();
                let rect = Rect::from_origin_size(Point::new(5.0, 7.0), paragraph.size());
                paragraph.paint(ctx, rect, VerticalAlign::Top);
            }),
        })
        .remove(0);

        let paragraph = measured.borrow();
        assert!(paragraph.line_count() > 2);
        assert_eq!(drawn.text, PARAGRAPH);
        assert_eq!(drawn.size, paragraph.size());
        assert!((drawn.origin.y - 7.0).abs() < 0.001, "{drawn:?}");
    }

    /// Fit each text in each width during measurement.
    fn fit(texts: &[&str], widths: &[f32]) -> Vec<(String, f32, ElidedLine)> {
        let fitted = Rc::new(RefCell::new(Vec::new()));
        let results = Rc::clone(&fitted);
        let texts = texts
            .iter()
            .map(|text| text.to_string())
            .collect::<Vec<_>>();
        let widths = widths.to_vec();
        render(Probe {
            measure: Some(Box::new(move |ctx| {
                let mut results = results.borrow_mut();
                results.clear();
                for text in &texts {
                    for &width in &widths {
                        let line = ElidedLine::new(ctx, text, &style(), width);
                        results.push((text.clone(), width, line));
                    }
                }
            })),
            paint: Box::new(|_| {}),
        });
        fitted.take()
    }

    fn full_width(text: &str) -> f32 {
        fit(&[text], &[f32::INFINITY])[0].2.width()
    }

    #[test]
    fn an_elided_line_keeps_text_that_fits() {
        let text = "Channels";
        let width = full_width(text);
        for max_width in [width, width + 40.0, f32::INFINITY] {
            let (_, _, line) = &fit(&[text], &[max_width])[0];
            assert_eq!(line.text(), text);
            assert!(!line.is_elided());
            assert!((line.width() - width).abs() < 0.001, "{line:?}");
        }
    }

    #[test]
    fn an_elided_line_cuts_between_characters_and_ends_in_an_ellipsis() {
        let texts = [
            "The user asks to reply exactly V5_OK",
            "Cafe\u{301} cre\u{300}me bru\u{302}le\u{301}e",
            "\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467} family \u{1F44D}\u{1F3FD} ok",
            "\u{5E9}\u{5DC}\u{5D5}\u{5DD} \u{5E2}\u{5D5}\u{5DC}\u{5DD} \u{5D8}\u{5D5}\u{5D1}",
            "Mixed \u{5E2}\u{5D1}\u{5E8}\u{5D9}\u{5EA} and English text",
        ];
        let ellipsis = full_width(ELLIPSIS);
        let widths = (0..=60).map(|step| step as f32 * 6.0).collect::<Vec<_>>();
        for (text, max_width, line) in fit(&texts, &widths) {
            let width = full_width(&text);
            if !line.is_elided() {
                assert!(
                    width <= max_width + 0.01,
                    "{text:?} in {max_width}: {line:?}"
                );
                assert_eq!(line.text(), text);
                continue;
            }
            assert!(width > max_width, "{text:?} in {max_width} fits: {line:?}");
            if max_width < ellipsis {
                let first = text.graphemes(true).next().unwrap();
                assert_eq!(line.text(), first, "{text:?} in {max_width}");
                continue;
            }
            assert!(
                line.width() <= max_width + 0.01,
                "{text:?} in {max_width}: {line:?}"
            );
            let start = line
                .text()
                .strip_suffix(ELLIPSIS)
                .unwrap_or_else(|| panic!("{text:?} in {max_width}: {line:?}"));
            assert!(text.starts_with(start), "{text:?} in {max_width}: {line:?}");
            assert!(
                text.grapheme_indices(true)
                    .any(|(index, _)| index == start.len())
                    || start.is_empty(),
                "{text:?} in {max_width} is cut inside a character: {line:?}"
            );
            assert_eq!(start, start.trim_end(), "{text:?} in {max_width}: {line:?}");
        }
    }

    #[test]
    fn an_elided_line_keeps_as_many_characters_as_fit() {
        let text = "abcdefghijklmnopqrstuvwxyz";
        let width = full_width(text);
        for (_, max_width, line) in fit(&[text], &[width * 0.3, width * 0.6, width - 1.0]) {
            let kept = line.text().strip_suffix(ELLIPSIS).unwrap();
            let one_more = format!("{}{ELLIPSIS}", &text[..kept.len() + 1]);
            assert!(
                full_width(&one_more) > max_width,
                "one more character would have fit in {max_width}: {line:?}"
            );
        }
    }

    #[test]
    fn an_elided_line_shows_the_first_line_of_several() {
        let (_, _, line) = &fit(&["First line\nSecond line"], &[f32::INFINITY])[0];
        assert_eq!(line.text(), "First line\u{2026}");
        assert!(line.is_elided());
    }

    #[test]
    fn a_line_too_narrow_for_an_ellipsis_shows_its_first_character_clipped() {
        let rect = Rect::new(20.0, 30.0, 2.0, 20.0);
        let clips = Rc::new(RefCell::new(Vec::new()));
        let mut runtime = Application::new()
            .window(WindowBuilder::new().title("Text").root(Probe {
                measure: None,
                paint: Box::new(move |ctx| {
                    paint_text_line_elided(ctx, rect, "Channels", &style(), TextAlign::Start);
                }),
            }))
            .build()
            .unwrap();
        let window_id = runtime.window_ids()[0];
        let output = runtime.render(window_id).unwrap();
        let registry = output.frame.text_layout_registry.as_ref();
        let mut stack = Vec::new();
        output
            .frame
            .scene
            .visit_commands(&mut |command| match command {
                SceneCommand::PushClip { rect } => stack.push(*rect),
                SceneCommand::PopClip => {
                    stack.pop();
                }
                SceneCommand::DrawShapedText(text) => {
                    let layout = text.resolve(registry).unwrap();
                    clips
                        .borrow_mut()
                        .push((layout.text().to_string(), stack.last().copied()));
                }
                _ => {}
            });
        let [(text, Some(clip))] = &clips.borrow()[..] else {
            panic!("one clipped text is drawn: {:?}", clips.borrow());
        };
        assert_eq!(text, "C");
        assert_eq!((clip.x(), clip.width()), (rect.x(), rect.width()));
        assert!(
            clip.y() < rect.y() && clip.max_y() > rect.max_y(),
            "{clip:?}"
        );
    }

    #[test]
    fn wrap_text_lines_preserves_newlines_and_keeps_long_words() {
        let lines = wrap_text_lines("alpha beta\nsuperlongword gamma", 10.0, |text| {
            text.chars().count() as f32
        });

        assert_eq!(
            lines,
            vec![
                "alpha beta".to_string(),
                "superlongword".to_string(),
                "gamma".to_string(),
            ]
        );
    }
}