xrack-runtime 0.1.1

Runtime types, properties, models, and controls for generated 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
use crate::{Length, Orientation, Property};
use std::{
    cell::{Cell, OnceCell, RefCell},
    fmt,
    rc::Rc,
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScrollAlignment {
    Beginning,
    Center,
    End,
    Visible,
    #[default]
    Contain,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScrollAction {
    CancelFlick,
    ReturnToBounds,
    To {
        x: Length,
        y: Length,
    },
    ToIndex {
        index: i64,
        alignment: ScrollAlignment,
    },
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ViewportMotion {
    #[default]
    Idle,
    Dragging,
    Flicking,
}

/// A viewport's stable identity and reactive geometry, owned by its component instance.
#[derive(Clone, Default)]
pub struct ViewportHandle(Rc<ViewportProperties>);

#[derive(Default)]
struct ViewportProperties {
    scroll_notifications: bool,
    motion: Option<Box<MotionProperties>>,
    content_x: Property<Length>,
    content_y: Property<Length>,
    visible_width: Property<Length>,
    visible_height: Property<Length>,
    ranges: [ViewportRange; 2],
    horizontal: OnceCell<OffsetBinding>,
    vertical: OnceCell<OffsetBinding>,
}

#[derive(Default)]
struct MotionProperties {
    phase: Cell<ViewportMotion>,
    dragging: Property<bool>,
    flicking: Property<bool>,
    moving: Property<bool>,
    overshoot: [RangeMetric; 2],
    returning: Cell<[bool; 2]>,
    rebounding: Property<bool>,
}

#[derive(Default)]
struct ViewportRange {
    position: RangeMetric,
    size: RangeMetric,
}

/// Keep the latest layout sample and allocate a dependency only when it is read.
#[derive(Default)]
struct RangeMetric {
    sample: Cell<f64>,
    observed: OnceCell<Box<Property<f64>>>,
}

impl RangeMetric {
    fn get(&self) -> f64 {
        self.observed
            .get_or_init(Default::default)
            .get(|| self.sample.get())
    }

    fn publish(&self, value: f64) {
        self.sample.set(value);
        if let Some(property) = self.observed.get() {
            property.set_if_changed(value);
        }
    }
}

struct OffsetBinding {
    read: Box<dyn Fn() -> Length>,
    write: Box<dyn Fn(Length)>,
}

impl PartialEq for ViewportHandle {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl fmt::Debug for ViewportHandle {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ViewportHandle")
            .finish_non_exhaustive()
    }
}

impl ViewportHandle {
    #[doc(hidden)]
    pub fn identity(&self) -> usize {
        Rc::as_ptr(&self.0) as usize
    }

    #[doc(hidden)]
    pub fn with_scroll_notifications() -> Self {
        Self(Rc::new(ViewportProperties {
            scroll_notifications: true,
            ..ViewportProperties::default()
        }))
    }

    #[doc(hidden)]
    pub fn for_flickable(scroll_notifications: bool) -> Self {
        Self(Rc::new(ViewportProperties {
            scroll_notifications,
            motion: Some(Box::default()),
            ..ViewportProperties::default()
        }))
    }

    pub fn dragging(&self) -> bool {
        self.0
            .motion
            .as_ref()
            .is_some_and(|state| state.dragging.get(|| false))
    }
    pub fn flicking(&self) -> bool {
        self.0
            .motion
            .as_ref()
            .is_some_and(|state| state.flicking.get(|| false))
    }
    pub fn moving(&self) -> bool {
        self.0
            .motion
            .as_ref()
            .is_some_and(|state| state.moving.get(|| false))
    }

    pub fn rebounding(&self) -> bool {
        self.0
            .motion
            .as_ref()
            .is_some_and(|state| state.rebounding.get(|| false))
    }

    pub fn horizontal_overshoot(&self) -> Length {
        self.overshoot(Orientation::Horizontal)
    }
    pub fn vertical_overshoot(&self) -> Length {
        self.overshoot(Orientation::Vertical)
    }

    fn overshoot(&self, axis: Orientation) -> Length {
        Length(self.0.motion.as_ref().map_or(0.0, |state| {
            state.overshoot[usize::from(axis == Orientation::Vertical)].get()
        }))
    }

    #[doc(hidden)]
    pub fn observes_motion(&self) -> bool {
        self.0.motion.is_some()
    }

    #[doc(hidden)]
    pub fn publish_motion(&self, motion: ViewportMotion) {
        if let Some(state) = &self.0.motion {
            state.phase.set(motion);
            state
                .dragging
                .set_if_changed(motion == ViewportMotion::Dragging);
            state
                .flicking
                .set_if_changed(motion == ViewportMotion::Flicking);
            state.moving.set_if_changed(
                motion != ViewportMotion::Idle || state.returning.get().contains(&true),
            );
        }
    }

    #[doc(hidden)]
    pub fn publish_overshoot(&self, axis: Orientation, value: f32, returning: bool) {
        if let Some(state) = &self.0.motion {
            let index = usize::from(axis == Orientation::Vertical);
            state.overshoot[index].publish(f64::from(value));
            let mut phases = state.returning.get();
            phases[index] = returning;
            state.returning.set(phases);
            let rebounding = phases.contains(&true);
            state.rebounding.set_if_changed(rebounding);
            state
                .moving
                .set_if_changed(state.phase.get() != ViewportMotion::Idle || rebounding);
        }
    }

    #[doc(hidden)]
    pub fn observes_user_scroll(&self) -> bool {
        self.0.scroll_notifications
    }

    fn offset_binding(&self, axis: Orientation) -> &OnceCell<OffsetBinding> {
        match axis {
            Orientation::Horizontal => &self.0.horizontal,
            Orientation::Vertical => &self.0.vertical,
        }
    }

    #[doc(hidden)]
    pub fn bind_offset(
        &self,
        axis: Orientation,
        read: impl Fn() -> Length + 'static,
        write: impl Fn(Length) + 'static,
    ) {
        let binding = OffsetBinding {
            read: Box::new(read),
            write: Box::new(write),
        };
        assert!(
            self.offset_binding(axis).set(binding).is_ok(),
            "viewport offset already bound"
        );
    }

    #[doc(hidden)]
    pub fn has_bound_offset(&self, axis: Orientation) -> bool {
        self.offset_binding(axis).get().is_some()
    }

    #[doc(hidden)]
    pub fn bound_offset(&self, axis: Orientation) -> Option<f32> {
        let binding = self.offset_binding(axis).get()?;
        Some((-(binding.read)().0).max(0.0).min(f64::from(f32::MAX)) as f32)
    }

    #[doc(hidden)]
    pub fn write_bound_offset(&self, axis: Orientation, offset: f32) {
        if let Some(binding) = self.offset_binding(axis).get() {
            (binding.write)(Length(-f64::from(offset)));
        }
    }

    pub fn content_x(&self) -> Length {
        self.0.content_x.get(Length::default)
    }
    pub fn content_y(&self) -> Length {
        self.0.content_y.get(Length::default)
    }
    pub fn visible_width(&self) -> Length {
        self.0.visible_width.get(Length::default)
    }
    pub fn visible_height(&self) -> Length {
        self.0.visible_height.get(Length::default)
    }

    fn range(&self, axis: Orientation) -> &ViewportRange {
        &self.0.ranges[usize::from(axis == Orientation::Vertical)]
    }

    pub fn scroll_position(&self, axis: Orientation) -> f64 {
        self.range(axis).position.get()
    }

    pub fn scroll_size(&self, axis: Orientation) -> f64 {
        self.range(axis).size.get()
    }

    #[doc(hidden)]
    pub fn publish_scroll_range(&self, axis: Orientation, offset: f32, page: f32, maximum: f32) {
        let page = f64::from(page);
        let extent = page + f64::from(maximum);
        let (position, size) =
            if page > 0.0 && maximum >= 0.0 && extent.is_finite() && offset.is_finite() {
                let size = page / extent;
                ((f64::from(offset) / extent).clamp(0.0, 1.0 - size), size)
            } else {
                (0.0, 0.0)
            };
        let range = self.range(axis);
        range.position.publish(position);
        range.size.publish(size);
    }

    #[doc(hidden)]
    pub fn publish(&self, x: Length, y: Length, width: Length, height: Length) {
        self.0.content_x.set_if_changed(x);
        self.0.content_y.set_if_changed(y);
        self.0.visible_width.set_if_changed(width);
        self.0.visible_height.set_if_changed(height);
    }

    pub fn request(&self, action: ScrollAction) {
        ACTIVE.with(|active| {
            if let Some(requests) = &*active.borrow() {
                requests.0.borrow_mut().push(ScrollRequest {
                    target: self.clone(),
                    action,
                });
            }
        });
    }
}

pub struct ScrollRequest {
    pub target: ViewportHandle,
    pub action: ScrollAction,
}

/// Commands are resolved against the window's newly prepared scene.
#[derive(Clone, Default)]
pub struct ScrollRequests(Rc<RefCell<Vec<ScrollRequest>>>);

thread_local! {
    static ACTIVE: RefCell<Option<ScrollRequests>> = const { RefCell::new(None) };
}

pub struct ScrollContext(Option<ScrollRequests>);

impl ScrollRequests {
    pub fn enter(&self) -> ScrollContext {
        ScrollContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
    }

    pub fn drain(&self) -> Vec<ScrollRequest> {
        std::mem::take(&mut *self.0.borrow_mut())
    }

    pub fn is_empty(&self) -> bool {
        self.0.borrow().is_empty()
    }
}

impl Drop for ScrollContext {
    fn drop(&mut self) {
        ACTIVE.with(|active| active.replace(self.0.take()));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn moving_binding_remains_cached_across_drag_to_flick_transition() {
        let viewport = ViewportHandle::for_flickable(false);
        let moving = Property::default();
        let dragging = Property::default();
        viewport.publish_motion(ViewportMotion::Dragging);
        assert!(moving.get(|| viewport.moving()));
        assert!(dragging.get(|| viewport.dragging()));
        viewport.publish_motion(ViewportMotion::Flicking);
        assert!(!moving.is_dirty());
        assert!(dragging.is_dirty());
        assert!(viewport.flicking());
        viewport.publish_motion(ViewportMotion::Idle);
        assert!(moving.is_dirty());
        assert!(!moving.get(|| viewport.moving()));
    }

    #[test]
    fn scroll_range_invalidates_only_the_changed_axis_and_metric() {
        let viewport = ViewportHandle::default();
        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 100.0, 100.0);
        assert!(
            viewport
                .range(Orientation::Horizontal)
                .size
                .observed
                .get()
                .is_none()
        );
        let size = Property::default();
        let position = Property::default();
        let read_size = || viewport.scroll_size(Orientation::Horizontal);
        let read_position = || viewport.scroll_position(Orientation::Horizontal);
        assert_eq!(size.get(read_size), 0.5);
        assert_eq!(position.get(read_position), 0.0);

        viewport.publish_scroll_range(Orientation::Vertical, 30.0, 20.0, 80.0);
        assert!(
            viewport
                .range(Orientation::Vertical)
                .position
                .observed
                .get()
                .is_none()
        );
        assert!(!position.is_dirty());
        assert!(!size.is_dirty());
        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
        assert!(position.is_dirty());
        assert!(!size.is_dirty());
        assert_eq!(position.get(read_position), 0.25);

        viewport.publish_scroll_range(Orientation::Horizontal, 50.0, 100.0, 100.0);
        assert!(!position.is_dirty());
        viewport.publish_scroll_range(Orientation::Horizontal, 0.0, 0.0, 0.0);
        assert!(position.is_dirty());
        assert!(size.is_dirty());
        assert_eq!(size.get(read_size), 0.0);
    }
}