gpui-fast 0.1.20

gpui: GPUI with gpui-fast rendering and layout optimizations
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
// Modified by Longbridge for gpui-fast.
//! The accessibility tree a window builds while drawing views and scroll
//! layers again from the last frame must be the tree it would build drawing
//! every frame from scratch. See `crate::fast::a11y`.
//!
//! The oracles (`oracle.rs`, `layers_oracle.rs`) compare whole trees over
//! random histories with [`a11y_snapshot`] and [`a11y_difference`]; the tests
//! here pin down single cases.

use std::fmt::Write as _;

use accesskit::{NodeId, Role};

use crate::{
    Context, Entity, FocusHandle, IntoElement, Render, TestAppContext, Window, div, prelude::*, px,
};

/// One node of a window's accessibility tree, named by where it is rather
/// than by its id: two windows drawing the same views have different view
/// ids, so different node ids.
#[derive(Debug)]
pub(super) struct A11yEntry {
    /// The child indices from the root down to the node.
    path: String,
    /// The node, its children and bounds left out.
    node: String,
    rect: Option<accesskit::Rect>,
    /// What a click on it would hit, in logical pixels.
    click_bounds: Option<crate::Bounds<crate::Pixels>>,
    focusable: bool,
    actions: Vec<String>,
}

/// A window's last accessibility tree, as [`A11yEntry`]s in depth-first
/// order, after the path of the focused node.
pub(super) fn a11y_snapshot(window: &Window) -> (String, Vec<A11yEntry>) {
    let tree = crate::fast::a11y::last_tree(window).expect("accessibility is active");
    let nodes: collections::FxHashMap<NodeId, &accesskit::Node> =
        tree.nodes.iter().map(|(id, node)| (*id, node)).collect();
    assert_eq!(nodes.len(), tree.nodes.len(), "a node id twice in the tree");
    let mut entries = Vec::new();
    let mut focus = String::from("unreachable");
    let mut stack = vec![(crate::window::a11y::ROOT_NODE_ID, String::from("r"))];
    while let Some((id, path)) = stack.pop() {
        let node = nodes[&id];
        if id == tree.focus {
            focus = path.clone();
        }
        for (ix, child) in node.children().iter().enumerate().rev() {
            stack.push((*child, format!("{path}.{ix}")));
        }
        let mut bare = node.clone();
        bare.clear_children();
        bare.clear_bounds();
        let mut actions: Vec<String> = window
            .a11y
            .action_listeners
            .get(&id)
            .map(|listeners| {
                listeners
                    .iter()
                    .map(|(action, _)| format!("{action:?}"))
                    .collect()
            })
            .unwrap_or_default();
        actions.sort();
        entries.push(A11yEntry {
            path,
            node: format!("{bare:?}"),
            rect: node.bounds(),
            click_bounds: window.a11y.node_bounds.get(&id).copied(),
            focusable: window.a11y.focus_ids.contains_key(&id),
            actions,
        });
    }
    assert_eq!(
        entries.len(),
        tree.nodes.len(),
        "a node in the tree that is not reachable from its root"
    );
    (focus, entries)
}

/// How `actual` differs from `expected`, bounds compared to within
/// `epsilon` device pixels, if it does.
pub(super) fn a11y_difference(
    actual: &(String, Vec<A11yEntry>),
    expected: &(String, Vec<A11yEntry>),
    epsilon: f64,
) -> Option<String> {
    let mut out = String::new();
    if actual.0 != expected.0 {
        writeln!(out, "focus at {} instead of {}", actual.0, expected.0).unwrap();
    }
    let close = |a: f64, b: f64| (a - b).abs() <= epsilon;
    let rects_match = |a: &Option<accesskit::Rect>, b: &Option<accesskit::Rect>| match (a, b) {
        (Some(a), Some(b)) => {
            close(a.x0, b.x0) && close(a.y0, b.y0) && close(a.x1, b.x1) && close(a.y1, b.y1)
        }
        (None, None) => true,
        _ => false,
    };
    let bounds_match = |a: &Option<crate::Bounds<crate::Pixels>>,
                        b: &Option<crate::Bounds<crate::Pixels>>| match (
        a, b,
    ) {
        (Some(a), Some(b)) => {
            close(a.origin.x.0 as f64, b.origin.x.0 as f64)
                && close(a.origin.y.0 as f64, b.origin.y.0 as f64)
                && close(a.size.width.0 as f64, b.size.width.0 as f64)
                && close(a.size.height.0 as f64, b.size.height.0 as f64)
        }
        (None, None) => true,
        _ => false,
    };
    for (a, e) in actual.1.iter().zip(&expected.1) {
        if a.path != e.path
            || a.node != e.node
            || !rects_match(&a.rect, &e.rect)
            || !bounds_match(&a.click_bounds, &e.click_bounds)
            || a.focusable != e.focusable
            || a.actions != e.actions
        {
            writeln!(out, "  actual:   {a:?}\n  expected: {e:?}").unwrap();
            break;
        }
    }
    if actual.1.len() != expected.1.len() {
        writeln!(
            out,
            "{} nodes instead of {}",
            actual.1.len(),
            expected.1.len()
        )
        .unwrap();
    }
    (!out.is_empty()).then_some(out)
}

struct Item {
    label: usize,
    /// Whether its synthetic node has bounds of its own.
    placed: bool,
}

impl Render for Item {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .id("item")
            .role(Role::ListItem)
            .aria_label(format!("item {}", self.label))
            .when(self.label % 4 == 1, |this| this.aria_active_descendant())
            .h(px(20.))
            .child(
                div()
                    .id("inner")
                    .role(Role::Button)
                    .on_a11y_action(accesskit::Action::Click, |_, _, _| {})
                    .size(px(10.))
                    .a11y_synthetic_children({
                        let placed = self.placed;
                        move |builder| {
                            let id = builder.synthetic_node_id(0);
                            let mut node = accesskit::Node::new(Role::Image);
                            if placed {
                                node.set_bounds(accesskit::Rect {
                                    x0: 1.,
                                    y0: 2.,
                                    x1: 3.,
                                    y1: 4.,
                                });
                            }
                            builder.push_child(id, node);
                        }
                    }),
            )
    }
}

struct ListView {
    items: Vec<Entity<Item>>,
    focus: FocusHandle,
    title: usize,
}

impl Render for ListView {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .id("list")
            .role(Role::List)
            .track_focus(&self.focus)
            .aria_label(format!("list {}", self.title))
            .flex()
            .flex_col()
            .children(self.items.iter().cloned())
    }
}

fn snapshot(cx: &mut TestAppContext, window: crate::WindowHandle<ListView>) -> String {
    cx.update_window(window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        let (focus, entries) = a11y_snapshot(window);
        let mut out = format!("focus {focus}\n");
        for entry in entries {
            writeln!(out, "{entry:?}").unwrap();
        }
        out
    })
    .unwrap()
}

/// Draws the same history in a window retaining views and one refreshed
/// every frame, comparing their trees.
#[crate::test]
fn reused_and_spliced_views_keep_their_accessibility_nodes(cx: &mut TestAppContext) {
    let open = |cx: &mut TestAppContext| {
        cx.add_window(|_, cx| ListView {
            items: (0..4)
                .map(|label| {
                    cx.new(|_| Item {
                        label,
                        placed: true,
                    })
                })
                .collect(),
            focus: cx.focus_handle(),
            title: 0,
        })
    };
    let retained = open(cx);
    let scratch = open(cx);
    for window in [retained, scratch] {
        cx.update_window(window.into(), |_, window, _| {
            window.set_a11y_active_for_tests(true)
        })
        .unwrap();
    }
    let step = |cx: &mut TestAppContext, f: &dyn Fn(&mut ListView, &mut Context<ListView>)| {
        for window in [retained, scratch] {
            window.update(cx, |view, _, cx| f(view, cx)).unwrap();
        }
        cx.update_window(scratch.into(), |_, window, _| window.refresh())
            .unwrap();
        let expected = snapshot(cx, scratch);
        let actual = snapshot(cx, retained);
        assert_eq!(actual, expected);
        cx.update_window(retained.into(), |_, window, _| {
            window.rendered_frame.retained.reused_any()
        })
        .unwrap()
    };
    step(cx, &|_, _| {});
    // Nothing changed: every item is drawn from the last frame.
    assert!(step(cx, &|_, cx| cx.notify()));
    // One item changed: the list is drawn around it.
    assert!(step(cx, &|view, cx| {
        view.items[2].update(cx, |item, cx| {
            item.label = 6;
            cx.notify();
        })
    }));
    // The list focused: its items claim to be its active descendant.
    for window in [retained, scratch] {
        cx.update_window(window.into(), |view, window, cx| {
            let focus = view.downcast::<ListView>().unwrap().read(cx).focus.clone();
            window.focus(&focus, cx);
        })
        .unwrap();
    }
    step(cx, &|_, _| {});
    assert!(step(cx, &|view, cx| {
        view.items[1].update(cx, |item, cx| {
            item.label = 7;
            cx.notify();
        })
    }));
    assert!(step(cx, &|view, cx| {
        view.title += 1;
        cx.notify()
    }));
}

/// A frame drawn after accessibility was turned on draws nothing from a
/// frame drawn without it, which logged no accessibility nodes.
#[crate::test]
fn turning_accessibility_on_builds_every_view(cx: &mut TestAppContext) {
    let window = cx.add_window(|_, cx| ListView {
        items: (0..3)
            .map(|label| {
                cx.new(|_| Item {
                    label,
                    placed: true,
                })
            })
            .collect(),
        focus: cx.focus_handle(),
        title: 0,
    });
    cx.update_window(window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.draw(cx).clear(cx);
        crate::fast::a11y::set_active_flag(&window.a11y, true);
        window.draw(cx).clear(cx);
        assert!(!window.rendered_frame.retained.reused_any());
        let (_, entries) = a11y_snapshot(window);
        // The window, the list, and an item, its button and its image each.
        assert_eq!(entries.len(), 2 + 3 * 3);
        window.draw(cx).clear(cx);
        assert!(window.rendered_frame.retained.reused_any());
        let (_, again) = a11y_snapshot(window);
        assert_eq!(format!("{again:?}"), format!("{entries:?}"));
    })
    .unwrap();
}

struct SyntheticTree;

impl Render for SyntheticTree {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .id("synthetic-tree")
            .role(Role::Group)
            .a11y_synthetic_children(|builder| {
                let parent_id = builder.synthetic_node_id("parent");
                let child_id = builder.synthetic_node_id("child");
                let mut parent = accesskit::Node::new(Role::Group);
                parent.set_children(vec![child_id]);
                builder.push_child(child_id, accesskit::Node::new(Role::Button));
                builder.push_child(parent_id, parent);
                builder.parent_node().set_children(vec![parent_id]);
            })
    }
}

struct SyntheticHost(Entity<SyntheticTree>);

impl Render for SyntheticHost {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().child(self.0.clone())
    }
}

#[crate::test]
fn reused_synthetic_subtrees_keep_their_hierarchy(cx: &mut TestAppContext) {
    let window = cx.add_window(|_, cx| SyntheticHost(cx.new(|_| SyntheticTree)));
    cx.update_window(window.into(), |_, window, cx| {
        window.set_a11y_active_for_tests(true);
        window.draw(cx).clear(cx);
        let expected = a11y_snapshot(window);
        window.draw(cx).clear(cx);
        assert!(window.rendered_frame.retained.reused_any());
        let actual = a11y_snapshot(window);
        assert_eq!(a11y_difference(&actual, &expected, 0.), None);
    })
    .unwrap();
}

/// A frame drawn with accessibility active keeps the tree it sent in
/// `A11yDebug::last_tree_update`, which views drawn again read their
/// finished nodes from.
#[crate::test]
fn a11y_frame_keeps_the_tree_it_sent(cx: &mut TestAppContext) {
    let window = cx.add_window(|_, cx| ListView {
        items: Vec::new(),
        focus: cx.focus_handle(),
        title: 0,
    });
    cx.update_window(window.into(), |_, window, cx| {
        crate::fast::a11y::set_active_flag(&window.a11y, true);
        window.draw(cx).clear(cx);
        assert!(crate::fast::a11y::last_tree(window).is_some());
    })
    .unwrap();
}

/// A page scrolling rows, some of them holding views, with accessibility
/// nodes.
struct ScrollPage {
    handle: crate::ScrollHandle,
    items: Vec<Entity<Item>>,
    placed: bool,
}

impl Render for ScrollPage {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size_full().bg(crate::white()).child(
            div()
                .id("scroller")
                .role(Role::ScrollView)
                .overflow_y_scroll()
                .track_scroll(&self.handle)
                .w(px(200.))
                .h(px(100.))
                .bg(crate::white())
                .children((0..40u32).map(|row| {
                    div()
                        .id(("row", row as usize))
                        .role(Role::Row)
                        .aria_label(format!("row {row}"))
                        .h(px(20.))
                        .bg(crate::rgb(0x100000 + row * 0x10))
                        .a11y_synthetic_children({
                            let placed = self.placed;
                            move |builder| {
                                let id = builder.synthetic_node_id(0);
                                let mut node = accesskit::Node::new(Role::Image);
                                if placed && let Some(bounds) = builder.parent_node().bounds() {
                                    node.set_bounds(bounds);
                                }
                                builder.push_child(id, node);
                            }
                        })
                        .when(row % 8 == 3, |this| {
                            this.child(self.items[row as usize / 8].clone())
                        })
                })),
        )
    }
}

/// A composited scroll layer adds its content's accessibility nodes moved
/// by the scroll since it was painted, as drawing the content would.
#[crate::test]
fn a_composited_layer_keeps_its_content_accessibility_nodes(cx: &mut TestAppContext) {
    assert_eq!(
        scroll_page_frames(cx, false) > 0,
        crate::fast::layers::COMPILED,
        "no frame composited the layer"
    );
}

/// Content holding synthetic nodes its code placed is painted again on
/// every scrolled frame rather than moved: nothing says the code places them
/// where its element is.
#[crate::test]
fn a_layer_holding_placed_synthetic_nodes_is_not_composited(cx: &mut TestAppContext) {
    assert_eq!(scroll_page_frames(cx, true), 0);
}

/// Scrolls a [`ScrollPage`] with layers and one without, comparing their
/// trees every frame, and returns how many frames composited the layer.
fn scroll_page_frames(cx: &mut TestAppContext, placed: bool) -> u64 {
    if !crate::fast::layers::COMPILED {
        return 0;
    }
    let open = |cx: &mut TestAppContext, layers: bool| {
        let window = cx.add_window(|_, cx| ScrollPage {
            handle: crate::ScrollHandle::new(),
            items: (0..5)
                .map(|label| cx.new(|_| Item { label, placed }))
                .collect(),
            placed,
        });
        cx.update_window(window.into(), |_, window, cx| {
            window.set_scroll_layers(layers);
            window.set_a11y_active_for_tests(true);
            window.draw(cx).clear(cx);
        })
        .unwrap();
        window
    };
    let layered = open(cx, true);
    let plain = open(cx, false);
    let mut composited = 0;
    for step in 0..30 {
        let dy = if step < 20 { -7.5 } else { 11. };
        let mut snapshots = Vec::new();
        for window in [layered, plain] {
            cx.update_window(window.into(), |_, window, cx| {
                let before = window.layout_stats();
                window.dispatch_event(
                    crate::PlatformInput::Scroll(crate::ScrollEvent {
                        position: crate::point(px(20.), px(20.)),
                        delta: crate::ScrollDelta::Pixels(crate::point(px(0.), px(dy))),
                        modifiers: Default::default(),
                        touch_phase: crate::TouchPhase::Moved,
                        ..Default::default()
                    }),
                    cx,
                );
                window.draw(cx).clear(cx);
                let after = window.layout_stats();
                if window.fast_layers.enabled {
                    composited += (after.layer_frames_composited - before.layer_frames_composited)
                        - (after.layer_frames_repainted - before.layer_frames_repainted);
                }
                snapshots.push(a11y_snapshot(window));
            })
            .unwrap();
        }
        if let Some(difference) = a11y_difference(&snapshots[0], &snapshots[1], 1e-3) {
            panic!("step {step}: the trees differ:\n{difference}");
        }
    }
    composited
}

/// Focusable elements, the first `shown` of `handles`.
struct TabStops {
    handles: Vec<FocusHandle>,
    shown: usize,
}

impl Render for TabStops {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size_full().children(
            self.handles[..self.shown]
                .iter()
                .enumerate()
                .map(|(ix, handle)| div().id(ix).track_focus(handle).w(px(10.)).h(px(10.))),
        )
    }
}

/// The accessibility dump counts the tab stops of the frame its tree was
/// captured from, and none once frames drawn without accessibility replaced
/// that frame on screen.
#[crate::test]
fn a11y_dump_counts_the_tab_stops_of_its_frame(cx: &mut TestAppContext) {
    let window = cx.add_window(|_, cx| TabStops {
        handles: (0..5).map(|_| cx.focus_handle().tab_stop(true)).collect(),
        shown: 3,
    });
    let tab_stop_count = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, _| {
            let json = window.debug_a11y_tree_json().expect("a tree was captured");
            serde_json::from_str::<serde_json::Value>(&json).unwrap()["frame"]["tab_stop_count"]
                .clone()
        })
        .unwrap()
    };
    cx.update_window(window.into(), |_, window, cx| {
        crate::fast::a11y::set_active_flag(&window.a11y, true);
        window.draw(cx).clear(cx);
    })
    .unwrap();
    assert_eq!(tab_stop_count(cx), serde_json::json!(3));

    cx.update_window(window.into(), |_, window, _| {
        crate::fast::a11y::set_active_flag(&window.a11y, false);
    })
    .unwrap();
    window
        .update(cx, |view, _, cx| {
            view.shown = 5;
            cx.notify();
        })
        .unwrap();
    cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
        .unwrap();
    assert_eq!(
        tab_stop_count(cx),
        serde_json::Value::Null,
        "the captured tree is older than the frame on screen"
    );
}

/// The dump's `rendered_at` is RFC 3339 in local time with milliseconds and a
/// `+hh:mm` offset, as it was when it was formatted with chrono's
/// `to_rfc3339_opts(SecondsFormat::Millis, false)`.
#[crate::test]
fn a11y_dump_rendered_at_is_rfc3339_local_time_with_milliseconds(cx: &mut TestAppContext) {
    let window = cx.add_window(|_, cx| TabStops {
        handles: vec![cx.focus_handle().tab_stop(true)],
        shown: 1,
    });
    cx.update_window(window.into(), |_, window, cx| {
        crate::fast::a11y::set_active_flag(&window.a11y, true);
        window.draw(cx).clear(cx);
    })
    .unwrap();
    let json = cx
        .update_window(window.into(), |_, window, _| {
            window.debug_a11y_tree_json().expect("a tree was captured")
        })
        .unwrap();
    let json: serde_json::Value = serde_json::from_str(&json).unwrap();
    let rendered_at = json["frame"]["rendered_at"]
        .as_str()
        .expect("the frame has a rendered_at string");

    // `YYYY-MM-DDTHH:MM:SS.mmm+HH:MM`
    assert_eq!(rendered_at.len(), 29, "{rendered_at}");
    assert_eq!(&rendered_at[19..20], ".", "{rendered_at}");
    assert!(matches!(&rendered_at[23..24], "+" | "-"), "{rendered_at}");

    let rendered_at: jiff::Timestamp = rendered_at.parse().expect("rendered_at is RFC 3339");
    let age = jiff::Timestamp::now().duration_since(rendered_at);
    assert!(
        age >= jiff::SignedDuration::ZERO && age < jiff::SignedDuration::from_secs(60),
        "{age:?}"
    );
}

/// The capture time prints the offset of the time zone it is formatted in,
/// and keeps milliseconds even when they are zero.
#[test]
fn a11y_captured_at_formats_in_its_time_zone() {
    let captured_at = |millis| {
        crate::fast::a11y::CapturedAt::from_timestamp(
            jiff::Timestamp::from_millisecond(millis).unwrap(),
        )
    };
    let utc = jiff::tz::TimeZone::UTC;
    let india =
        jiff::tz::TimeZone::fixed(jiff::tz::Offset::from_seconds(5 * 3600 + 30 * 60).unwrap());
    let newfoundland =
        jiff::tz::TimeZone::fixed(jiff::tz::Offset::from_seconds(-(3 * 3600 + 30 * 60)).unwrap());
    // 2025-07-01T23:59:58.123Z
    assert_eq!(
        captured_at(1_751_414_398_123).to_rfc3339_in(utc),
        "2025-07-01T23:59:58.123+00:00"
    );
    assert_eq!(
        captured_at(1_751_414_398_123).to_rfc3339_in(india),
        "2025-07-02T05:29:58.123+05:30"
    );
    assert_eq!(
        captured_at(1_751_414_398_000).to_rfc3339_in(newfoundland),
        "2025-07-01T20:29:58.000-03:30"
    );
}

struct TallRow {
    state: crate::ListState,
}

impl Render for TallRow {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        crate::list(self.state.clone(), |_, _, _| {
            div()
                .id("row")
                .role(Role::ListItem)
                .flex()
                .flex_col()
                .child(div().id("button").role(Role::Button).h(px(20.)))
                .child(
                    // Asks the list to show the row's bottom, below the
                    // viewport, as `reveal_range` on a text deep in the row
                    // does: the list scrolls and prepaints the row again.
                    crate::canvas(
                        |bounds, window, _| {
                            window.request_autoscroll(crate::Bounds::from_corners(
                                crate::point(bounds.left(), bounds.bottom() - px(10.)),
                                bounds.bottom_right(),
                            ));
                        },
                        |_, _, _, _| {},
                    )
                    .h(px(480.))
                    .w_full(),
                )
                .into_any()
        })
        .w_full()
        .h(px(100.))
    }
}

/// A list prepainting a row again to honor its autoscroll request rolls
/// back the accessibility nodes of the attempt it discards, as it rolls
/// back its hitboxes, so the row's nodes are not pushed twice.
#[crate::test]
fn an_autoscroll_retry_does_not_push_a_row_s_nodes_twice(cx: &mut TestAppContext) {
    let state = crate::ListState::new(1, crate::ListAlignment::Top, px(0.));
    let window = cx.add_window({
        let state = state.clone();
        move |_, _| TallRow { state }
    });
    cx.update_window(window.into(), |_, window, cx| {
        window.set_a11y_active_for_tests(true);
        // The window's first frame scrolled before accessibility was on.
        state.scroll_to(crate::ListOffset {
            item_ix: 0,
            offset_in_item: px(0.),
        });
        window.refresh();
        window.draw(cx).clear(cx);
        let (_, entries) = a11y_snapshot(window);
        // The window, the list's row and its button, each once.
        let buttons = entries
            .iter()
            .filter(|entry| entry.node.contains("Button"))
            .count();
        assert_eq!(buttons, 1, "{entries:#?}");
    })
    .unwrap();
    assert!(state.logical_scroll_top().offset_in_item > px(0.));
}

/// A header above a scrolled list of buttons, recording which one a click
/// reached.
struct ScrolledUnderHeader {
    handle: crate::ScrollHandle,
    clicked: std::rc::Rc<std::cell::RefCell<Vec<&'static str>>>,
}

impl Render for ScrolledUnderHeader {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let button = |name: &'static str| {
            let clicked = self.clicked.clone();
            div()
                .id(name)
                .role(Role::Button)
                .aria_label(name)
                .h(px(20.))
                .on_click(move |_, _, _| clicked.borrow_mut().push(name))
        };
        div().size_full().child(button("header")).child(
            div()
                .id("list")
                .h(px(40.))
                .overflow_y_scroll()
                .track_scroll(&self.handle)
                .children(["row-0", "row-1", "row-2", "row-3", "row-4"].map(button)),
        )
    }
}

/// A synthesized accessibility click goes to the part of the node its scroll
/// container shows, and to nothing when no part is shown, instead of to
/// whatever is drawn at the centre of its unclipped bounds (gpui-kit#3658).
#[crate::test]
fn a11y_click_reaches_only_the_visible_part_of_a_scrolled_node(cx: &mut TestAppContext) {
    let clicked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
    let handle = crate::ScrollHandle::new();
    let window = cx.add_window({
        let clicked = clicked.clone();
        let handle = handle.clone();
        move |_, _| ScrolledUnderHeader { handle, clicked }
    });
    cx.update_window(window.into(), |_, window, cx| {
        window.set_a11y_active_for_tests(true);
        window.draw(cx).clear(cx);
        // The list starts at y = 20. Scrolled by 30, row 0 lies at -10..10, all
        // of it under the header, and row 1 at 10..30, half of it shown.
        handle.set_offset(crate::point(px(0.), px(-30.)));
        window.refresh();
        window.draw(cx).clear(cx);

        let node = |window: &Window, name: &str| {
            crate::fast::a11y::last_tree(window)
                .expect("accessibility is active")
                .nodes
                .iter()
                .find(|(_, node)| node.label() == Some(name))
                .map(|(id, _)| *id)
                .expect("a node with this label")
        };
        let click = |window: &mut Window, cx: &mut crate::App, name: &str| {
            let target_node = node(window, name);
            window.handle_a11y_action(
                accesskit::ActionRequest {
                    action: accesskit::Action::Click,
                    target_tree: accesskit::TreeId::ROOT,
                    target_node,
                    data: None,
                },
                cx,
            );
        };

        click(window, cx, "row-0");
        assert!(
            clicked.borrow().is_empty(),
            "clicked {:?}",
            clicked.borrow()
        );
        click(window, cx, "row-1");
        assert_eq!(*clicked.borrow(), ["row-1"]);
        click(window, cx, "header");
        assert_eq!(*clicked.borrow(), ["row-1", "header"]);
    })
    .unwrap();
}