gui: Scroll to top and Scroll to bottom on a long page (emo172)

#1090 (emo172) asked for back-to-top and back-to-bottom buttons on the
main pages. Once a page is scrolled more than one window down, a small
capsule with two buttons, Scroll to top and Scroll to bottom, fades in.
It sits in the page's right margin when a wide window leaves one, and
otherwise over the page's corner, above Providers' sticky Add buttons.
It stays hidden near the top of the page, while a dialog is open, and
(over the corner) at the page's foot, where the last row can't scroll
out from under it, unless it has the pointer or keyboard focus. The
page's own height never changes for it, because app.js's scroll guard
measures that height.

A press goes through scrollOnPurpose, so the window's scroll guard
takes it as the reader's own scroll. It scrolls smoothly, or at once
under reduced motion, and the button at the end it already reached is
aria-disabled. Both buttons are real buttons, reachable by Tab, with a
label and tooltip in en, zh, zh-TW, ja and de. They are drawn from the
window's tokens in both themes, with no gradient and no coloured edge.

scrollends.js is imported on the window's first scroll, so the core
scripts carry one line in app.js, paid for by two comments cut from
the scroll guard's. No budget was raised. old-webkit lists scrollends.js among the lazy scripts.
docs/subsystems/gui-shell.md says where the capsule sits and when it
shows.

Run on mote at this head (on 2c90922b0, with the next commit):
- view-ends.test.cjs, 32 of 32: Chromium and WebKit, light and dark,
  420 and 1180 wide, every language. It checks that the capsule shows
  only past one window, that Scroll to bottom reaches the foot and stays
  there, and that the page is never taller under the capsule. It checks
  that the capsule is beside every row, or steps aside at the foot, and
  that Tab plus Enter on Scroll to top reaches 0 and stays.
- click-scroll, i18n-keys and old-webkit: ok.
- go test -run Budget ./internal/gui, gofmt -l, and go vet with
  GOOS=linux -tags nogui and with GOOS=windows: ok.
- The whole GUI suite at the pre-rebase head (5f0a84a00 + this):
  18,675 tests, 18,370 pass, 305 fail in 51 files. All 51 files were run
  again at 5f0a84a00 without this change, and 48 were red there too
  (297 fails).
  - The other three, import-row, provider-detect-models and
    routing-many-keys, and every test red at the head but not at the
    base, were run again alone at the head. They passed, or failed in a
    different engine or language than the first run, in the same tests
    that were red at the base. These are known load reds: #4389, #3488,
    #4585, #3415, #4127, #4126, #4244, #4082, #4619, #4431 and #4035.
  - old-webkit's red ("profilerename.js is not loaded by index.html")
    is on main since 1cb4d4301 and is fixed in the next commit.
- go test ./internal/gui: red only at TestMainWindowCorners on mote's
  macOS 27 (#3949), the same as on main.

Broken by hand:
- At the old code, view-ends is red: the capsule's ::after room made the
  page taller ("the page grew under the capsule"). That room had also
  turned add-button, library-discover-jump and account-eye red in the
  whole suite, which is why the capsule steps aside instead.
- Without the step-aside at the foot, view-ends is red.
- Without the import hook in app.js, every case is red.
- Without scrollOnPurpose, "the page stays at its foot" is red, because
  the guard puts the scroll back.

Not tried: the real Wails app on macOS, Windows and Linux (WebKitGTK),
and the tray panel, which has no long page to show it on.
This commit is contained in:
yetone
2026-11-03 02:14:32 +08:00
parent d8a34cbcf6
commit d5dc8eeccc
8 changed files with 310 additions and 6 deletions
+1
View File
@@ -503,6 +503,7 @@ covers it in both engines, every language and a narrow window.
- Settings' Search APIs add row has a base URL field under the key for every API (#1580): the vendor's own address is its placeholder, picking an API already added fills in its saved URL so a new key alone keeps it, and Add with no key changes only the URL. See [a search API's base URL](gateway-routing.md#a-search-apis-base-url), [`renderSearch`](../../internal/gui/assets/plugins/search/settings.js) and `search-api.test.cjs`.
- Every user-visible string has zh, zh-TW, ja and de translations with the same placeholders. `gui-zh-tw.test.cjs`, `gui-ja.test.cjs` and `gui-de.test.cjs` fail on a missing one; `gui-zh-tw.test.cjs` also fails on a zh-TW string with a Simplified character left in it.
- A click never moves the page. Code scrolls a view only with the reader's event in hand (`scrollOnPurpose`); `click-scroll.test.cjs` guards this. A click is taken where the reader left the view: a scroll not theirs made just before it, whose scroll event the browser sends only at the next frame, after the click, is put back first (`backToReader` in the click guard, #1554). What was clicked is held where it was (`hold`); a view at its top when clicked stays at its top, and what comes in above the control moves it down instead (#2134, `update-auto.test.cjs`), as long as it moves less than half its own height and so stays under the pointer. When what the click does leaves the page shorter under it (a list emptied), the view keeps room at its foot for it to stay (`.view-room`), room that goes as the reader scrolls back. A control under what it unrolls (`data-unrolls`, "Show 7 more") goes down with what it opens: what's held is the part it is in, so the rows open downwards. Anything larger above it, as the stage a day picked on Routing brings in above the bar, is scrolled past, and the control stays where it was clicked (`routing-days-fit.test.cjs`, `routing-failed-open.test.cjs`).
- A page scrolled a screen down shows Scroll to top and Scroll to bottom (emo172, #1090): a small capsule of two chevron buttons at the open page's lower right, in its right margin when a wide window leaves one, else over its corner; above Providers' sticky Add buttons. It goes again near the page's top and over a dialog, and, over the corner, at the page's foot, where the last row can't scroll out from under it, unless it has the pointer or focus. It never changes the page's height, which the guard below measures. A press is the reader's scroll (`scrollOnPurpose`, then `arrived` once the page stands still), smooth unless motion is reduced; Scroll to bottom is `aria-disabled` at the foot. Each button's name and tooltip are in every language. The code is [`scrollends.js`](../../internal/gui/assets/scrollends.js), imported on the window's first scroll so the core doesn't carry it; the tray panel has none. Home and End scroll a page as before. See `view-ends.test.cjs`.
- A scroll not the reader's is put back, so every way the reader scrolls has to count as theirs: the wheel and a trackpad's coast after the lift (WebKit on the Mac plays the coast itself and the page hears its scrolls with no wheel for each, so the wheel starts the same chain a touch fling does, `flings`/`flingUntil`: each scroll keeps the next one the reader's till it rests, and a click ends it; issenn on Discord, `view-trackpad-coast.test.cjs`), a wheel or coast the page is never told of (macOS 13's WebKit, Safari 16.6's, scrolled a view under wheels it never dispatched, so every scroll was put back and only the bar's drag moved the page: three scrolls put back the same way within a second are taken as the reader's run and given back, and so is each one after it that goes on the same way within a second of the last, so a wheel turned slowly or on a loaded Mac loses no step; a scroll by code is one, not a run, and two at rest are still put back; issenn on Discord, `view-wheel-unheard.test.cjs`. Under a click's 4s hold the same holds: only a put-back that comes with the page redrawn since the hold last held (`redrawn`: the view's height or where the first held parts sit moved from `h.lay`) is the hold's and never counts toward a run, so a profile opened on the Agents page and wheeled through at once scrolls, issennknight on Discord, `view-wheel-after-click.test.cjs`. The parts `h.lay` measures are those still in the page that scroll with it: a part drawn again since (the Usage page's tabs, the agents' list under an agent opened or closed) is a redraw once, not at every scroll, and a sticky one (Settings' tabs at a narrow width) is left out, as it sits still while the page scrolls; `view-wheel-after-redraw.test.cjs`), a touch and its fling, the keys, a drag, the scrollbar's own drag (`barDrag`, #1089) and the middle button's autoscroll (`panning`, 多喝热水 on Discord). Chromium and WebView2 give the autoscroll a press of button 1 and then no event of the reader's while it scrolls; from that press the view follows it till Chromium ends it, on the next press (which reaches the page only as a pointerup), a key (a keyup), or the lift after the mouse moved while held. A field the guard brings back into view after putting a scroll back is one focused since the reader last scrolled that view, not one they scrolled away from (`scrolledFrom`): the middle press focuses the button under it. See `view-middle-autoscroll.test.cjs`.
- A load that lands puts the view back where the reader left it (`show`'s `back` on the page's first reads, the Providers pages' reload after `render`): what it drew may have pulled the view up, the browser clamping it to a page shorter for a moment. While the reader scrolls, the place last heard is late (the page hears of a scroll a frame or more after it, WebKit scrolling on its own thread), and putting it back took their last steps and stopped their coast each time a load landed under the wheel, so Routing and Usage, scrolled as they opened, shook and snapped back (issennknight on Discord, macOS 13). `backAfterLoad` keeps a view that has gone on the way the reader's own scrolls go (`readerWay`, set from each scroll of theirs) as theirs, and puts back only a move against it, which is a redraw's clamp. The browser's scroll anchoring stays on: as data comes in above, it lowers `scrollTop` with what's on the screen still, which the reader never sees, so the test tells a put-back (the view up, what was under the pointer going down with it) from that.
- Where the window's WebKit scrolls under wheels it never tells the page of (macOS 13's, 16.6), each gesture's first scrolls were put back until three the same way made a run (`puttingBack`), a shake at the start of every gesture, the first on a page just opened included. The first run given back is remembered (`deaf`, kept in localStorage as `magpie.unheardWheels` for the next start); from then on a scroll at rest waits 120ms before it is put back (`waitsBack`), and one more the same way within 80ms (a frame or a few; code's two scrolls in a row come further apart and are both put back, `view-wheel-unheard.test.cjs`), with the page's height the same (no redraw between them), makes it the reader's at once. A lone scroll (a redraw's, code's) is still put back, 120ms later; one under a click's hold is put back at once as before. See `view-open-wheel.test.cjs`, which starts the wheel before the first data, tells the page of each scroll 80ms late or never, and counts every write that moves the view up under the wheel. What the wait puts back is recorded as an at-once put-back is, so a wheel heard later than 120ms still gives it back (`givesBack`).
+9
View File
@@ -2225,6 +2225,15 @@ body.window .foot .status:not(.err):not(.warn) { pointer-events: none; }
it shorter and move it */
.status.ok, .status.err, .status.warn { font-size: 12.5px; line-height: 16px; font-weight: 500; padding: 3px 10px; border-radius: 999px; background: color-mix(in srgb, currentColor 16%, var(--bg)); box-shadow: inset 0 0 0 1px color-mix(in srgb, currentColor 30%, transparent); }
.status.lift { position: fixed; z-index: 21; font-size: 12.5px; font-weight: 500; padding: 3px 10px; border-radius: 11px; background: color-mix(in srgb, currentColor 16%, var(--card)); left: 50%; bottom: 18px; transform: translateX(-50%); max-width: calc(100vw - 32px); box-shadow: inset 0 0 0 1px color-mix(in srgb, currentColor 30%, transparent), 0 6px 20px rgba(0, 0, 0, .28); animation: fade-in .2s var(--ease); }
/* Scroll to top / Scroll to bottom (scrollends.js, #1090): a quiet capsule at
the open page's lower right, in when the page is a screen down */
.view-ends { position: fixed; z-index: 9; right: 16px; bottom: 16px; display: flex; flex-direction: column; align-items: center; padding: 2px; border-radius: 9px; background: var(--pop-bg); -webkit-backdrop-filter: blur(20px); backdrop-filter: blur(20px); box-shadow: 0 4px 14px rgba(20, 22, 30, .12), 0 0 0 .5px var(--line-2); opacity: 0; visibility: hidden; pointer-events: none; transform: translateY(4px); transition: opacity .18s var(--ease), transform .18s var(--ease), visibility 0s .18s; }
.view-ends.on, .view-ends:focus-within { opacity: 1; visibility: visible; pointer-events: auto; transform: none; transition: opacity .18s var(--ease), transform .18s var(--ease), visibility 0s; }
.view-ends button { display: flex; align-items: center; justify-content: center; width: 26px; height: 24px; border-radius: 7px; color: var(--fg-2); }
.view-ends button:hover { background: var(--pill-hover); color: var(--fg); }
.view-ends button[aria-disabled="true"] { color: var(--faint); background: none; }
.view-ends .ve-sep { width: 14px; height: 1px; margin: 1px 0; background: var(--line-2); }
@media (prefers-reduced-motion: reduce) { .view-ends, .view-ends.on { transition: none; transform: none; } }
/* a line longer than its place floats too (status), and is read whole
(littleHong): wrapped, up to ten lines, the rest scrolled to; one line
is still a pill (22px tall, 11px corners) */
+2 -3
View File
@@ -22708,14 +22708,12 @@ function savePrefs(body) {
//
// Code moves a view only in answer to a click that asks to go somewhere, and
// shows that with the reader's event: scrollOnPurpose(e). Called without one
// (from a load, a timer, a helper that other clicks share) it is refused,
// and whatever scroll follows is put back.
// it is refused, and whatever scroll follows is put back.
let purposeUntil = 0, held = null;
// guardUntil is purposeUntil when the window is the click guard's own (a
// field brought back into sight, backToReader): it lets that scroll stand,
// but it isn't the reader's, so an app menu the click opens stays open.
let guardUntil = 0;
// A new purposeful scroll supersedes any still-pending quota navigation.
const readerScrolls = (ms) => { quotaFocus = ""; purposeUntil = Math.max(purposeUntil, performance.now() + ms); held = null; guardUntil = 0; };
function scrollOnPurpose(e, ms = 1000) {
if (!e?.isTrusted || performance.now() - e.timeStamp > 1000) {
@@ -23150,6 +23148,7 @@ for (const v of document.querySelectorAll(".view")) {
puttingBack(v, from, h);
}, { passive: true });
}
addEventListener("scroll", () => import("./scrollends.js"), { capture: true, passive: true, once: true });
let settingsLoad = Promise.resolve(); // show()'s read of Settings, for openSettingsAt
async function show(v) {
+8
View File
@@ -4,6 +4,8 @@
// works. {name} slots are filled by t(str, vars).
const I18N = {
zh: {
"Scroll to top": "回到顶部",
"Scroll to bottom": "回到底部",
"Claude Code runs as": "Claude Code 运行方式",
"Interactive mode (TUI)": "交互模式(TUI)",
"Last request {ago}: interactive mode": "上次请求 {ago}:交互模式",
@@ -4427,6 +4429,8 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。",
},
"zh-TW": {
"Scroll to top": "回到頂部",
"Scroll to bottom": "回到底部",
"Claude Code runs as": "Claude Code 執行方式",
"Interactive mode (TUI)": "互動模式(TUI)",
"Last request {ago}: interactive mode": "上次請求 {ago}:互動模式",
@@ -8835,6 +8839,8 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。",
},
ja: {
"Scroll to top": "一番上へ",
"Scroll to bottom": "一番下へ",
"Claude Code runs as": "Claude Code の実行方式",
"Interactive mode (TUI)": "対話モード(TUI)",
"Last request {ago}: interactive mode": "前回のリクエスト({ago}):対話モード",
@@ -13245,6 +13251,8 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。",
},
de: {
"Scroll to top": "Nach ganz oben",
"Scroll to bottom": "Nach ganz unten",
"Claude Code runs as": "Claude Code läuft als",
"Interactive mode (TUI)": "Interaktiver Modus (TUI)",
"Last request {ago}: interactive mode": "Letzte Anfrage {ago}: interaktiver Modus",
+74
View File
@@ -0,0 +1,74 @@
// Scroll to top and Scroll to bottom (#1090, emo172): a small capsule at the
// lower right of the open page, shown once the page is scrolled a screen
// down and gone again near its top, like a long page's in Safari. app.js
// imports this on the window's first scroll, so it weighs nothing on the
// core. A press is the reader's: it goes through scrollOnPurpose, and
// arrived() keeps the page where it ended. Home and End still scroll the
// page as they always did; the buttons are for a mouse, and Tab reaches
// them too. The tray panel has none.
(() => {
if (document.body.classList.contains("panel")) return;
const box = el("div", "view-ends");
const up = el("button", "ve-up"), down = el("button", "ve-down");
up.type = down.type = "button";
up.append(svg("m4.5 9.5 3.5-3.5 3.5 3.5", 14, 1.7));
down.append(svg("m4.5 6.5 3.5 3.5 3.5-3.5", 14, 1.7));
box.append(up, el("span", "ve-sep"), down);
document.body.append(box);
let lang = null;
const open = () => [...document.querySelectorAll(".view")].find((v) => !v.hidden);
const atEnd = (v) => v.scrollTop + v.clientHeight >= v.scrollHeight - 2;
function paint() {
if (lang !== locale) {
lang = locale;
for (const [b, s] of [[up, "Scroll to top"], [down, "Scroll to bottom"]]) b.title = t(s), b.setAttribute("aria-label", t(s));
}
const v = open(), modal = document.getElementById("modal");
const held = box.contains(document.activeElement) || box.matches(":hover");
let on = !!v && (!modal || modal.hidden) && v.scrollTop > v.clientHeight;
if (!v || !on && !held) { box.classList.remove("on"); return; }
const r = v.getBoundingClientRect(), bar = v.offsetWidth - v.clientWidth, pad = parseFloat(getComputedStyle(v).paddingRight) || 0;
// in the page's right margin when a wide window leaves one; else over the
// page's corner, and out of the way at the page's foot, where its last
// row can't be scrolled out from under it. The page's own height is
// never changed for it: app.js's "where the reader is" measures it.
const gutter = pad >= box.offsetWidth + 16;
if (!gutter && v.scrollHeight - v.clientHeight - v.scrollTop < box.offsetHeight + 24) on = false;
box.classList.toggle("on", on || held);
let bottom = innerHeight - r.bottom + 16;
// above a page's own sticky foot (Providers' Add buttons)
const foot = v.querySelector(":scope > .after-list:not(.away)");
if (foot && getComputedStyle(foot).position === "sticky") bottom = Math.max(bottom, innerHeight - foot.getBoundingClientRect().top + 8);
box.style.right = Math.max(8, innerWidth - r.right + bar + (gutter ? (pad - box.offsetWidth) / 2 : 10)) + "px";
box.style.bottom = bottom + "px";
up.setAttribute("aria-disabled", v.scrollTop < 1);
down.setAttribute("aria-disabled", atEnd(v));
}
let queued = false;
const later = () => { if (!queued) { queued = true; requestAnimationFrame(() => { queued = false; paint(); }); } };
addEventListener("scroll", later, { capture: true, passive: true });
addEventListener("resize", later);
box.addEventListener("focusout", later);
box.addEventListener("pointerleave", later);
new MutationObserver(later).observe(document.body, { subtree: true, attributes: true, attributeFilter: ["hidden"] });
function go(e, top) {
const v = open();
if (!v || e.currentTarget.getAttribute("aria-disabled") === "true") return;
if (!scrollOnPurpose(e, 2500)) return;
const to = top ? 0 : v.scrollHeight - v.clientHeight;
v.scrollTo({ top: to, behavior: calm() ? "auto" : "smooth" });
// done when it has stood still a few frames (WebKit has no scrollend)
let last = -1, still = 0;
const until = performance.now() + 2400;
const settle = () => {
if (v.scrollTop === last) still++; else still = 0, last = v.scrollTop;
if (still < 3 && performance.now() < until) return requestAnimationFrame(settle);
arrived(v);
paint();
};
requestAnimationFrame(settle);
}
up.onclick = (e) => go(e, true);
down.onclick = (e) => go(e, false);
paint();
})();
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -153,8 +153,9 @@ test("compat.js is the first of the page's own scripts", async () => {
// Use is pressed, quotaall.js when a provider has two accounts,
// quitask.js when a Quit asks first, checkinnow.js when Settings' Check
// in now for one account is pressed, autobackup.js when Settings draws
// Sync; the checks above still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
// Sync, scrollends.js on the window's first scroll; the checks above
// still read them
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+212
View File
@@ -0,0 +1,212 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Scroll to top and Scroll to bottom (emo172, #1090): a quiet capsule at the
// open page's lower right (scrollends.js), shown once the page is scrolled a
// screen down and not before. Each press is the reader's own scroll: the page
// goes to its top or its foot and stays there, not put back by the "where the
// reader is" guard. Reached by the keyboard too (Tab, then Enter), its label
// and tooltip in every language, in both themes, at a narrow window and a wide
// one, with the motion on and off. It never makes the page taller (app.js
// measures it to keep the reader's place), so over the page's corner it
// steps aside at the foot once the pointer and focus leave it. Chromium and
// WebKit.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const now = new Date();
// rows enough for a page several screens tall
const AGENTS = Array.from({ length: 40 }, (_, i) => ({
id: "a" + i, name: "Agent " + i, path: "/t/a" + i + ".json", icon: "generic", wired: true,
fields: [{ key: "model", label: "model", value: "m", options: [{ value: "m", label: "M", ref: "a/m" }] }],
}));
const WORDS = {
en: ["Scroll to top", "Scroll to bottom"],
zh: ["回到顶部", "回到底部"],
"zh-TW": ["回到頂部", "回到底部"],
ja: ["一番上へ", "一番下へ"],
de: ["Nach ganz oben", "Nach ganz unten"],
};
const SHAPES = [
{ viewport: { width: 440, height: 620 }, theme: "light", motion: "reduce" },
{ viewport: { width: 1180, height: 640 }, theme: "dark", motion: "no-preference" },
// wide enough that the page keeps a margin at its right: the capsule sits in it
{ viewport: { width: 1640, height: 700 }, theme: "light", motion: "no-preference", margin: true },
];
function server(lang, theme) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"${theme}",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: AGENTS, profiles: [], settings: { lang, theme }, fx: { rate: 7.2, at: now.toISOString() } });
if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// the page at rest: the same scrollTop over a few reads
async function rested(view, p, ms = 4000) {
let last = NaN, same = 0;
const until = Date.now() + ms;
while (Date.now() < until) {
const t = await view.evaluate((v) => v.scrollTop);
if (t === last && ++same >= 3) return t;
if (t !== last) same = 0;
last = t;
await p.waitForTimeout(80);
}
return last;
}
const shown = (p) => p.evaluate(() => {
const b = document.querySelector(".view-ends");
return !!b && getComputedStyle(b).visibility === "visible" && b.classList.contains("on");
});
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a long page has Scroll to top and Scroll to bottom", { timeout: 300000 }, async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit : chromium).launch();
t.after(() => browser.close());
for (const lang of Object.keys(WORDS)) {
for (const shape of SHAPES) {
await t.test(`${lang} ${shape.viewport.width} ${shape.theme}`, async () => {
const errors = [];
const ctx = await browser.newContext({ viewport: shape.viewport, reducedMotion: shape.motion, colorScheme: shape.theme });
const p = await ctx.newPage();
p.setDefaultTimeout(8000);
p.setDefaultNavigationTimeout(60000);
p.on("pageerror", (e) => {
if (!/^ResizeObserver loop completed with undelivered notifications/.test(e.message)) errors.push(e.message);
});
await p.route("**/*", server(lang, shape.theme));
const view = p.locator("#view-agents");
await p.goto("http://magpie.test/?view=agents");
await p.locator("#view-agents .ag-lead").first().waitFor();
await p.waitForFunction(() => { const v = document.getElementById("view-agents"); return v.scrollHeight > v.clientHeight * 3; }).catch(() => {});
const h = await view.evaluate((v) => ({ over: v.scrollHeight - v.clientHeight, h: v.clientHeight, tall: v.scrollHeight }));
assert(h.over > 2 * h.h, `the page must be several screens tall: ${JSON.stringify(h)}`);
// at the top, nothing shows
assert.equal(await shown(p), false, "no capsule at the page's top");
// the reader's wheel, past a screen
const r = await view.boundingBox();
await p.mouse.move(r.x + r.width / 2, r.y + r.height / 2);
for (let i = 0; i < 12 && (await view.evaluate((v) => v.scrollTop <= v.clientHeight * 1.2)); i++) {
await p.mouse.wheel(0, 300);
await p.waitForTimeout(120);
}
await rested(view, p);
await p.waitForFunction(() => document.querySelector(".view-ends.on"));
assert.equal(await shown(p), true, "the capsule shows a screen down");
const up = p.locator(".view-ends .ve-up"), down = p.locator(".view-ends .ve-down");
// its words, as its name and its tooltip
for (const [b, w] of [[up, WORDS[lang][0]], [down, WORDS[lang][1]]]) {
assert.equal(await b.getAttribute("aria-label"), w);
assert.equal(await b.getAttribute("title"), w);
}
await p.getByRole("button", { name: WORDS[lang][1], exact: true }).waitFor();
// inside the window and over the page, quiet: no coloured left
// border, its colours the theme's
const look = await p.evaluate(() => {
const b = document.querySelector(".view-ends"), r = b.getBoundingClientRect(), v = document.getElementById("view-agents").getBoundingClientRect();
const cs = getComputedStyle(b);
const rgb = cs.backgroundColor.match(/[\d.]+/g).map(Number);
return {
inside: r.left >= 0 && r.right <= innerWidth && r.top >= 0 && r.bottom <= innerHeight && r.right <= v.right && r.bottom <= v.bottom,
wide: document.documentElement.scrollWidth > innerWidth || document.body.scrollWidth > innerWidth,
left: parseFloat(cs.borderLeftWidth),
light: (rgb[0] + rgb[1] + rgb[2]) / 3,
image: cs.backgroundImage,
};
});
assert.ok(look.inside, "the capsule sits inside the window, over the page");
assert.equal(look.wide, false, "nothing scrolls sideways");
assert.equal(look.left, 0);
assert.equal(look.image, "none", "no gradient");
if (shape.theme === "dark") assert.ok(look.light < 100, `dark in the dark theme: ${look.light}`);
else assert.ok(look.light > 200, `light in the light theme: ${look.light}`);
if (process.env.ARTIFACT_DIR) await p.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${shape.viewport.width}-view-ends.png`) });
// Scroll to bottom: to the page's foot, and it stays there
await down.click();
const max = await view.evaluate((v) => v.scrollHeight - v.clientHeight);
await p.waitForFunction((m) => Math.abs(document.getElementById("view-agents").scrollTop - m) <= 1, max);
await p.waitForTimeout(700);
assert.ok(Math.abs((await view.evaluate((v) => v.scrollTop)) - max) <= 1, "the page stays at its foot");
assert.equal(await down.getAttribute("aria-disabled"), "true", "at the foot, Scroll to bottom has nowhere to go");
// the page's height is its own: nothing is added at its foot
assert.equal(await view.evaluate((v) => v.scrollHeight), h.tall, "the page grew under the capsule");
// at the foot nothing that can be pressed is under the capsule once
// the pointer has left it: in a wide window's margin it is beside
// every row; over the page's corner it steps aside, as the last row
// can't be scrolled out from under it
await p.mouse.move(r.x + 40, r.y + 40);
await down.evaluate((b) => b.blur());
// in sight in the margin; stepped aside, and gone, over the corner
await p.waitForFunction((m) => {
const b = document.querySelector(".view-ends");
return m ? b.classList.contains("on") : getComputedStyle(b).visibility === "hidden";
}, !!shape.margin);
const clear = await p.evaluate(() => {
const box = document.querySelector(".view-ends"), b = box.getBoundingClientRect();
const under = new Set();
if (getComputedStyle(box).visibility === "visible") for (let x = b.left + 2; x < b.right; x += 6) for (let y = b.top + 2; y < b.bottom; y += 6) {
for (const e of document.elementsFromPoint(x, y)) {
if (box.contains(e)) continue;
const c = e.closest("button, a, input, label, [role], [tabindex]:not(.view)");
if (c) under.add(c.outerHTML.slice(0, 80));
}
}
const rows = [...document.querySelectorAll("#view-agents #agents > .row")];
return { rows: rows.length, under: [...under], beside: rows.every((r) => r.getBoundingClientRect().right <= b.left) };
});
assert.ok(clear.rows > 30, `the page's rows: ${clear.rows}`);
if (shape.margin) {
assert.equal(await shown(p), true, "in the margin it stays at the foot");
assert.ok(clear.beside, "in the page's margin, beside every row");
} else assert.equal(await shown(p), false, "over the corner it steps aside at the foot");
assert.deepEqual(clear.under, [], "at the foot nothing to press is under the capsule");
assert.ok(Math.abs((await view.evaluate((v) => v.scrollTop)) - max) <= 1, "the page stays at its foot");
// the keyboard: a button, so Tab reaches it; Enter takes the page to
// its top, and it stays there. A little up from the foot it is back.
await p.mouse.move(r.x + r.width / 2, r.y + r.height / 2);
await p.mouse.wheel(0, -300);
await p.waitForFunction(() => document.querySelector(".view-ends.on"));
await p.mouse.move(r.x + 40, r.y + 40);
await up.focus();
await p.keyboard.press("Enter");
await p.waitForFunction(() => document.getElementById("view-agents").scrollTop === 0);
await p.waitForTimeout(700);
assert.equal(await view.evaluate((v) => v.scrollTop), 0, "the page stays at its top");
// focus keeps it in sight; once focus leaves, at the top it goes
assert.equal(await shown(p), true, "a focused capsule stays");
await up.evaluate((b) => b.blur());
await p.waitForFunction(() => !document.querySelector(".view-ends.on"));
// code moving the page is still put back: only the reader's scrolls
// (and the capsule's presses) stand
await view.evaluate((v) => { v.scrollTop = v.clientHeight * 2; });
await p.waitForTimeout(300);
assert.equal(await view.evaluate((v) => v.scrollTop), 0, "a scroll no one asked for is put back");
assert.equal(await shown(p), false);
assert.deepEqual(errors, []);
await ctx.close();
});
}
}
});
}