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
use crate::{LayoutContext, LayoutNode, Point, Rect, Size, TextMeasurer, linear};
use std::{
    collections::BTreeMap,
    time::{Duration, Instant},
};
use xrack_runtime::{Color, Length, Node, RowKey, is_window_overlay};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Source {
    #[default]
    Pointer,
    Focus,
    Touch,
}

#[derive(Clone, Copy, Debug)]
enum Anchor {
    Pointer(Point),
    Focus,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TooltipKey {
    owner: Vec<usize>,
    slot: usize,
    row: Option<RowKey>,
    source: Source,
}

impl TooltipKey {
    fn new(scene: &Node, path: &[usize], source: Source) -> Option<Self> {
        let (slot, _) = attached(scene.at_path(path)?)?;
        Some(Self {
            owner: path.to_vec(),
            slot,
            row: scene.row_key_at(path),
            source,
        })
    }

    fn node<'a>(&self, scene: &'a Node) -> Option<&'a Node> {
        if scene.row_key_at(&self.owner) != self.row {
            return None;
        }
        scene
            .at_path(&self.owner)?
            .child_at(self.slot)
            .filter(|node| has_content(node))
    }
}

fn attached(owner: &Node) -> Option<(usize, &Node)> {
    owner
        .materialized_children()
        .find(|(_, node)| has_content(node))
}

#[doc(hidden)]
pub fn tooltip_text(owner: &Node) -> Option<&str> {
    let text = attached(owner)?.1.text("text")?.trim();
    (!text.is_empty()).then_some(text)
}

fn has_content(node: &Node) -> bool {
    node.kind == "Tooltip"
        && node.is_visible()
        && (node
            .text("text")
            .is_some_and(|text| !text.trim().is_empty())
            || node.children.iter().any(Node::is_visible))
}

pub(crate) fn hovered(
    scene: &Node,
    layout: &LayoutNode,
    scope: &[usize],
    point: Point,
    source: Source,
) -> Option<TooltipKey> {
    fn path_at(node: &Node, item: &LayoutNode, point: Point, path: &mut Vec<usize>) -> bool {
        if !item.contains_subtree_point(point) {
            return false;
        }
        for (index, child, layout) in item.children_in_paint_order(node).rev() {
            if is_window_overlay(child.kind) {
                continue;
            }
            path.push(index);
            if path_at(child, layout, point, path) {
                return true;
            }
            path.pop();
        }
        item.map_from_window(point)
            .is_some_and(|point| item.bounds.contains(point))
    }
    let mut path = scope.to_vec();
    if !path_at(
        scene.at_path(scope)?,
        layout.at_path(scope)?,
        point,
        &mut path,
    ) {
        return None;
    }
    find_owner(scene, &path, scope.len(), source)
}

pub(crate) fn focused(scene: &Node, path: &[usize], scope: &[usize]) -> Option<TooltipKey> {
    if !path.starts_with(scope) {
        return None;
    }
    find_owner(scene, path, scope.len(), Source::Focus)
}

fn find_owner(
    scene: &Node,
    path: &[usize],
    min_depth: usize,
    source: Source,
) -> Option<TooltipKey> {
    (min_depth..=path.len())
        .rev()
        .find_map(|depth| TooltipKey::new(scene, &path[..depth], source))
}

#[derive(Clone, Copy, Debug)]
enum Phase {
    Waiting(Instant),
    Showing { since: Instant, anchor: Anchor },
    Suppressed,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct TooltipState {
    pub(crate) source: Source,
    key: Option<TooltipKey>,
    phase: Option<Phase>,
    deadline: Option<Instant>,
    suppress_next: bool,
}

fn after(now: Instant, millis: i64) -> Instant {
    now.checked_add(Duration::from_millis(millis.max(0) as u64))
        .unwrap_or_else(|| now + Duration::from_secs(86_400))
}

impl TooltipState {
    pub(crate) fn touch_key(&self, layout: &LayoutNode, scope: &[usize]) -> Option<TooltipKey> {
        self.key
            .as_ref()
            .filter(|key| {
                key.owner.starts_with(scope)
                    && layout.at_path(&key.owner).is_some_and(|owner| {
                        let bounds = owner.visible_window_bounds(owner.bounds);
                        owner.visible && bounds.width > 0.0 && bounds.height > 0.0
                    })
            })
            .cloned()
    }

    pub(crate) fn show_touch(&mut self, key: TouchTooltip, now: Instant) {
        *self = Self {
            source: Source::Touch,
            key: Some(key.0),
            phase: Some(Phase::Showing {
                since: now,
                anchor: Anchor::Focus,
            }),
            ..Self::default()
        };
    }

    pub(crate) fn focus_source(&mut self) {
        self.source = Source::Focus;
        self.suppress_next = false;
    }
    pub(crate) fn dismiss(&mut self) -> bool {
        let was_visible = self.visible();
        self.phase = Some(Phase::Suppressed);
        self.deadline = None;
        self.suppress_next = self.key.is_none();
        was_visible
    }

    pub(crate) fn pointer_left(&mut self) -> bool {
        if self.source != Source::Pointer {
            return false;
        }
        let visible = self.visible();
        self.key = None;
        self.phase = None;
        self.deadline = None;
        self.suppress_next = false;
        visible
    }

    fn visible(&self) -> bool {
        matches!(self.phase, Some(Phase::Showing { .. }))
    }

    pub(crate) fn deadline(&self) -> Option<Instant> {
        self.deadline
    }

    pub(crate) fn advance(
        &mut self,
        scene: &Node,
        key: Option<TooltipKey>,
        pointer: Option<Point>,
        blocked: bool,
        now: Instant,
    ) -> bool {
        let was_visible = self.visible();
        let changed = self.key != key;
        self.deadline = None;
        let suppress = std::mem::take(&mut self.suppress_next) || blocked;
        if changed {
            self.key = key;
            self.phase = Some(Phase::Waiting(now));
        }
        let Some(key) = &self.key else {
            self.phase = None;
            return was_visible;
        };
        let Some(node) = key.node(scene) else {
            self.phase = None;
            return was_visible;
        };
        if suppress {
            self.phase = Some(Phase::Suppressed);
        }
        if let Some(Phase::Waiting(since)) = self.phase {
            let show = after(since, node.int("delay").unwrap_or(600));
            if now < show {
                self.deadline = Some(show);
            } else {
                let anchor = match key.source {
                    Source::Focus | Source::Touch => Anchor::Focus,
                    Source::Pointer => pointer.map_or(Anchor::Focus, Anchor::Pointer),
                };
                self.phase = Some(Phase::Showing { since: now, anchor });
            }
        }
        if let Some(Phase::Showing { since, .. }) = self.phase
            && let Some(timeout) = node.int("timeout").filter(|timeout| *timeout >= 0)
        {
            let hide = after(since, timeout);
            if now >= hide {
                self.phase = Some(Phase::Suppressed);
            } else {
                self.deadline = Some(hide);
            }
        }
        self.visible() != was_visible || changed && was_visible
    }

    pub(crate) fn popup<'a>(
        &self,
        scene: &'a Node,
        layout: &LayoutNode,
        scope: &[usize],
    ) -> Option<TooltipPopup<'a>> {
        let Some(Phase::Showing { anchor, .. }) = self.phase else {
            return None;
        };
        let key = self.key.as_ref()?;
        if !key.owner.starts_with(scope) {
            return None;
        }
        let node = key.node(scene)?;
        let owner = layout.at_path(&key.owner)?;
        let bounds = owner.visible_window_bounds(owner.bounds);
        if !owner.visible || bounds.width <= 0.0 || bounds.height <= 0.0 {
            return None;
        }
        Some(TooltipPopup {
            node,
            anchor,
            owner: bounds,
            layout_direction: node
                .layout_direction()
                .or(owner.layout_direction_override()),
        })
    }
}

#[doc(hidden)]
#[derive(PartialEq, Eq)]
pub struct TouchTooltip(TooltipKey);

impl TouchTooltip {
    pub(crate) fn at(
        scene: &Node,
        layout: &LayoutNode,
        scope: &[usize],
        point: Point,
        now: Instant,
    ) -> Option<(Self, Instant)> {
        let key = hovered(scene, layout, scope, point, Source::Touch)?;
        let node = key.node(scene)?;
        if node.int("timeout") == Some(0) {
            return None;
        }
        // A tooltip with no hover delay still requires a deliberate touch hold.
        let deadline = after(now, node.int("delay").unwrap_or(600).max(500));
        Some((Self(key), deadline))
    }
}

pub struct TooltipPopup<'a> {
    pub node: &'a Node,
    anchor: Anchor,
    owner: Rect,
    layout_direction: Option<xrack_runtime::LayoutDirection>,
}

/// Place a tooltip surface in window coordinates, using the normal text and layout engine.
pub fn layout_tooltip(
    popup: TooltipPopup<'_>,
    viewport: Rect,
    text: &mut impl TextMeasurer,
) -> (Node, LayoutNode) {
    let TooltipPopup {
        node,
        anchor,
        owner,
        layout_direction,
    } = popup;
    let area = viewport.inset(6.0);
    let mut surface = Node::new("VerticalLayout", None);
    if let Some(opacity) = node.properties.get("opacity") {
        surface.properties.insert("opacity", opacity.clone());
    }
    surface.properties.insert(
        "background",
        node.properties
            .get("background")
            .cloned()
            .unwrap_or_else(|| Color(0x25334bff).into()),
    );
    surface.properties.insert(
        "padding",
        Length(f64::from(
            node.length("padding").unwrap_or(8.0).clamp(0.0, 32.0),
        ))
        .into(),
    );
    surface
        .properties
        .insert("border-radius", Length(5.0).into());
    surface
        .properties
        .insert("border-width", Length(1.0).into());
    surface
        .properties
        .insert("border-color", Color(0x627596ff).into());
    if let Some(value) = node.text("text") {
        let mut label = Node::new("Text", None);
        label.properties.insert("text", value.to_owned().into());
        for name in [
            "font",
            "font-size",
            "font-family",
            "font-weight",
            "font-italic",
        ] {
            if let Some(value) = node.properties.get(name) {
                label.properties.insert(name, value.clone());
            }
        }
        if label.font_size().is_none() && text.default_font_size().is_none() {
            label.properties.insert("font-size", Length(14.0).into());
        }
        if let Some(color) = node.color("color") {
            label.properties.insert("color", color.into());
        }
        surface.children.push(label);
    } else {
        surface.children.clone_from(&node.children);
    }

    let cap = node
        .relative_length("max-width", area.width)
        .unwrap_or(320.0)
        .clamp(0.0, area.width);
    let width = node
        .relative_length("width", area.width)
        .unwrap_or_else(|| {
            linear::measure(&surface, Size::new(cap, area.height), text)
                .x
                .preferred
        })
        .clamp(0.0, cap);
    let height = node
        .relative_length("height", area.height)
        .unwrap_or_else(|| {
            linear::measure(&surface, Size::new(width, area.height), text)
                .y
                .preferred
        })
        .clamp(0.0, area.height);
    let (x, below, above) = match anchor {
        Anchor::Pointer(point) => (point.x + 12.0, point.y + 18.0, point.y - 8.0),
        Anchor::Focus => (
            owner.x + (owner.width - width) * 0.5,
            owner.y + owner.height + 8.0,
            owner.y - 8.0,
        ),
    };
    let bottom = area.y + area.height;
    let y = if below + height <= bottom || bottom - below >= above - area.y {
        below
    } else {
        above - height
    };
    let bounds = Rect::new(
        x.clamp(area.x, (area.x + area.width - width).max(area.x)),
        y.clamp(area.y, (bottom - height).max(area.y)),
        width,
        height,
    );
    let mut context = LayoutContext {
        row_key: None,
        layout_direction,
        anchor: None,
        resolved_list_scroll: None,
        row_layouts: None,
        ancestor_shapes: None,
        space: None,
        text,
        offsets: &BTreeMap::new(),
        input: None,
        path: Vec::new(),
        viewport,
    };
    let layout = context.place(&surface, bounds, area, true, true, None);
    (surface, layout)
}