Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

scroll-anchor.test.ts

85 lines2.4 KB

1import { describe, expect, it } from "vite-plus/test";
2​
3import { anchorAt, scrollTopForAnchor } from "./scroll-anchor";
4import type { AnchorBox, ScrollAnchor } from "./scroll-anchor";
5​
6const boxes: AnchorBox[] = [
7 { id: "intro", top: -300, bottom: 100 },
8 { id: "collections", top: 120, bottom: 600 },
9 { id: "live-queries", top: 600, bottom: 900 },
10];
11​
12describe("anchorAt", () => {
13 it("finds the anchor that spans the line", () => {
14 expect(anchorAt(boxes, 0)?.id).toBe("intro");
15 expect(anchorAt(boxes, 300)?.id).toBe("collections");
16 expect(anchorAt(boxes, 600)?.id).toBe("live-queries");
17 });
18​
19 it("keeps the anchor above when the line falls in a gap", () => {
20 expect(anchorAt(boxes, 110)?.id).toBe("intro");
21 });
22​
23 it("returns nothing above the first anchor", () => {
24 expect(anchorAt(boxes, -301)).toBeUndefined();
25 expect(anchorAt([], 0)).toBeUndefined();
26 });
27});
28​
29describe("scrollTopForAnchor", () => {
30 const saved: ScrollAnchor = { scrollTop: 1000, anchorId: "collections", anchorTop: -40 };
31​
32 it("returns the same position when nothing moved", () => {
33 expect(
34 scrollTopForAnchor({
35 saved,
36 currentScrollTop: 1000,
37 currentAnchorTop: -40,
38 maxScrollTop: 5000,
39 }),
40 ).toBe(1000);
41 });
42​
43 it("follows the anchor when content above it grew", () => {
44 // A 24px "You did it" row appeared above the anchor.
45 expect(
46 scrollTopForAnchor({
47 saved,
48 currentScrollTop: 1000,
49 currentAnchorTop: -16,
50 maxScrollTop: 5000,
51 }),
52 ).toBe(1024);
53 });
54​
55 it("works when the view was scrolled away in the meantime", () => {
56 expect(
57 scrollTopForAnchor({ saved, currentScrollTop: 0, currentAnchorTop: 960, maxScrollTop: 5000 }),
58 ).toBe(1000);
59 });
60​
61 it("falls back to the raw position when the anchor is gone", () => {
62 expect(
63 scrollTopForAnchor({
64 saved,
65 currentScrollTop: 0,
66 currentAnchorTop: undefined,
67 maxScrollTop: 5000,
68 }),
69 ).toBe(1000);
70 });
71​
72 it("clamps to the scroll range", () => {
73 expect(
74 scrollTopForAnchor({ saved, currentScrollTop: 0, currentAnchorTop: 960, maxScrollTop: 700 }),
75 ).toBe(700);
76 expect(
77 scrollTopForAnchor({
78 saved: { scrollTop: 0, anchorId: null, anchorTop: 0 },
79 currentScrollTop: 50,
80 currentAnchorTop: undefined,
81 maxScrollTop: -10,
82 }),
83 ).toBe(0);
84 });
85});