Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useRestingTopOffset.test.tsx

73 lines2.1 KB

1import { act, useLayoutEffect } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, describe, expect, it } from "vite-plus/test";
4​
5import { useRestingTopOffset } from "./useRestingTopOffset";
6​
7let root: Root | null = null;
8let latest: ReturnType<typeof useRestingTopOffset> | null = null;
9​
10function Probe(props: { readonly topInset: number; readonly restoredOffset?: number }) {
11 const restingOffset = useRestingTopOffset(
12 props.topInset,
13 props.restoredOffset === undefined ? {} : { contentOffset: { x: 0, y: props.restoredOffset } },
14 );
15 useLayoutEffect(() => {
16 latest = restingOffset;
17 });
18 return null;
20​
21function render(topInset: number, restoredOffset?: number) {
22 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
23 root ??= createRoot(document.createElement("div"));
24 act(() => root!.render(<Probe topInset={topInset} restoredOffset={restoredOffset} />));
26​
27function scrollTo(y: number) {
28 const event = { nativeEvent: { contentOffset: { x: 0, y } } } as Parameters<
29 ReturnType<typeof useRestingTopOffset>["onScroll"]
30 >[0];
31 act(() => latest!.onScroll(event));
33​
34function offset() {
35 return latest!.contentOffset.y;
37​
38afterEach(() => {
39 act(() => root?.unmount());
40 root = null;
41 latest = null;
42});
43​
44describe("useRestingTopOffset", () => {
45 it("keeps an untouched list below the header once the column's inset arrives", () => {
46 // The folded iPhone Duo's window has no top inset; the header's arrives after mount.
47 render(0);
48 render(54);
49 expect(offset()).toBe(-54);
50 });
51​
52 it("does not move a list the reader scrolled when the inset changes", () => {
53 render(54);
54 scrollTo(300);
55 render(90);
56 expect(offset()).toBe(-54);
57 });
58​
59 it("follows the inset again once the list is back at the top", () => {
60 render(54);
61 scrollTo(300);
62 render(90);
63 scrollTo(-90);
64 render(54);
65 expect(offset()).toBe(-54);
66 });
67​
68 it("holds a restored position through an inset change", () => {
69 render(0, 1_200);
70 render(54);
71 expect(offset()).toBe(1_200);
72 });
73});