tobogganSe connecter

library

Prebuilt pebble components: drop-in custom elements, no compiler needed

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

Dernier runAucun
0Étoiles
0Forks
2Issues
199 lignes · 7783 octetsBrut · Historique
1// <pebble-more>: loading the next page when the link nears the viewport or is
2// activated, appending the answer's items, taking its next link or ending the
3// feed, one fetch at a time, the retry after a failure, and the announcement.
4// IntersectionObserver and fetch are fakes; real scrolling is the smoke's job
5// (examples/more.html).
6import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test";
7import { ROOT_MARGIN } from "../packages/more/index";
8import styles from "../packages/more/more.css";
9
10const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
11
12type Callback = (entries: { isIntersecting: boolean; target: Element }[]) => void;
13const observers: FakeObserver[] = [];
14class FakeObserver {
15 targets = new Set<Element>();
16 constructor(
17 public callback: Callback,
18 public options: IntersectionObserverInit,
19 ) {
20 observers.push(this);
21 }
22 observe(target: Element) {
23 this.targets.add(target);
24 }
25 unobserve(target: Element) {
26 this.targets.delete(target);
27 }
28 disconnect() {
29 this.targets.clear();
30 }
31}
32/** Bring every observed link into view. */
33const intersect = () => {
34 for (const o of observers) if (o.targets.size) o.callback([...o.targets].map(target => ({ isIntersecting: true, target })));
35};
36
37const page = (items: string[], next?: string) =>
38 `<!doctype html><main><ol data-feed-items>${items.map(i => `<li>${i}</li>`).join("")}</ol>` +
39 (next ? `<pebble-more><a href="${next}" data-more>Voir plus</a></pebble-more>` : "") +
40 `</main>`;
41
42let calls: { url: string; init: RequestInit }[] = [];
43let answers: Array<() => Promise<Response>> = [];
44const realFetch = globalThis.fetch;
45const realObserver = globalThis.IntersectionObserver;
46const happy = (window as unknown as { happyDOM: { setURL(url: string): void } }).happyDOM;
47
48beforeAll(() => happy.setURL("https://cine.example/fil"));
49afterAll(() => happy.setURL("about:blank"));
50
51beforeEach(() => {
52 calls = [];
53 answers = [];
54 observers.length = 0;
55 globalThis.IntersectionObserver = FakeObserver as unknown as typeof IntersectionObserver;
56 globalThis.fetch = (async (url: string | URL, init: RequestInit = {}) => {
57 calls.push({ url: String(url), init });
58 const next = answers.shift();
59 if (!next) throw new Error("no answer queued");
60 return next();
61 }) as typeof fetch;
62});
63
64afterEach(async () => {
65 globalThis.fetch = realFetch;
66 globalThis.IntersectionObserver = realObserver;
67 document.body.textContent = "";
68 await sleep(0);
69});
70
71const mount = (attrs = "") => {
72 const wrap = document.createElement("div");
73 wrap.innerHTML =
74 `<ol id="fil" data-feed-items><li>un</li><li>deux</li></ol>` +
75 `<pebble-more ${attrs}><a href="/fil?apres=2" data-more>Voir plus</a></pebble-more>`;
76 document.body.appendChild(wrap);
77 const host = wrap.querySelector("pebble-more") as HTMLElement;
78 return { host, list: wrap.querySelector("#fil")!, link: () => host.querySelector<HTMLAnchorElement>("a[data-more]") };
79};
80const texts = (list: Element) => [...list.children].map(li => li.textContent);
81const html = (body: string, status = 200) => async () => new Response(body, { status, headers: { "content-type": "text/html" } });
82
83test("watches the link 600px ahead and loads the next page into the previous sibling", async () => {
84 const { host, list, link } = mount('announce="{n} de plus"');
85 expect(observers[0]!.options.rootMargin).toBe(ROOT_MARGIN);
86 expect([...observers[0]!.targets]).toEqual([link()!]);
87
88 answers.push(html(page(["trois", "quatre"], "/fil?apres=4")));
89 intersect();
90 expect(host.hasAttribute("data-loading")).toBe(true);
91 expect(link()!.hidden).toBe(true);
92 await sleep(5);
93
94 expect(calls[0]!.url).toBe("https://cine.example/fil?apres=2");
95 const headers = calls[0]!.init.headers as Record<string, string>;
96 expect(headers.Accept).toBe("text/html");
97 expect(headers["X-Fragment"]).toBe("1");
98 expect(texts(list)).toEqual(["un", "deux", "trois", "quatre"]);
99 expect(link()!.getAttribute("href")).toBe("/fil?apres=4");
100 expect(link()!.hidden).toBe(false);
101 expect(host.hasAttribute("data-loading")).toBe(false);
102 expect(host.querySelector("[role=status]")!.textContent).toBe("2 de plus");
103 expect([...observers[0]!.targets]).toEqual([link()!]); // the new link is watched
104});
105
106test("an answer without a next link ends the feed; the URL is left alone", async () => {
107 const { host, list, link } = mount();
108 answers.push(html(page(["fin"])));
109 link()!.click();
110 await sleep(5);
111 expect(texts(list)).toEqual(["un", "deux", "fin"]);
112 expect(link()).toBeNull();
113 expect(host.isConnected).toBe(true);
114 expect(host.hasAttribute("data-done")).toBe(true);
115 expect(host.querySelector("[role=status]")!.textContent).toBe("1 more");
116 expect(observers[0]!.targets.size).toBe(0);
117 expect(location.href).toBe("https://cine.example/fil");
118});
119
120test("one fetch at a time", async () => {
121 const { link } = mount();
122 let resolve!: (r: Response) => void;
123 answers.push(() => new Promise(r => (resolve = r)));
124 intersect();
125 intersect();
126 link()!.click();
127 expect(calls.length).toBe(1);
128 resolve(new Response(page(["trois"], "/fil?apres=3")));
129 await sleep(5);
130 expect(calls.length).toBe(1);
131});
132
133test("a failure shows the link again; only a click retries", async () => {
134 const { host, list, link } = mount();
135 answers.push(html("boom", 500));
136 intersect();
137 await sleep(5);
138 expect(link()!.hidden).toBe(false);
139 expect(host.hasAttribute("data-error")).toBe(true);
140 intersect(); // the observer no longer loads by itself
141 expect(calls.length).toBe(1);
142
143 answers.push(html(page(["trois"], "/fil?apres=3")));
144 link()!.click();
145 await sleep(5);
146 expect(calls.length).toBe(2);
147 expect(texts(list)).toEqual(["un", "deux", "trois"]);
148 expect(host.hasAttribute("data-error")).toBe(false);
149});
150
151test("an answer without [data-feed-items] is a failure", async () => {
152 const { host, link } = mount();
153 answers.push(html("<p>Erreur</p>"));
154 link()!.click();
155 await sleep(5);
156 expect(host.hasAttribute("data-error")).toBe(true);
157 expect(link()!.hidden).toBe(false);
158});
159
160test("for names the list; a click from the keyboard focuses the first new item", async () => {
161 const wrap = document.createElement("div");
162 wrap.innerHTML = `<ol id="ailleurs" data-feed-items><li>a</li></ol><p>entre</p><pebble-more for="ailleurs"><a href="/p2" data-more>Voir plus</a></pebble-more>`;
163 document.body.appendChild(wrap);
164 const link = wrap.querySelector<HTMLAnchorElement>("a[data-more]")!;
165 answers.push(html(page(["b", "c"], "/p3")));
166 link.focus();
167 link.click();
168 await sleep(5);
169 const list = wrap.querySelector("#ailleurs")!;
170 expect(texts(list)).toEqual(["a", "b", "c"]);
171 expect(document.activeElement).toBe(list.children[1]!);
172 expect(list.children[1]!.getAttribute("tabindex")).toBe("-1");
173});
174
175test("a modified click is the browser's (a new tab)", () => {
176 const { link } = mount();
177 const event = new MouseEvent("click", { bubbles: true, cancelable: true, ctrlKey: true });
178 link()!.dispatchEvent(event);
179 expect(event.defaultPrevented).toBe(false);
180 expect(calls.length).toBe(0);
181});
182
183test("the same announcement twice is still a change", async () => {
184 const { host } = mount();
185 answers.push(html(page(["x"], "/a")), html(page(["y"], "/b")));
186 intersect();
187 await sleep(5);
188 const first = host.querySelector("[role=status]")!.textContent;
189 intersect();
190 await sleep(5);
191 expect(host.querySelector("[role=status]")!.textContent).not.toBe(first);
192});
193
194test("the sheet: 44px target, a hidden status, the reduced-motion and dark defaults", () => {
195 expect(styles).toContain("44px");
196 expect(styles).toContain("prefers-reduced-motion");
197 expect(styles).toContain("prefers-color-scheme:dark");
198 expect(styles).toContain("--pebble-more-");
199});