diff --git a/internal/gui/assets/plugingrid.js b/internal/gui/assets/plugingrid.js new file mode 100644 index 000000000..10be6cedc --- /dev/null +++ b/internal/gui/assets/plugingrid.js @@ -0,0 +1,110 @@ +// Discover's long lists (all 369 subscriptions, a search that matches +// hundreds): only the rows near the view are drawn, as the page was slow +// with all of them. The grid keeps the whole list's height in its padding +// above and below what it shows, and the rows follow the scroll; a card +// with focus is kept. plugins.js imports this when its page is first drawn, +// so it weighs nothing on the core; a list shorter than its VMIN is drawn +// whole there. +window.pmVirtualGrids = function (page, card) { + const VMORE = 700; // px drawn past each edge of the view + const vgrids = new Set(); + let vrowH = 172, vcols = 3; // a row's height and the columns, as last measured + function grid(g, list) { + g.classList.add("pm-virtual"); + const v = { g, list, cols: 0, h: [], seen: new Set(), made: new Map() }; + vgrids.add(v); + vlayout(v); + return g; + } + function vlayout(v) { + const { g, list } = v; + // laid out: in the page, and the page shown + const on = g.isConnected && g.getClientRects().length > 0; + const cs = on ? getComputedStyle(g) : null; + const cols = on ? Math.max(1, cs.gridTemplateColumns.split(" ").filter(Boolean).length) : vcols; + const gap = (cs && parseFloat(cs.rowGap)) || 10; + const rows = Math.ceil(list.length / cols); + if (cols !== v.cols) { + v.cols = cols; + v.h = new Array(rows).fill(vrowH); + v.seen.clear(); + if (on) vcols = cols; + } + const above = (first) => { let y = 0; for (let r = 0; r < first; r++) y += v.h[r] + gap; return y; }; + const below = (last) => { let y = 0; for (let r = last + 1; r < rows; r++) y += v.h[r] + gap; return y; }; + for (let pass = 0; pass < 2; pass++) { + // the view, from the grid's top + let top = -VMORE, bottom = innerHeight + VMORE; + if (on) { + const gt = g.getBoundingClientRect().top, pr = page.getBoundingClientRect(); + top = pr.top - gt - VMORE; + bottom = pr.bottom - gt + VMORE; + } + let first = -1, last = rows - 1, y = 0; + for (let r = 0; r < rows; r++) { + if (first < 0 && y + v.h[r] >= top) first = r; + if (y > bottom) { last = r - 1; break; } + y += v.h[r] + gap; + } + if (first < 0) first = rows - 1; + last = Math.max(first, last); + const nodes = []; + for (let i = first * cols; i < Math.min(list.length, (last + 1) * cols); i++) { + let c = v.made.get(i); + if (!c) { + c = card(list[i]); + c.dataset.i = i; + v.made.set(i, c); + } + c.classList.remove("pm-held"); + c.style.cssText = ""; + nodes.push(c); + } + // the card with focus stays in the page, where it would be, out of + // the rows drawn (keys go on from it as before) + const f = document.activeElement?.closest?.(".pm-card"); + if (on && f && f.parentNode === g && !nodes.includes(f)) { + const i = +f.dataset.i, fr = Math.floor(i / cols), col = i % cols; + const ws = cs.gridTemplateColumns.split(" ").map(parseFloat), cg = parseFloat(cs.columnGap) || gap; + let left = parseFloat(cs.paddingLeft) || 0; + for (let k = 0; k < col; k++) left += ws[k] + cg; + f.classList.add("pm-held"); + f.style.cssText = `position:absolute;top:${above(fr)}px;left:${left}px;width:${ws[col]}px;height:${v.h[fr]}px`; + nodes.push(f); + } + replaceKeeping(g, nodes); + g.style.paddingTop = above(first) + "px"; + g.style.paddingBottom = below(last) + "px"; + if (!on) return; + // the rows as drawn: a row is as tall as its tallest card + let moved = false; + for (let r = first; r <= last; r++) { + const c = nodes[(r - first) * cols]; + const h = c && !c.classList.contains("pm-held") ? c.offsetHeight : 0; + if (!h) continue; + if (!v.seen.size && Math.abs(vrowH - h) > 0.5) { + // the first measure: every row not drawn yet is taken to be as tall + for (let k = 0; k < rows; k++) v.h[k] = h; + vrowH = h; + moved = true; + } + v.seen.add(r); + if (Math.abs(v.h[r] - h) > 0.5) { v.h[r] = h; moved = true; } + } + if (!moved) return; + g.style.paddingTop = above(first) + "px"; + g.style.paddingBottom = below(last) + "px"; + } + } + // every long grid in the page follows the scroll and the width + let vframe = 0; + function vnow() { + cancelAnimationFrame(vframe); + vframe = 0; + for (const v of vgrids) v.g.isConnected ? vlayout(v) : vgrids.delete(v); + } + const vsoon = () => { if (vgrids.size && !vframe) vframe = requestAnimationFrame(vnow); }; + page.addEventListener("scroll", vsoon, { passive: true }); + if (window.ResizeObserver) new ResizeObserver(vsoon).observe(page); + return { grid, now: vnow }; +}; diff --git a/internal/gui/assets/plugins.css b/internal/gui/assets/plugins.css index 8f816afda..0b275f7fd 100644 --- a/internal/gui/assets/plugins.css +++ b/internal/gui/assets/plugins.css @@ -92,6 +92,8 @@ .pm-sechead h3 { margin: 0; font-size: 12.5px; font-weight: 650; } .pm-sechead span { font-size: 11.5px; color: var(--muted); } .pm-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(262px, 1fr)); gap: 10px; } +/* a long list draws only the rows near the view (plugingrid.js) */ +.pm-grid.pm-virtual { position: relative; } .pm-ghnone { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 22px 12px; border-radius: 12px; border: 1px dashed var(--line); font-size: 12px; color: var(--muted); text-align: center; } /* what GitHub couldn't give, over the cards it could: a quiet line, its reason wrapping anywhere (a URL in it is one long word) */ diff --git a/internal/gui/assets/plugins.js b/internal/gui/assets/plugins.js index 5ef21dd9d..b1ff6b8ce 100644 --- a/internal/gui/assets/plugins.js +++ b/internal/gui/assets/plugins.js @@ -641,12 +641,23 @@ const h = el("div", "pm-sechead"); h.append(el("h3", "", title)); if (hint) h.append(el("span", "", hint)); - const g = el("div", "pm-grid"); - for (const l of list) g.append(card(l)); - box.append(h, g); + box.append(h, cardGrid(list)); return box; } + // a long list draws only the rows near the view (plugingrid.js); until + // that has come, and for a short list, every card is drawn + const VMIN = 48; + let vg = null; + const vload = () => vload.p = vload.p || import("./plugingrid.js").then(() => { vg = pmVirtualGrids(page, card); if (body?.querySelector(".pm-grid:not(.pm-virtual) > .pm-card:nth-child(" + VMIN + ")")) drawBody(); }, () => {}); + function cardGrid(list) { + const g = el("div", "pm-grid"); + if (list.length >= VMIN && vg) return vg.grid(g, list); + for (const l of list) g.append(card(l)); + return g; + } + const vnow = () => vg?.now(); + // Discover is one market (#owner, 11-09): every plugin, whoever wrote // it (magpie's community, another author on npm, a repository its // author tagged on GitHub), is the same card, its source said under its @@ -866,9 +877,7 @@ more.onclick = () => { kindPick = k; drawBody(); page.scrollTo({ top: 0 }); }; h.append(el("span", "grow"), more); } - const g = el("div", "pm-grid"); - for (const l of list.slice(0, limit)) g.append(card(l)); - box.append(h, g); + box.append(h, cardGrid(list.slice(0, limit))); return box; } function market(all) { @@ -997,12 +1006,14 @@ let body = null; function draw() { + vload(); const scroll = page.scrollTop; // the body is made once, so the GitHub section's field stays in the page body = body || el("div", "lib-body pm-body"); replaceKeeping(page, [head(), body]); drawBody(); page.scrollTop = scroll; + vnow(); } function drawBody() { @@ -1037,6 +1048,7 @@ import("./registry.js").then(() => pmRegistry(regBox, mine, askNPM), statusTErr); } replaceKeeping(body, out); + vnow(); if (agentsFor && body.querySelector(".pm-agents")) { // after the view is put back where the reader was, as showing it // does; the section then is the one drawn last (npm's answers draw @@ -1065,12 +1077,11 @@ else { const list = hits.list.filter((x) => !known.has(x.package)); if (!list.length) box.append(el("p", "pm-note", ls.length ? t("Nothing else on npm") : t("No plugin called “{q}”", { q: query.trim() }))); - const g = el("div", "pm-grid"); - for (const x of list) g.append(card({ package: x.package, name: x.package, npm: x })); - box.append(g); + box.append(cardGrid(list.map((x) => ({ package: x.package, name: x.package, npm: x })))); } out.push(box); replaceKeeping(body, out); + vnow(); } // what a plugin is to the reader, and how one is written, under the list diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 254a176e6..e5c048bdc 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -177,9 +177,10 @@ test("compat.js is the first of the page's own scripts", async () => { // codexprojects.js when the open Codex app shows fewer projects; // pipecheck.js when Settings draws Models; // addfloat.js when the Providers page's add sheet first opens; + // plugingrid.js when Plugins first draws; // 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", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + 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", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/gui/tests/plugin-discover-virtual.test.cjs b/internal/gui/tests/plugin-discover-virtual.test.cjs new file mode 100644 index 000000000..895c10b25 --- /dev/null +++ b/internal/gui/tests/plugin-discover-virtual.test.cjs @@ -0,0 +1,156 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Discover with a market of 500 plugins stays light: a kind picked (369 +// subscriptions) or a search that matches hundreds draws only the cards +// near the view, while the list keeps its whole height. Scrolled to the +// bottom the last card is there and its Install works; a card with focus +// stays in the page while the reader scrolls away; a narrow search still +// lists every match. Every language, both engines, wide and narrow; the API +// is faked. PERF=1 prints how long a kind takes to draw. +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(process.env.MAGPIE_ASSETS || path.join(__dirname, "../assets")); + +// 370 subscriptions and the rest, the most downloaded first: pv-0 … pv-369 +const KINDS = [["pv", 370, null], ["mw", 50, "middleware"], ["ag", 48, "agent"], ["tl", 8, "tools"], ["pg", 27, "page"]]; +const listings = []; +for (const [k, n, kind] of KINDS) for (let i = 0; i < n; i++) { + const l = { package: `@x/${k}-${i}`, name: `${k}-${i}`, community: i % 3 === 0, summary: { en: `Plugin ${k} number ${i}, a summary long enough to take two lines of a card at its narrowest width` }, npm: { version: "0.1." + i, weekly: 100000 - i } }; + if (kind) l.kind = kind; else l.providers = [`${k}${i}`]; + listings.push(l); +} +const npm = Object.fromEntries(listings.map((l) => [l.package, l.npm])); +const state = { bun: true, bunVersion: "1.3.0", plugins: [] }; +const added = []; + +function server(lang) { + 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:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/plugins") return json(state); + if (url.pathname === "/api/plugins/listings") return json({ listings }); + if (url.pathname === "/api/plugins/github") return json({ listings: [] }); + if (url.pathname === "/api/plugins/npm") return json({ npm }); + if (url.pathname === "/api/plugins/search") return json({ hits: [] }); + if (url.pathname === "/api/plugins/add") { added.push(route.request().postDataJSON()?.spec); return json({}); } + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const L = { en: "Plugins", zh: "插件", "zh-TW": "外掛", ja: "プラグイン", de: "Erweiterungen" }; +// a page of cards and the rows around it, never the whole market +const MOST = 72; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": Discover draws the cards near the view, not all 500", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of (process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(L))) for (const width of [1180, 420]) { + await t.test(lang + " " + width, async () => { + const page = await (await browser.newContext({ viewport: { width, height: 820 } })).newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang)); + await page.goto("http://magpie.test/?view=plugins"); + const view = page.locator("#view-plugins"); + await view.locator(".pm-kinds .opt").nth(1).waitFor(); + // npm's numbers in, so nothing redraws under the measure + await view.locator(`.pm-card[data-pkg="@x/pv-0"] .pm-act.get`).waitFor(); + + // Subscriptions, timed from the click to the cards drawn + const ms = await page.evaluate(() => { + const t0 = performance.now(); + document.querySelectorAll("#view-plugins .pm-kinds .opt")[1].click(); + document.body.offsetHeight; + return performance.now() - t0; + }); + const sec = view.locator('.pm-sec[data-kind="pv"]'); + await sec.waitFor(); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + const cards = await sec.locator(".pm-card").count(); + const nodes = await page.evaluate(() => document.querySelectorAll("#view-plugins *").length); + if (process.env.PERF) console.log(`${engine} ${lang} ${width}: Subscriptions drawn in ${ms.toFixed(1)}ms, ${cards} cards, ${nodes} nodes`); + assert.ok(cards > 0 && cards <= MOST, `${cards} of 370 cards in the page`); + // the list keeps its whole height: 370 cards' rows + const geo = await sec.locator(".pm-grid").evaluate((g) => { + const cols = getComputedStyle(g).gridTemplateColumns.split(" ").length; + return { cols, h: g.getBoundingClientRect().height, card: g.querySelector(".pm-card").getBoundingClientRect().height }; + }); + const rows = Math.ceil(370 / geo.cols); + assert.ok(geo.h >= rows * geo.card, `the list is ${geo.h}px for ${rows} rows of ${geo.card}px`); + + // a card with focus stays while the reader scrolls away from it + const first = sec.locator('.pm-card[data-pkg="@x/pv-0"]'); + await first.focus(); + const inView = () => page.evaluate(() => { + const p = document.querySelector("#view-plugins").getBoundingClientRect(); + return [...document.querySelectorAll('#view-plugins .pm-sec[data-kind="pv"] .pm-card')] + .filter((c) => { const r = c.getBoundingClientRect(); return r.bottom > p.top && r.top < p.bottom; }).map((c) => c.dataset.pkg); + }); + // wheeled as a reader does (the app puts back a scroll that isn't + // the reader's), each step landed before the next; at every stop + // the view has cards in it, never an empty stretch + const box = await view.boundingBox(); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + const scrollTo = async (f) => { + for (let i = 0; i < 200; i++) { + const [top, max] = await view.evaluate((v) => [v.scrollTop, v.scrollHeight - v.clientHeight]); + const want = Math.round(max * f); + if (Math.abs(want - top) < 2 || (f === 1 && top >= max - 1)) break; + await page.mouse.wheel(0, Math.max(-2500, Math.min(2500, want - top))); + for (let k = 0; k < 50 && (await view.evaluate((v) => v.scrollTop)) === top; k++) await page.waitForTimeout(20); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + assert.ok((await inView()).length > 0, "an empty stretch at " + (await view.evaluate((v) => v.scrollTop)) + "px"); + } + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + }; + await scrollTo(0.5); + const mid = await inView(); + assert.ok(mid.length > 0, "cards in the view halfway down"); + assert.ok(await page.evaluate(() => document.activeElement?.dataset?.pkg === "@x/pv-0" && document.activeElement.isConnected), "the focused card is kept"); + assert.ok((await sec.locator(".pm-card").count()) <= MOST + 1); + + // the bottom: the last card, and its Install works + await scrollTo(1); + const end = await inView(); + assert.ok(end.includes("@x/pv-369"), "the last card at the bottom: " + end.join(" ")); + added.length = 0; + await sec.locator('.pm-card[data-pkg="@x/pv-369"] .pm-act.get').click(); + for (let i = 0; i < 100 && !added.length; i++) await page.waitForTimeout(20); + assert.deepEqual(added, ["@x/pv-369"]); + + // a search: a few matches are all there; hundreds are drawn near the view + await scrollTo(0); + const q = view.locator(".pm-find input"); + await q.fill("pv-12"); + const hits = view.locator(".pm-sec").filter({ has: page.locator(".pm-sechead h3", { hasText: new RegExp("^" + L[lang] + "$") }) }); + await hits.locator('.pm-card[data-pkg="@x/pv-129"]').waitFor(); + assert.equal(await hits.locator(".pm-card").count(), 11); + await q.fill("pv"); + await hits.locator('.pm-card[data-pkg="@x/pv-0"]').waitFor(); + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + const many = await hits.locator(".pm-card").count(); + assert.ok(many > 0 && many <= MOST, `${many} of 370 matches in the page`); + + const over = await page.evaluate(() => document.scrollingElement.scrollWidth - document.scrollingElement.clientWidth); + assert.ok(over <= 0, "page scrolls sideways by " + over); + assert.deepEqual(errors, []); + await page.context().close(); + }); + } + }); +}