sk-tree 0.3.0

Skathi's retained node tree and the renderer's host functions
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
//! Programmatic scrolling — `el.scrollTop = n`, `scrollTo`, `scrollBy`, `scrollIntoView()`.
//!
//! - The write is synchronous and the read sees it at once (a `ScrollHandle` is an `Rc<RefCell<…>>`),
//!   with the same clamp gpui's wheel handler applies.
//! - A write lays out first, as a read does: the clamp needs `max_offset`, and `list.append(row);
//!   list.scrollTop = list.scrollHeight` appends after the last frame.
//! - The `scroll` event is asynchronous, as in a browser: a write queues the node and
//!   [`dispatch_pending`] (from [`crate::frame_tick`], the one place with a `Window`) fires it.
//! - A rectangle read after a scroll is corrected, not re-measured ([`unpainted_shift`]): a second
//!   `draw` is refused inside the window's own update.
//! - A smooth scroll (`behavior: "smooth"`, or `auto` on a box with `scroll-behavior: smooth`)
//!   glides there over the next frames ([`tick`]); a read sees where it is so far. An instant
//!   scroll of the same box, or the user scrolling it, stops the glide.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};

use gpui::{px, Pixels, Point, ScrollHandle};

use crate::render;
use crate::tree;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Align {
    Start,
    Center,
    End,
    Nearest,
}

/// CSSOM View's `ScrollBehavior`; `Auto` defers to the scrolled box's `scroll-behavior`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Behavior {
    Auto,
    Instant,
    Smooth,
}

impl Behavior {
    fn smooth_for(self, id: u32) -> bool {
        match self {
            Behavior::Instant => false,
            Behavior::Smooth => true,
            Behavior::Auto => tree::read_tree(|t| {
                t.node(id)
                    .and_then(|n| n.computed.as_ref())
                    .and_then(|cs| cs.extras.scroll_smooth)
            })
            .unwrap_or(false),
        }
    }
}

struct Glide {
    from: Point<Pixels>,
    to: Point<Pixels>,
    start: Instant,
    duration: Duration,
    /// The offset the glide last wrote: anything else means something else scrolled the box.
    last: Point<Pixels>,
}

impl Glide {
    fn new(from: Point<Pixels>, to: Point<Pixels>) -> Self {
        let distance = f32::from((to.x - from.x).abs()).max(f32::from((to.y - from.y).abs()));
        Glide {
            from,
            to,
            start: Instant::now(),
            duration: glide_duration(distance),
            last: from,
        }
    }

    fn at(&self, now: Instant) -> (Point<Pixels>, bool) {
        let t = now.saturating_duration_since(self.start).as_secs_f32()
            / self.duration.as_secs_f32().max(f32::EPSILON);
        if t >= 1.0 {
            return (self.to, true);
        }
        let e = ease_in_out(t);
        let lerp = |a: Pixels, b: Pixels| a + (b - a) * e;
        (
            Point {
                x: lerp(self.from.x, self.to.x),
                y: lerp(self.from.y, self.to.y),
            },
            false,
        )
    }
}

/// Longer for a longer way, as in browsers, within the 150-500 ms they keep a programmatic glide to.
fn glide_duration(distance: f32) -> Duration {
    Duration::from_secs_f32((distance.sqrt() * 15.0).clamp(150.0, 500.0) / 1000.0)
}

fn ease_in_out(t: f32) -> f32 {
    if t < 0.5 {
        4.0 * t * t * t
    } else {
        1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Info {
    pub(crate) left: f32,
    pub(crate) top: f32,
    pub(crate) scroll_width: f32,
    pub(crate) scroll_height: f32,
    /// Content size and clamp are from the LAST PAINTED frame: the tree changed in this JS wave and a
    /// layout could not be forced ([`crate::dom::layout_if_stale`]).
    pub(crate) stale: bool,
}

thread_local! {
    static PENDING: RefCell<HashSet<u32>> = RefCell::new(HashSet::new());
    static AT_BUILD: RefCell<HashMap<u32, (f32, f32)>> = RefCell::new(HashMap::new());
    static GLIDES: RefCell<HashMap<u32, Glide>> = RefCell::new(HashMap::new());
}

pub(crate) fn note_built(id: u32, handle: &ScrollHandle) {
    let o = handle.offset();
    AT_BUILD.with(|m| {
        m.borrow_mut()
            .insert(id, (-f32::from(o.x), -f32::from(o.y)))
    });
}

pub(crate) fn unpainted_shift(id: u32) -> (f32, f32) {
    if AT_BUILD.with(|m| m.borrow().is_empty()) {
        return (0.0, 0.0);
    }
    let (dx, dy) = scrolled_since_build(id);
    let (sx, sy) = crate::sticky::unpainted(id, scrolled_since_build);
    (dx + sx, dy + sy)
}

fn scrolled_since_build(id: u32) -> (f32, f32) {
    let (mut dx, mut dy) = (0.0f32, 0.0f32);
    let mut cur = tree::read_tree(|t| t.node(id).map(|n| n.parent).unwrap_or(0));
    for _ in 0..4096 {
        if cur == 0 {
            break;
        }
        if let Some(handle) = render::scroll_handle_of(cur) {
            let at_build = AT_BUILD
                .with(|m| m.borrow().get(&cur).copied())
                .unwrap_or((0.0, 0.0));
            let now = handle.offset();
            dx -= (-f32::from(now.x)) - at_build.0;
            dy -= (-f32::from(now.y)) - at_build.1;
        }
        cur = tree::read_tree(|t| t.node(cur).map(|n| n.parent).unwrap_or(0));
    }
    (dx, dy)
}

pub(crate) fn gc(live: &dyn Fn(u32) -> bool) {
    PENDING.with(|p| p.borrow_mut().retain(|&id| live(id)));
    AT_BUILD.with(|m| m.borrow_mut().retain(|&id, _| live(id)));
    GLIDES.with(|g| g.borrow_mut().retain(|&id, _| live(id)));
}

pub(crate) fn info(id: u32) -> Option<Info> {
    let stale = crate::dom::layout_if_stale(id);
    let handle = render::scroll_handle_of(id)?;
    Some(info_of(&handle, stale))
}

fn info_of(handle: &ScrollHandle, stale: bool) -> Info {
    // gpui's offsets are <= 0 (the content is shifted up/left); CSS counts down/right as positive.
    let offset = handle.offset();
    let max = handle.max_offset();
    let viewport = handle.bounds().size;
    Info {
        left: -f32::from(offset.x),
        top: -f32::from(offset.y),
        scroll_width: f32::from(viewport.width + max.x),
        scroll_height: f32::from(viewport.height + max.y),
        stale,
    }
}

pub(crate) fn set(
    id: u32,
    left: Option<f32>,
    top: Option<f32>,
    behavior: Behavior,
) -> Option<Info> {
    let (handle, stale) = layout_then_handle(id)?;
    let smooth = behavior.smooth_for(id);
    // An axis a smooth call leaves alone keeps going where a glide was taking it.
    let current = smooth
        .then(|| glide_target(id))
        .flatten()
        .unwrap_or_else(|| handle.offset());
    let want = Point {
        x: left.map_or(current.x, |v| px(-v)),
        y: top.map_or(current.y, |v| px(-v)),
    };
    Some(apply(id, &handle, want, stale, smooth).0)
}

pub(crate) fn by(id: u32, dx: f32, dy: f32, behavior: Behavior) -> Option<Info> {
    let (handle, stale) = layout_then_handle(id)?;
    let smooth = behavior.smooth_for(id);
    // A smooth scrollBy during a glide adds to where it is going, as in browsers.
    let current = smooth
        .then(|| glide_target(id))
        .flatten()
        .unwrap_or_else(|| handle.offset());
    let want = Point {
        x: current.x - px(dx),
        y: current.y - px(dy),
    };
    Some(apply(id, &handle, want, stale, smooth).0)
}

fn glide_target(id: u32) -> Option<Point<Pixels>> {
    GLIDES.with(|g| g.borrow().get(&id).map(|glide| glide.to))
}

/// Moves (or starts gliding) to `want`, clamped; answers the position now and the one it goes to.
fn apply(
    id: u32,
    handle: &ScrollHandle,
    want: Point<Pixels>,
    stale: bool,
    smooth: bool,
) -> (Info, Point<Pixels>) {
    let before = handle.offset();
    let max = handle.max_offset();
    // The clamp gpui's wheel handler applies: a programmatic scroll cannot leave the box where a
    // wheel could not.
    let clamped = Point {
        x: want.x.clamp(-max.x, px(0.)),
        y: want.y.clamp(-max.y, px(0.)),
    };
    GLIDES.with(|g| {
        let mut g = g.borrow_mut();
        if smooth && clamped != before {
            g.insert(id, Glide::new(before, clamped));
        } else {
            g.remove(&id);
        }
    });
    if !smooth && clamped != before {
        handle.set_offset(clamped);
        note_moved(id);
    }
    (info_of(handle, stale), clamped)
}

/// Advances every glide one frame; true while any is still moving.
pub(crate) fn tick() -> bool {
    if GLIDES.with(|g| g.borrow().is_empty()) {
        return false;
    }
    let now = Instant::now();
    let mut moved = Vec::new();
    GLIDES.with(|g| {
        g.borrow_mut().retain(|&id, glide| {
            let Some(handle) = render::scroll_handle_of(id) else {
                return false;
            };
            if handle.offset() != glide.last {
                return false;
            }
            let (at, done) = glide.at(now);
            let max = handle.max_offset();
            let at = Point {
                x: at.x.clamp(-max.x, px(0.)),
                y: at.y.clamp(-max.y, px(0.)),
            };
            if at != glide.last {
                handle.set_offset(at);
                glide.last = at;
                moved.push(id);
            }
            !done
        })
    });
    for id in &moved {
        note_moved(*id);
    }
    !moved.is_empty() || GLIDES.with(|g| !g.borrow().is_empty())
}

fn note_moved(id: u32) {
    PENDING.with(|p| p.borrow_mut().insert(id));
    tree::with_tree(|t| t.touch(id));
}

fn layout_then_handle(id: u32) -> Option<(ScrollHandle, bool)> {
    let stale = crate::dom::layout_if_stale(id);
    render::scroll_handle_of(id).map(|h| (h, stale))
}

pub(crate) fn into_view(
    id: u32,
    block: Align,
    inline: Align,
    behavior: Behavior,
) -> Result<bool, String> {
    // `true`: the rectangles and clamps are from the last painted frame ([`Info::stale`]); the JS
    // side turns it into the one advisory.
    let stale = crate::dom::layout_if_stale(id);
    // The same correction `dom::bounds` applies, for the same reason: two `scrollIntoView()` calls
    // in one JS wave must not both aim at the position the first one moved away from.
    let shift = unpainted_shift(id);
    let Some((mut x, mut y, w, h)) =
        render::bounds_of(id).map(|(x, y, w, h)| (x + shift.0, y + shift.1, w, h))
    else {
        return Err(format!(
            "scrollIntoView(): node {id} has no rectangle — it is detached, \
             `display: none`, or parked in a <KeepAlive> cache, and a browser \
             would not scroll to it either"
        ));
    };
    let chain = tree::read_tree(|t| {
        let mut out = Vec::new();
        let mut cur = t.node(id).map(|n| n.parent).unwrap_or(0);
        // A depth cap for the same reason `Tree::touch` has one: a corrupt parent link must not
        // hang the pump.
        for _ in 0..4096 {
            if cur == 0 {
                break;
            }
            out.push(cur);
            cur = t.node(cur).map(|n| n.parent).unwrap_or(0);
        }
        out
    });
    let mut scrolled = false;
    for ancestor in chain {
        let Some(handle) = render::scroll_handle_of(ancestor) else {
            continue;
        };
        let viewport = handle.bounds();
        if viewport.size.width <= px(0.) && viewport.size.height <= px(0.) {
            continue;
        }
        let dx = align_delta(
            inline,
            x,
            w,
            f32::from(viewport.origin.x),
            f32::from(viewport.size.width),
        );
        let dy = align_delta(
            block,
            y,
            h,
            f32::from(viewport.origin.y),
            f32::from(viewport.size.height),
        );
        let before = handle.offset();
        let want = Point {
            x: before.x - px(dx),
            y: before.y - px(dy),
        };
        let smooth = behavior.smooth_for(ancestor);
        let (_, after) = apply(ancestor, &handle, want, stale, smooth);
        x -= f32::from(before.x - after.x);
        y -= f32::from(before.y - after.y);
        scrolled |= before != after;
    }
    let _ = scrolled;
    Ok(stale)
}

fn align_delta(
    align: Align,
    target_start: f32,
    target_len: f32,
    view_start: f32,
    view_len: f32,
) -> f32 {
    let target_end = target_start + target_len;
    let view_end = view_start + view_len;
    match align {
        Align::Start => target_start - view_start,
        Align::End => target_end - view_end,
        Align::Center => (target_start + target_len / 2.0) - (view_start + view_len / 2.0),
        Align::Nearest => {
            // CSSOM-View: already fully inside → do nothing; covering the whole viewport on both
            // edges → do nothing (scrolling either way would only take some of it off screen);
            // otherwise bring in the edge that is out, and no further.
            if target_start >= view_start && target_end <= view_end {
                0.0
            } else if target_start < view_start && target_end > view_end {
                0.0
            } else if target_start < view_start {
                target_start - view_start
            } else {
                target_end - view_end
            }
        }
    }
}

pub(crate) fn dispatch_pending(window: &mut gpui::Window, cx: &mut gpui::App) -> bool {
    let pending: Vec<u32> = PENDING.with(|p| p.borrow_mut().drain().collect());
    if pending.is_empty() {
        return false;
    }
    for id in pending {
        let Some(handle) = render::scroll_handle_of(id) else {
            continue;
        };
        render::report_scroll(id, &handle, window, cx);
    }
    true
}

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

    #[test]
    fn a_glide_moves_one_way_and_lands_exactly() {
        let from = Point {
            x: px(0.),
            y: px(-10.),
        };
        let to = Point {
            x: px(0.),
            y: px(-410.),
        };
        let glide = Glide::new(from, to);
        assert_eq!(glide.at(glide.start), (from, false));
        let mut last = from.y;
        let steps = 20;
        for step in 1..steps {
            let (at, done) = glide.at(glide.start + glide.duration * step / steps);
            assert!(!done && at.y < last, "step {step}: {at:?}");
            last = at.y;
        }
        assert_eq!(glide.at(glide.start + glide.duration), (to, true));
        assert!(glide_duration(10.) < glide_duration(400.));
    }

    #[test]
    fn the_three_fixed_alignments_are_arithmetic() {
        let (t0, tl, v0, vl) = (500.0, 40.0, 100.0, 200.0);
        assert_eq!(align_delta(Align::Start, t0, tl, v0, vl), 400.0);
        assert_eq!(align_delta(Align::End, t0, tl, v0, vl), 240.0);
        assert_eq!(align_delta(Align::Center, t0, tl, v0, vl), 320.0);
    }

    #[test]
    fn nearest_moves_only_the_edge_that_is_out() {
        let (v0, vl) = (100.0, 200.0);
        assert_eq!(align_delta(Align::Nearest, 150.0, 40.0, v0, vl), 0.0);
        assert_eq!(align_delta(Align::Nearest, 40.0, 30.0, v0, vl), -60.0);
        assert_eq!(align_delta(Align::Nearest, 400.0, 30.0, v0, vl), 130.0);
        assert_eq!(align_delta(Align::Nearest, 0.0, 1000.0, v0, vl), 0.0);
    }

    /// An element exactly flush with an edge is inside: otherwise `scrollIntoView` on an aligned row jitters.
    #[test]
    fn nearest_treats_a_flush_edge_as_visible() {
        assert_eq!(align_delta(Align::Nearest, 100.0, 200.0, 100.0, 200.0), 0.0);
        assert_eq!(align_delta(Align::Nearest, 100.0, 50.0, 100.0, 200.0), 0.0);
        assert_eq!(align_delta(Align::Nearest, 250.0, 50.0, 100.0, 200.0), 0.0);
    }
}