// : loading the next page when the link nears the viewport or is // activated, appending the answer's items, taking its next link or ending the // feed, one fetch at a time, the retry after a failure, and the announcement. // IntersectionObserver and fetch are fakes; real scrolling is the smoke's job // (examples/more.html). import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"; import { ROOT_MARGIN } from "../packages/more/index"; import styles from "../packages/more/more.css"; const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms)); type Callback = (entries: { isIntersecting: boolean; target: Element }[]) => void; const observers: FakeObserver[] = []; class FakeObserver { targets = new Set(); constructor( public callback: Callback, public options: IntersectionObserverInit, ) { observers.push(this); } observe(target: Element) { this.targets.add(target); } unobserve(target: Element) { this.targets.delete(target); } disconnect() { this.targets.clear(); } } /** Bring every observed link into view. */ const intersect = () => { for (const o of observers) if (o.targets.size) o.callback([...o.targets].map(target => ({ isIntersecting: true, target }))); }; const page = (items: string[], next?: string) => `
    ${items.map(i => `
  1. ${i}
  2. `).join("")}
` + (next ? `Voir plus` : "") + `
`; let calls: { url: string; init: RequestInit }[] = []; let answers: Array<() => Promise> = []; const realFetch = globalThis.fetch; const realObserver = globalThis.IntersectionObserver; const happy = (window as unknown as { happyDOM: { setURL(url: string): void } }).happyDOM; beforeAll(() => happy.setURL("https://cine.example/fil")); afterAll(() => happy.setURL("about:blank")); beforeEach(() => { calls = []; answers = []; observers.length = 0; globalThis.IntersectionObserver = FakeObserver as unknown as typeof IntersectionObserver; globalThis.fetch = (async (url: string | URL, init: RequestInit = {}) => { calls.push({ url: String(url), init }); const next = answers.shift(); if (!next) throw new Error("no answer queued"); return next(); }) as typeof fetch; }); afterEach(async () => { globalThis.fetch = realFetch; globalThis.IntersectionObserver = realObserver; document.body.textContent = ""; await sleep(0); }); const mount = (attrs = "") => { const wrap = document.createElement("div"); wrap.innerHTML = `
  1. un
  2. deux
` + `Voir plus`; document.body.appendChild(wrap); const host = wrap.querySelector("pebble-more") as HTMLElement; return { host, list: wrap.querySelector("#fil")!, link: () => host.querySelector("a[data-more]") }; }; const texts = (list: Element) => [...list.children].map(li => li.textContent); const html = (body: string, status = 200) => async () => new Response(body, { status, headers: { "content-type": "text/html" } }); test("watches the link 600px ahead and loads the next page into the previous sibling", async () => { const { host, list, link } = mount('announce="{n} de plus"'); expect(observers[0]!.options.rootMargin).toBe(ROOT_MARGIN); expect([...observers[0]!.targets]).toEqual([link()!]); answers.push(html(page(["trois", "quatre"], "/fil?apres=4"))); intersect(); expect(host.hasAttribute("data-loading")).toBe(true); expect(link()!.hidden).toBe(true); await sleep(5); expect(calls[0]!.url).toBe("https://cine.example/fil?apres=2"); const headers = calls[0]!.init.headers as Record; expect(headers.Accept).toBe("text/html"); expect(headers["X-Fragment"]).toBe("1"); expect(texts(list)).toEqual(["un", "deux", "trois", "quatre"]); expect(link()!.getAttribute("href")).toBe("/fil?apres=4"); expect(link()!.hidden).toBe(false); expect(host.hasAttribute("data-loading")).toBe(false); expect(host.querySelector("[role=status]")!.textContent).toBe("2 de plus"); expect([...observers[0]!.targets]).toEqual([link()!]); // the new link is watched }); test("an answer without a next link ends the feed; the URL is left alone", async () => { const { host, list, link } = mount(); answers.push(html(page(["fin"]))); link()!.click(); await sleep(5); expect(texts(list)).toEqual(["un", "deux", "fin"]); expect(link()).toBeNull(); expect(host.isConnected).toBe(true); expect(host.hasAttribute("data-done")).toBe(true); expect(host.querySelector("[role=status]")!.textContent).toBe("1 more"); expect(observers[0]!.targets.size).toBe(0); expect(location.href).toBe("https://cine.example/fil"); }); test("one fetch at a time", async () => { const { link } = mount(); let resolve!: (r: Response) => void; answers.push(() => new Promise(r => (resolve = r))); intersect(); intersect(); link()!.click(); expect(calls.length).toBe(1); resolve(new Response(page(["trois"], "/fil?apres=3"))); await sleep(5); expect(calls.length).toBe(1); }); test("a failure shows the link again; only a click retries", async () => { const { host, list, link } = mount(); answers.push(html("boom", 500)); intersect(); await sleep(5); expect(link()!.hidden).toBe(false); expect(host.hasAttribute("data-error")).toBe(true); intersect(); // the observer no longer loads by itself expect(calls.length).toBe(1); answers.push(html(page(["trois"], "/fil?apres=3"))); link()!.click(); await sleep(5); expect(calls.length).toBe(2); expect(texts(list)).toEqual(["un", "deux", "trois"]); expect(host.hasAttribute("data-error")).toBe(false); }); test("an answer without [data-feed-items] is a failure", async () => { const { host, link } = mount(); answers.push(html("

Erreur

")); link()!.click(); await sleep(5); expect(host.hasAttribute("data-error")).toBe(true); expect(link()!.hidden).toBe(false); }); test("for names the list; a click from the keyboard focuses the first new item", async () => { const wrap = document.createElement("div"); wrap.innerHTML = `
  1. a

entre

Voir plus`; document.body.appendChild(wrap); const link = wrap.querySelector("a[data-more]")!; answers.push(html(page(["b", "c"], "/p3"))); link.focus(); link.click(); await sleep(5); const list = wrap.querySelector("#ailleurs")!; expect(texts(list)).toEqual(["a", "b", "c"]); expect(document.activeElement).toBe(list.children[1]!); expect(list.children[1]!.getAttribute("tabindex")).toBe("-1"); }); test("a modified click is the browser's (a new tab)", () => { const { link } = mount(); const event = new MouseEvent("click", { bubbles: true, cancelable: true, ctrlKey: true }); link()!.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); expect(calls.length).toBe(0); }); test("the same announcement twice is still a change", async () => { const { host } = mount(); answers.push(html(page(["x"], "/a")), html(page(["y"], "/b"))); intersect(); await sleep(5); const first = host.querySelector("[role=status]")!.textContent; intersect(); await sleep(5); expect(host.querySelector("[role=status]")!.textContent).not.toBe(first); }); test("the sheet: 44px target, a hidden status, the reduced-motion and dark defaults", () => { expect(styles).toContain("44px"); expect(styles).toContain("prefers-reduced-motion"); expect(styles).toContain("prefers-color-scheme:dark"); expect(styles).toContain("--pebble-more-"); });