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

WorkLog.browser.test.tsx

101 lines2.6 KB

1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4import { WorkLogDetails } from "./WorkLog";
5​
6// The scroller's geometry is simulated so the test controls it: a 384px
7// viewport over content whose height the test grows like a streamed trace.
8const VIEWPORT = 384;
9let contentHeight = 0;
10let scrollTop = 0;
11​
12let root: Root;
13let host: HTMLDivElement;
14​
15function render(followLive: boolean, text: string) {
16 act(() => {
17 root.render(
18 <WorkLogDetails followLive={followLive}>
19 <p>{text}</p>
20 </WorkLogDetails>,
21 );
22 });
24​
25function scroller() {
26 const element = host.firstElementChild;
27 if (!(element instanceof HTMLDivElement)) throw new Error("missing scroller");
28 return element;
30​
31function stream(followLive: boolean, text: string) {
32 contentHeight += 200;
33 render(followLive, text);
35​
36function readerScrollsTo(top: number) {
37 scroller().scrollTop = top;
38 act(() => {
39 scroller().dispatchEvent(new Event("scroll"));
40 });
42​
43const maxScrollTop = () => contentHeight - VIEWPORT;
44​
45beforeEach(() => {
46 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
47 contentHeight = 1000;
48 scrollTop = 0;
49 Object.defineProperties(HTMLDivElement.prototype, {
50 clientHeight: { configurable: true, get: () => VIEWPORT },
51 scrollHeight: { configurable: true, get: () => contentHeight },
52 scrollTop: {
53 configurable: true,
54 get: () => scrollTop,
55 set: (value: number) => {
56 scrollTop = Math.max(0, Math.min(value, maxScrollTop()));
57 },
58 },
59 });
60 host = document.createElement("div");
61 document.body.append(host);
62 root = createRoot(host);
63});
64​
65afterEach(() => {
66 act(() => root.unmount());
67 host.remove();
68 for (const key of ["clientHeight", "scrollHeight", "scrollTop"]) {
69 Reflect.deleteProperty(HTMLDivElement.prototype, key);
70 }
71 vi.unstubAllGlobals();
72});
73​
74describe("WorkLogDetails followLive", () => {
75 it("keeps the newest streamed text in view", () => {
76 render(true, "a");
77 expect(scrollTop).toBe(maxScrollTop());
78​
79 stream(true, "ab");
80 stream(true, "abc");
81 expect(scrollTop).toBe(maxScrollTop());
82 });
83​
84 it("stops following when the reader scrolls up and resumes at the end", () => {
85 render(true, "a");
86 readerScrollsTo(100);
87​
88 stream(true, "ab");
89 expect(scrollTop).toBe(100);
90​
91 readerScrollsTo(maxScrollTop());
92 stream(true, "abc");
93 expect(scrollTop).toBe(maxScrollTop());
94 });
95​
96 it("does not move a trace that is not streaming", () => {
97 render(false, "a");
98 stream(false, "ab");
99 expect(scrollTop).toBe(0);
100 });
101});