diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 3f25b168d..e902061a2 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8820,7 +8820,9 @@ $("#modal").addEventListener("keydown", (e) => { }); // A dialog stays centred while it fills in, until the reader's first press // or key (the owner 10-24); then it holds what was last pressed in place. -const modalHold = { off: 0, at: null, y: 0, cap: null, capSet: "", touched: false }; +const modalHold = { off: 0, at: null, y: 0, cap: null, capSet: "", touched: false, copy: null }; +// openModal giving a redraw's focus back: not a new place to hold +let modalRefocus = false; // how far down the dialog an element sits, its animation left out: one // that scales by its own top (the owner, 10-23), one that turns by its holder. function modalDepth(a, d) { @@ -8885,6 +8887,11 @@ function holdModal(later) { // what was pressed, or failing that what has the focus (a redraw swaps // the pressed element for its copy, and gives that copy the focus) let y = modalDepth(modalHold.at, d), stood = false; + // a redraw's copy openModal found (the pressed one of several alike, a + // refresh button it put back), held as one standIn finds + const copy = modalHold.copy; + modalHold.copy = null; + if (copy?.isConnected && d.contains(copy)) { const c = modalDepth(copy, d); if (c != null) { modalHold.at = copy; y = c; stood = true; } } if (y == null && !modalHold.at?.isConnected) { const s = modalStandIn(d); if (s) { modalHold.at = s; y = modalDepth(s, d); stood = y != null; } @@ -8951,9 +8958,24 @@ function holdModal(later) { // the reader's own press or key: from here the dialog holds its place m.addEventListener("pointerdown", (e) => { modalHold.touched = true; modalMark(e.target); }, true); m.addEventListener("keydown", () => { modalHold.touched = true; }, true); - m.addEventListener("focusin", (e) => modalMark(e.target), true); - // a scroll moves the marked element, not the dialog - m.addEventListener("scroll", () => modalMark(modalHold.at), true); + m.addEventListener("focusin", (e) => { if (!modalRefocus) modalMark(e.target); }, true); + // a scroll moves the marked element, not the dialog; one held low with + // its fields cut short takes the room above as they scroll + m.addEventListener("scroll", (e) => { modalClimb(e.target); modalMark(modalHold.at); }, true); +} +// A dialog held low rises as its fields scroll, its foot staying, to the room it needs. +function modalClimb(body) { + const m = $("#modal"), d = m.firstElementChild; + if (!body?.classList?.contains("ebody") || body.parentElement?.parentElement !== d) return; + if (m.hidden || !m.classList.contains("held") || !modalHold.touched || modalHold.cap != null || modalHold.off <= 0) return; + const space = m.clientHeight - parseFloat(getComputedStyle(m).paddingTop) - parseFloat(getComputedStyle(m).paddingBottom); + const need = d.offsetHeight + body.scrollHeight - body.clientHeight; + const by = Math.min(modalHold.off - Math.max(0, (space - Math.min(need, space)) / 2), body.scrollTop); + if (by < 1) return; + modalHold.off -= by; + d.style.top = modalHold.off + "px"; + d.style.maxHeight = modalHold.capSet = modalCap(); + body.scrollTop -= by; } function openModal(content, quiet) { const m = $("#modal"), d = m.firstElementChild; @@ -8973,6 +8995,10 @@ function openModal(content, quiet) { const focusID = active?.id; const focusLabel = active?.getAttribute("aria-label"); const focusIndex = active ? [...d.querySelectorAll("input, textarea, select, button")].indexOf(active) : -1; + // several alike (each account's Refresh this card): the same one of them + const labelled = (n) => [...n.querySelectorAll("[aria-label]")].filter((element) => element.getAttribute("aria-label") === focusLabel); + const focusNth = focusLabel ? labelled(d).indexOf(active) : -1; + const held = !fresh && d.contains(modalHold.at) ? modalHold.at : null; if (fresh) modalReturnFocus = document.activeElement; d.replaceChildren(content); d.setAttribute("role", "dialog"); @@ -8985,9 +9011,14 @@ function openModal(content, quiet) { if (fresh) modalBackground(true); if (fresh) markModalSaved(); const focus = focusID && content.querySelector("#" + CSS.escape(focusID)) - || focusLabel && [...content.querySelectorAll("[aria-label]")].find((element) => element.getAttribute("aria-label") === focusLabel) + || focusLabel && labelled(content)[Math.max(0, focusNth)] || focusIndex >= 0 && content.querySelectorAll("input, textarea, select, button")[focusIndex]; - (focus || content.querySelector("input:not([disabled]), textarea, select, button:not([disabled])") || d).focus(NO_SCROLL); + // the focus given back is not a press: what was pressed stays held, by + // the element a redraw put back or by the focused copy of it + modalRefocus = !fresh; + try { (focus || content.querySelector("input:not([disabled]), textarea, select, button:not([disabled])") || d).focus(NO_SCROLL); } + finally { modalRefocus = false; } + if (held) modalHold.copy = content.contains(held) ? held : held === active && focus || null; const body = content.querySelector(":scope > .ebody"); if (body) body.scrollTop = top; // a re-render keeps the place const nextNames = content.querySelector(".mnames:not([hidden])"); @@ -13626,14 +13657,9 @@ function codexNote(cls, n, s) { return box; } -// Accounts brought in from another tool's export instead of signing in -// again: the files' text (or what is pasted) goes to magpie, which checks -// each account with the vendor before keeping it, and says what became of -// each. What is read stays here only until it is sent; the box masks it. -// A sign-in waiting for its browser's address is kept behind the import -// rather than canceled: that address pasted into the import box finishes -// it there (LuvLetter, magpie in Docker, pasted it into this box instead of -// the sign-in's Callback URL field), and closing the box ends it. +// Accounts brought in from another tool's export: magpie checks each with +// the vendor and says what became of it. A sign-in waiting for its address +// is kept behind the import; that address pasted here finishes it. function startImport(agent) { const behind = signingOpen() && signing.pasteCallback ? signing.id : signing?.behind; if (signingOpen() && signing.id !== behind) api("signin/" + signing.id + "/cancel", {}).catch(() => {}); @@ -15186,16 +15212,10 @@ function scrollCloses(box, e) { if (e.target.matches?.("input, textarea")) return false; return !e.target.classList?.contains("view") || performance.now() < purposeUntil && purposeUntil !== guardUntil; } -// openProtoMenu picks one of opts, or several when value is a list: each -// ticked or unticked in turn with the menu kept open, choose given the -// ticked ones, in the menu's order, once it closes (and only if they -// changed). With live, choose runs after each tick instead; "" is none -// of them and closes it, "\x00" a note to read. -// placeMenu puts an app menu (box, already in the page) under its anchor, -// or over it when the window runs out below. One that fits neither way goes -// where there is more room, its height held to that room, and scrolls inside -// itself, so its last item can be reached in a short window (#1437). align -// "right" lines its right edge up with the anchor's; dx nudges it sideways. +// openProtoMenu picks one of opts, or several when value is a list (ticked +// in turn, menu kept open; live: choose after each tick). +// placeMenu puts an app menu under its anchor, or over it, or where there +// is more room, scrolling inside itself (#1437) function placeMenu(box, anchor, align = "left", dx = 0) { const r = anchor.getBoundingClientRect(), h = box.offsetHeight, pad = 8, top = popTop(pad); let y = r.bottom + 5; @@ -23025,15 +23045,9 @@ function hold(h) { if (Math.abs(d) >= 1) { let want = v.scrollTop + d; const max = v.scrollHeight - v.clientHeight; - // a view at its top when clicked stays at its top: what comes in above - // what was clicked moves it down rather than scrolling the view to follow - // it. Turning automatic updates off grew the Version row above the - // switch once the save answered, and the view slid 2px off its top (#2134). - // Only while what was clicked moved by less than its height, a line come - // in above it: a day picked on Routing brings its stage in above the bar - // (~138px), and the bar is held where it was clicked (#961). Half its - // height was too little once a settings row kept 12px above and below its - // words: the Version row's line grew it 12px past a 22px switch (10-22) + // a view at its top when clicked stays there: a line come in above what + // was clicked (less than its height) moves it down, not the view (#2134, + // #961, 10-22) if (h.top && want > 0 && Math.abs(d) < a[0].getBoundingClientRect().height) want = 0; // a view at its top when clicked stays there rather than be given room // to scroll down: a chip saved in the panel's Profiles came in above the @@ -23108,15 +23122,8 @@ addEventListener("click", (e) => { const at = protoMenu?.box.contains(e.target) ? protoMenu.anchor : e.target; const v = at.closest?.(".view"); if (!v || v.hidden) { held = null; return; } - // a click before a frame has held the one before it (a tab list's keys - // pressed in quick turn) holds that one first: the page it shrank is put - // back, so this one is taken where the reader left it, not at the top. - // So is a scroll the page hasn't heard of yet: the browser tells of a - // scroll at the next frame, and a scroll made just before the click and - // not the reader's (a field focused on the press, scrolled to; a scroll by - // code; a test's click scrolling what it clicks into view while the view - // slides in) would be heard of only after it, and kept as where the reader - // was (#1554). + // a click before a frame holds the one before it first, and a scroll the + // page hasn't heard of yet is put back, not kept as the reader's (#1554) if (held?.v === v) hold(held); else if (!readers && barDrag !== v) backToReader(v); const chain = []; @@ -23732,15 +23739,9 @@ function toggleSideNav() { try { localStorage.setItem("magpie.navLayout", navPick); } catch { /* this time only */ } navMorph(layoutNav); } -// the two layouts trade places as one motion (app.css .nav-morph): the old -// drawn and the new laid out, the sidebar sliding and each tab flying to -// its place in the other; a webview without view transitions, or a reader -// who asked for less motion, has the new at once. So does the Linux app: -// WebKitGTK with compositing off (webkit_linux.go turns it off under -// Wayland) crashes in a view transition, the click on the sidebar's button -// taking the window down (depravity_wings on X). Anywhere else, a transition -// still going well past its half second is cut short, so a webview that -// never ends one can't leave the window on the old layout's picture +// the layouts trade places as one motion (.nav-morph); at once without view +// transitions, for less motion, and on Linux (WebKitGTK crashes in one); +// a transition past MORPH_MAX is cut short var MORPH_MAX = 1500; function navMorph(change) { if (navCalm() || !document.startViewTransition || document.body.classList.contains("linux")) { change(); return; } diff --git a/internal/gui/tests/account-refresh-holds.test.cjs b/internal/gui/tests/account-refresh-holds.test.cjs new file mode 100644 index 000000000..525049e30 --- /dev/null +++ b/internal/gui/tests/account-refresh-holds.test.cjs @@ -0,0 +1,156 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// 墨雨藏锋 (Discord, 11-09), a plugin subscription's editor with several +// accounts: "供应商的卡片点击刷新额度的时候会把窗口往下挪一点 然后…窗口太矮了 +// 基本只能放几行账号". +// A refresh redraws the editor, and every account's refresh has the same +// label: the focus given back went to the first account's, and holding +// that one instead of the pressed one let the pressed row move as the rows +// above it grew. The pressed account's refresh stays where it was, and +// keeps the focus. And a sheet pressed while short, then grown to the +// window's foot, held low with its accounts cut to a few rows, rises into +// the room above as they are scrolled, lifted by the scroll before them. +// In every language, wide, narrow and in a phone's browser, both engines. +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_GUI_ASSETS || path.resolve(__dirname, "../assets")); +const prov = (users) => ({ + id: "monkeycode", name: "MonkeyCode", icon: "", chat: "", responses: "", anthropic: "", catalog: "", routing: "", + models: [{ id: "m", name: "", on: true }], agents: [], fallback: [], headers: {}, keyList: [], proxy: "", + account: { agent: "monkeycode", agentName: "MonkeyCode", user: users[0], plan: "pro", logins: users.map((user, i) => ({ user, plan: "pro", active: i === 0, on: true })) }, +}); +// read again, an account shows six pools, its line wrapping at any width +const windows = (pools) => ({ windows: pools + ? ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"].flatMap((pool, k) => ["5h", "7d"].map((name, j) => ({ name, pool, members: [pool + " one", pool + " two"], used: 10 + k * 5 + j * 20, limit: 100 }))) + : [{ name: "5h", used: 12, limit: 100 }, { name: "7d", used: 40, limit: 100 }] }); +const serve = (lang, web, ctl) => 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:${JSON.stringify(lang)},theme:"light",web:${web}};` }); + 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: [prov(ctl.users)], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [{ id: "monkeycode", pid: "monkeycode", name: "MonkeyCode", spec: "@magpie-community/opencode-monkeycode-auth" }] }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/login/usage") return json(Object.fromEntries(ctl.users.map((u, i) => [u, ctl.usage(i)]).filter(([, q]) => q))); + if (url.pathname === "/api/usage/quotas/refresh") { + ctl.refreshed = true; + await new Promise((resolve) => setTimeout(resolve, 250)); + return json([{ provider: "monkeycode", user: url.searchParams.get("user"), windows: [{ name: "5h", used: 64, limit: 100 }] }]); + } + 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 sizes = [[false, 1000], [false, 560], [true, 390]]; +const langs = ["en", "zh", "zh-TW", "ja", "de"]; +async function open(browser, lang, web, width, height, ctl) { + const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" }); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, web, ctl)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { hasText: "MonkeyCode" }).first().click(); + await page.locator(`.editor .acc[data-account-id="${ctl.users.at(-1)}"] .quota-refresh`).waitFor(); + await page.waitForFunction(() => !loginUsage.monkeycode?.loading); + await page.waitForTimeout(400); + return { context, page, errors }; +} +const settled = (page) => page.waitForFunction(() => !document.querySelector(".editor .quota-refresh.busy") && !loginUsage.monkeycode?.loading).then(() => page.waitForTimeout(400)); + +for (const [engine, browserType] of [["chromium", chromium], ["webkit", webkit]]) { + test(engine + ": an account's refresh stays where it was pressed, with the focus", async (t) => { + const browser = await browserType.launch(); + t.after(() => browser.close()); + for (const [web, width] of sizes) for (const lang of langs) { + const at = `${lang} ${web ? "web " : ""}${width}`; + const ctl = { users: Array.from({ length: 12 }, (_, i) => `u${i}@example.com`), refreshed: false }; + // read again, the two accounts above the pressed one take more room + ctl.usage = (i) => windows(ctl.refreshed && i < 2); + const { context, page, errors } = await open(browser, lang, web, width, 760, ctl); + await page.evaluate(() => { const b = document.querySelector(".editor .ebody"); b.scrollTop = 80; }); + await page.waitForTimeout(200); + const tall = () => page.locator('.editor .acc[data-account-id="u0@example.com"]').evaluate((r) => r.getBoundingClientRect().height); + const was = await tall(); + const button = page.locator('.editor .acc[data-account-id="u3@example.com"] .quota-refresh'); + const before = await button.evaluate((b) => b.getBoundingClientRect().top); + await page.evaluate(() => { + window.__seen = []; + const tick = () => { + const b = document.querySelector('.editor .acc[data-account-id="u3@example.com"] .quota-refresh'); + if (b) window.__seen.push([b.getBoundingClientRect().top, document.querySelector("#modal").firstElementChild.getBoundingClientRect().top]); + window.__raf = requestAnimationFrame(tick); + }; + tick(); + }); + const dialogTop = await page.evaluate(() => document.querySelector("#modal").firstElementChild.getBoundingClientRect().top); + const box = await button.boundingBox(); + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); + await page.waitForFunction(() => document.querySelector(".editor .quota-refresh.busy")); + await settled(page); + const seen = await page.evaluate(() => { cancelAnimationFrame(window.__raf); return window.__seen; }); + const grew = await tall() - was; + assert.ok(grew >= 10, `${engine} ${at}: the rows above grew (${grew}px)`); + const off = Math.max(...seen.map(([y]) => Math.abs(y - before))); + assert.ok(off <= 1, `${engine} ${at}: the pressed refresh moved ${off}px (from ${before})`); + const moved = Math.max(...seen.map(([, y]) => Math.abs(y - dialogTop))); + assert.ok(moved <= 1, `${engine} ${at}: the dialog moved ${moved}px`); + const focused = await page.evaluate(() => document.activeElement?.classList.contains("quota-refresh") ? document.activeElement.closest(".acc")?.dataset.accountId : null); + if (engine === "chromium") assert.equal(focused, "u3@example.com", `${engine} ${at}: the focus stays on the pressed refresh`); + else assert.ok(focused == null || focused === "u3@example.com", `${engine} ${at}: the focus went to ${focused}'s refresh`); + assert.deepEqual(errors, [], `${engine} ${at}: page errors`); + await context.close(); + } + }); + + test(engine + ": a sheet pressed while short rises into the room as its accounts scroll", async (t) => { + const browser = await browserType.launch(); + t.after(() => browser.close()); + for (const [web, width] of sizes) for (const lang of langs) { + const at = `${lang} ${web ? "web " : ""}${width}`; + const ctl = { users: Array.from({ length: 12 }, (_, i) => `u${i}@example.com`), refreshed: false }; + // no readings at first; read again, every account's line wraps + ctl.usage = () => ctl.refreshed ? windows(true) : null; + const { context, page, errors } = await open(browser, lang, web, width, 900, ctl); + // a window with room for the sheet and 160px more + const need = await page.evaluate(() => { const m = document.querySelector("#modal"), d = m.firstElementChild, b = d.querySelector(".ebody"), c = getComputedStyle(m); return d.offsetHeight + b.scrollHeight - b.clientHeight + parseFloat(c.paddingTop) + parseFloat(c.paddingBottom); }); + await page.setViewportSize({ width, height: Math.ceil(need) + 160 }); + await page.waitForTimeout(300); + const d = () => page.evaluate(() => { const r = document.querySelector("#modal").firstElementChild.getBoundingClientRect(); return { top: r.top, bottom: r.bottom }; }); + const short = await d(); + assert.ok(short.top > 60, `${engine} ${at}: the sheet opens short, centred (top ${short.top})`); + await page.locator('.editor .acc[data-account-id="u0@example.com"] .quota-refresh').click(); + await page.waitForFunction(() => document.querySelector(".editor .quota-refresh.busy")); + await settled(page); + const low = await d(); + const body = page.locator(".editor .ebody"); + const over = await body.evaluate((b) => b.scrollHeight - b.clientHeight); + assert.ok(over > 200, `${engine} ${at}: the accounts outgrew the sheet (${over})`); + assert.ok(Math.abs(low.top - short.top) <= 1, `${engine} ${at}: the press held the sheet (${short.top} → ${low.top})`); + // the scroll lifts the sheet with its accounts, its foot staying + const row = page.locator('.editor .acc[data-account-id="u1@example.com"]'); + const rowAt = await row.evaluate((r) => r.getBoundingClientRect().top); + await body.evaluate((b) => { b.scrollTop += 40; }); + await page.waitForTimeout(150); + const rose = await d(); + assert.ok(rose.top <= low.top - 39, `${engine} ${at}: the sheet rose as its accounts scrolled (${low.top} → ${rose.top})`); + assert.ok(Math.abs(rose.bottom - low.bottom) <= 1, `${engine} ${at}: its foot stayed (${low.bottom} → ${rose.bottom})`); + const rowNow = await row.evaluate((r) => r.getBoundingClientRect().top); + assert.ok(Math.abs(rowNow - (rowAt - 40)) <= 1, `${engine} ${at}: the accounts moved as scrolled (${rowAt} → ${rowNow})`); + assert.equal(await body.evaluate((b) => b.scrollTop), 0, `${engine} ${at}: the sheet rose before its accounts scrolled`); + // scrolled on, it takes the whole room it needs, centred no higher + await body.evaluate((b) => { b.scrollTop += 2000; }); + await page.waitForTimeout(150); + const top = await d(); + const pad = await page.evaluate(() => parseFloat(getComputedStyle(document.querySelector("#modal")).paddingTop)); + assert.ok(Math.abs(top.top - pad) <= 1, `${engine} ${at}: the sheet took the room above (top ${top.top}, padding ${pad})`); + assert.deepEqual(errors, [], `${engine} ${at}: page errors`); + await context.close(); + } + }); +}