xrack-layout 0.8.0

Layout, hit testing, and input routing for XRack UI
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
use crate::{
    Point, Size, TextMeasurer, font_size,
    text_area::{fitting_prefix, grapheme_boundaries, paragraphs},
};
use std::{borrow::Cow, ops::Range};
use unicode_bidi::{Direction, get_base_direction};
use unicode_segmentation::UnicodeSegmentation;
use xrack_runtime::{
    LayoutDirection, Node, TextHorizontalAlignment, TextOverflow, TextVerticalAlignment, TextWrap,
    Value,
};

/// Resolves logical alignment using the nearest layout declaration or text direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub struct TextAlignment {
    mode: TextHorizontalAlignment,
    direction: Option<LayoutDirection>,
}

impl TextAlignment {
    pub(crate) fn from_node(
        node: &Node,
        direction: Option<LayoutDirection>,
        default: TextHorizontalAlignment,
    ) -> Self {
        let mode = match node.properties.get("horizontal-alignment") {
            Some(Value::TextHorizontalAlignment(alignment)) => *alignment,
            _ => default,
        };
        Self { mode, direction }
    }

    pub fn editor(node: &Node, direction: Option<LayoutDirection>) -> Self {
        let default = if direction.is_some() {
            TextHorizontalAlignment::Start
        } else {
            TextHorizontalAlignment::Left
        };
        Self::from_node(node, direction, default)
    }

    pub(crate) fn has_offset(self) -> bool {
        self.mode != TextHorizontalAlignment::Left
    }

    pub fn offset(self, space: f32, natural_rtl: bool) -> f32 {
        use TextHorizontalAlignment as Horizontal;
        let rtl = self.direction.map_or(natural_rtl, |direction| {
            direction == LayoutDirection::RightToLeft
        });
        match self.mode {
            Horizontal::Center => space * 0.5,
            Horizontal::Right => space,
            Horizontal::Start if rtl => space,
            Horizontal::End if !rtl => space,
            _ => 0.0,
        }
    }

    /// Reserve one pixel for the caret and reveal it when a line overflows.
    pub fn single_line_offset(
        self,
        width: f32,
        advance: f32,
        rtl: bool,
        caret: Option<f32>,
    ) -> f32 {
        let free = width - advance - 1.0;
        if free < 0.0
            && let Some(caret) = caret
        {
            -(caret + 1.0 - width).max(0.0)
        } else {
            self.offset(free, rtl)
        }
    }

    #[doc(hidden)]
    pub fn single_line_view_offset(
        self,
        width: f32,
        advance: f32,
        rtl: bool,
        caret: Option<f32>,
        drag_scroll: Option<f32>,
    ) -> f32 {
        let overflow = advance + 1.0 - width;
        if let Some(scroll) = drag_scroll
            && overflow > 0.0
        {
            -scroll.clamp(0.0, overflow)
        } else {
            self.single_line_offset(width, advance, rtl, caret)
        }
    }
}

pub fn uses_label_layout(node: &Node) -> bool {
    matches!(node.kind, "Label" | "StyledText")
        || node.kind == "Text"
            && [
                "horizontal-alignment",
                "vertical-alignment",
                "overflow",
                "max-lines",
                "wrap",
            ]
            .iter()
            .any(|key| node.properties.contains_key(key))
}

fn wrap(node: &Node) -> TextWrap {
    match node.properties.get("wrap") {
        Some(Value::TextWrap(wrap)) => *wrap,
        _ if node.kind == "Label" => TextWrap::NoWrap,
        _ => TextWrap::WordWrap,
    }
}

pub(crate) fn reflows_at_width(node: &Node) -> bool {
    uses_label_layout(node) && wrap(node) != TextWrap::NoWrap
}

pub(crate) fn flexible_width(node: &Node) -> bool {
    reflows_at_width(node)
        || uses_label_layout(node)
            && node.properties.get("overflow") == Some(&Value::TextOverflow(TextOverflow::Elide))
}

pub struct LabelLine<'a> {
    pub text: Cow<'a, str>,
    pub origin: Point,
}

/// The same line plan is used for intrinsic measurement and GPU painting.
pub struct LabelLayout<'a> {
    pub size: Size,
    pub lines: Vec<LabelLine<'a>>,
}

impl<'a> LabelLayout<'a> {
    pub fn new(node: &'a Node, available: Size, advance: impl FnMut(&str) -> f32) -> Self {
        Self::with_font_size(node, available, font_size(node), advance)
    }

    pub fn with_font_size(
        node: &'a Node,
        available: Size,
        size: f32,
        advance: impl FnMut(&str) -> f32,
    ) -> Self {
        Self::in_direction(node, available, size, node.layout_direction(), advance)
    }

    pub fn in_direction(
        node: &'a Node,
        available: Size,
        size: f32,
        direction: Option<LayoutDirection>,
        mut advance: impl FnMut(&str) -> f32,
    ) -> Self {
        let text = node.text("text").unwrap_or("");
        let plan = LabelPlan::in_direction(node, available, size, direction, |range, ellipsis| {
            advance(&line_text(text, range, ellipsis))
        });
        Self {
            size: plan.size,
            lines: plan
                .lines
                .into_iter()
                .map(|line| LabelLine {
                    text: line_text(text, line.range, line.ellipsis),
                    origin: line.origin,
                })
                .collect(),
        }
    }
}

fn line_text(text: &str, range: Range<usize>, ellipsis: bool) -> Cow<'_, str> {
    if ellipsis {
        let mut shown = text[range].to_owned();
        shown.push('…');
        Cow::Owned(shown)
    } else {
        Cow::Borrowed(&text[range])
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct PlannedLabelLine {
    pub range: Range<usize>,
    pub ellipsis: bool,
    pub origin: Point,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct TitleLayout {
    pub height: f32,
    pub font_size: f32,
    pub lines: Vec<PlannedLabelLine>,
}

impl PlannedLabelLine {
    pub fn text<'a>(&self, source: &'a str) -> Cow<'a, str> {
        line_text(source, self.range.clone(), self.ellipsis)
    }
}

struct LabelStyle {
    horizontal: TextAlignment,
    vertical: TextVerticalAlignment,
    wrap: TextWrap,
    elide: bool,
    max_lines: usize,
}

/// Text ranges shared by plain and styled labels, independent of the shaping backend.
pub struct LabelPlan {
    pub size: Size,
    pub lines: Vec<PlannedLabelLine>,
}

impl LabelPlan {
    pub fn with_font_size(
        node: &Node,
        available: Size,
        size: f32,
        advance: impl FnMut(Range<usize>, bool) -> f32,
    ) -> Self {
        Self::in_direction(node, available, size, node.layout_direction(), advance)
    }

    fn in_direction(
        node: &Node,
        available: Size,
        size: f32,
        direction: Option<LayoutDirection>,
        advance: impl FnMut(Range<usize>, bool) -> f32,
    ) -> Self {
        use TextHorizontalAlignment as Horizontal;
        use TextVerticalAlignment as Vertical;

        let text = node.text("text").unwrap_or("");
        let elide =
            node.properties.get("overflow") == Some(&Value::TextOverflow(TextOverflow::Elide));
        let default = if matches!(node.kind, "Label" | "StyledText") {
            Horizontal::Start
        } else {
            Horizontal::Left
        };
        let horizontal = TextAlignment::from_node(node, direction, default);
        let vertical = match node.properties.get("vertical-alignment") {
            Some(Value::TextVerticalAlignment(alignment)) => *alignment,
            _ => Vertical::Top,
        };
        let max_lines = node
            .int("max-lines")
            .and_then(|count| usize::try_from(count).ok())
            .filter(|&count| count > 0)
            .unwrap_or(usize::MAX);
        Self::plan(
            text,
            available,
            size,
            LabelStyle {
                horizontal,
                vertical,
                wrap: wrap(node),
                elide,
                max_lines,
            },
            advance,
        )
    }

    pub(crate) fn leading_title(
        node: &Node,
        title: &str,
        width: f32,
        size: f32,
        direction: LayoutDirection,
        max_lines: usize,
        text: &mut impl TextMeasurer,
    ) -> Self {
        let preferred_size = text.font_size(node);
        Self::plan(
            title,
            Size::new(width, f32::INFINITY),
            size,
            LabelStyle {
                horizontal: TextAlignment {
                    mode: TextHorizontalAlignment::Start,
                    direction: Some(direction),
                },
                vertical: TextVerticalAlignment::Top,
                wrap: TextWrap::WordWrap,
                elide: true,
                max_lines,
            },
            |range, ellipsis| {
                let value = line_text(title, range, ellipsis);
                if size == preferred_size {
                    text.measure_node(node, &value, f32::MAX).width
                } else {
                    text.measure_node_at_size(node, &value, size, f32::MAX)
                        .width
                }
            },
        )
    }

    fn plan(
        text: &str,
        available: Size,
        size: f32,
        style: LabelStyle,
        mut advance: impl FnMut(Range<usize>, bool) -> f32,
    ) -> Self {
        use TextHorizontalAlignment as Horizontal;
        use TextVerticalAlignment as Vertical;

        let LabelStyle {
            horizontal,
            vertical,
            wrap,
            elide,
            max_lines,
        } = style;
        let line_height = size * 1.4;
        let by_height = available.height / line_height;
        let by_height = if elide {
            // The measured height is a rounded product of the line count and height.
            by_height.next_up().floor()
        } else {
            by_height.ceil()
        } as usize;
        let limit = max_lines.min(by_height);
        if limit == 0 || available.width <= 0.0 {
            return Self {
                size: Size::default(),
                lines: Vec::new(),
            };
        }

        let mut raw = Vec::new();
        'paragraphs: for range in paragraphs(text) {
            let content = &text[range.clone()];
            let rtl = horizontal.direction.is_none()
                && matches!(horizontal.mode, Horizontal::Start | Horizontal::End)
                && get_base_direction(content) == Direction::Rtl;
            if wrap == TextWrap::NoWrap || content.is_empty() {
                raw.push((range, rtl));
                if raw.len() > limit {
                    break;
                }
                continue;
            }
            let graphemes = grapheme_boundaries(content);
            let words = if wrap == TextWrap::WordWrap {
                content
                    .split_word_bound_indices()
                    .map(|(start, word)| start + word.len())
                    .collect::<Vec<_>>()
            } else {
                Vec::new()
            };
            let last = graphemes.len() - 1;
            let mut start = 0;
            while start < last {
                let fit = fitting_prefix(start, last, |index| {
                    let from = range.start + graphemes[start];
                    let to = range.start + graphemes[index];
                    advance(from..to, false) <= available.width
                })
                .max(start + 1);
                let word_end = words.partition_point(|&byte| byte <= graphemes[fit]);
                let next = word_end
                    .checked_sub(1)
                    .and_then(|index| graphemes.binary_search(&words[index]).ok())
                    .filter(|&index| index > start)
                    .unwrap_or(fit);
                let from = range.start + graphemes[start];
                let to = range.start + graphemes[next];
                raw.push((trim_trailing_space(text, from..to), rtl));
                if raw.len() > limit {
                    break 'paragraphs;
                }
                start = next;
                while start < last
                    && content[graphemes[start]..graphemes[start + 1]]
                        .chars()
                        .all(char::is_whitespace)
                {
                    start += 1;
                }
            }
        }

        let truncated = raw.len() > limit;
        raw.truncate(limit);
        let last = raw.len().saturating_sub(1);
        let height = raw.len() as f32 * line_height;
        let free = if available.height.is_finite() {
            (available.height - height).max(0.0)
        } else {
            0.0
        };
        let top = match vertical {
            Vertical::Top => 0.0,
            Vertical::Center => free * 0.5,
            Vertical::Bottom => free,
        };
        let mut width = 0.0_f32;
        let lines = raw
            .into_iter()
            .enumerate()
            .map(|(index, (mut range, rtl))| {
                let mut span = advance(range.clone(), false);
                let mut ellipsis = false;
                if elide && (span > available.width || truncated && index == last) {
                    (range, ellipsis) = elided(text, range, available.width, &mut advance);
                    span = advance(range.clone(), ellipsis);
                }
                width = width.max(span);
                let free = available.width - span;
                let x = horizontal.offset(free, rtl);
                PlannedLabelLine {
                    range,
                    ellipsis,
                    origin: Point {
                        x,
                        y: top + index as f32 * line_height,
                    },
                }
            })
            .collect();
        Self {
            size: Size::new(width.min(available.width), height),
            lines,
        }
    }
}

fn trim_trailing_space(text: &str, range: Range<usize>) -> Range<usize> {
    range.start..range.start + text[range.clone()].trim_end().len()
}

/// Fit a single line to the available width without splitting a grapheme.
#[doc(hidden)]
pub fn elide_to_width(
    text: &str,
    width: f32,
    mut advance: impl FnMut(&str) -> f32,
) -> Cow<'_, str> {
    if advance(text) <= width {
        return Cow::Borrowed(text);
    }
    let (range, ellipsis) = elided(text, 0..text.len(), width, &mut |range, ellipsis| {
        advance(&line_text(text, range, ellipsis))
    });
    line_text(text, range, ellipsis)
}

fn elided(
    text: &str,
    range: Range<usize>,
    width: f32,
    advance: &mut impl FnMut(Range<usize>, bool) -> f32,
) -> (Range<usize>, bool) {
    let start = range.start;
    if advance(start..start, true) > width {
        return (start..start, false);
    }
    let boundaries = grapheme_boundaries(&text[range]);
    let end = fitting_prefix(0, boundaries.len() - 1, |index| {
        advance(
            trim_trailing_space(text, start..start + boundaries[index]),
            true,
        ) <= width
    });
    (
        trim_trailing_space(text, start..start + boundaries[end]),
        true,
    )
}