diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index 2534783cf..1a674d5c5 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -361,6 +361,23 @@ card's "Show … accounts" button keeps its room but is hidden and inert, so the strip stays where it was. A menu bar cell asking for one of the accounts unfolds them (`focusQuotaCard`). See `usage-all-fold.test.cjs`. +The Usage page's allowances are cards, or a table when the reader picks +Table in the Allowances head (`#quotaView`; zysicyj on X: a dozen-plus +accounts were hard to scan as cards). The pick is kept in localStorage +`magpie.quotaView` on this computer and nothing is written until it is +made, so the default stays cards. The table (`quotaTable` in +`quotatable.js`, which app.js imports once it is picked) has a row per +account in the cards' order, so what the cards hide or merge is hidden or +merged here too, with the subscription, the account, the four windows most +accounts have (each as its used or left share, a bar and when it resets, +from the same `quotaFill` and `quotaText` as the cards, so Used/Left turns +both) and the rest of an account's windows in a last column; a failed read +and a balance say so across the windows. A head sorts by it (most used first +for a window, A first for a name), again the other way, a third time back +to the cards' order; accounts with nothing in that column stay last. It +scrolls in its own box at a narrow width, the subscription held at the left. +See `usage-quota-table.test.cjs`. + ### The Sessions page's folders The Sessions page lists an agent's project folders as one list, newest diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index a6e4ccb18..766d94e16 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -998,14 +998,41 @@ body.panel .row.pref.flash { border-radius: 10px; } /* packed into columns (packUsage): each card as tall as itself, placed on rows a pixel high, the gap between cards in its place on them (#860) */ .subscription-usage.packed { grid-auto-rows: 1px; row-gap: 0; } +/* the allowances as a table: a row an account (quotatable.js); wider than the + page, it scrolls in its own box with the subscription held at the left */ +.subscription-usage.tabled { display: block; } +.qt-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: 10px; background: var(--card); } +.qt { width: 100%; min-width: 560px; border-collapse: separate; border-spacing: 0; font-size: 12px; } +.qt th, .qt td { padding: 8px 10px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--line); } +.qt tbody tr:last-child td { border-bottom: 0; } +.qt th { padding-block: 4px; font-size: 10.5px; font-weight: 500; color: var(--muted); white-space: nowrap; } +.qt .qt-sub { position: sticky; left: 0; z-index: 1; min-width: 118px; background: var(--card); } +.qt .qt-w { min-width: 84px; width: 15%; } +.qt-sort { display: inline-flex; align-items: center; gap: 3px; padding: 2px 0; font: inherit; color: inherit; background: none; border: 0; cursor: pointer; } +.qt-sort.on { color: var(--fg); } +.qt-arrow { display: inline-block; min-width: 1ch; } +@media (hover: hover) and (pointer: fine) { .qt-sort:hover { color: var(--fg); } } +.qt-id { display: flex; align-items: center; gap: 6px; } +.qt-id .ic { width: 15px; height: 15px; flex: none; } +.qt-id b { font-weight: 600; white-space: nowrap; } +.qt .plan { display: block; margin: 2px 0 0 21px; font-size: 10.5px; color: var(--muted); text-transform: capitalize; white-space: nowrap; } +.qt .qt-acct { min-width: 120px; max-width: 220px; color: var(--fg-2); } +.qt .subscription-account { margin: 0; font-size: 12px; } +.qt .qt-acct .quota-of, .qt .qt-acct .quota-seat { color: var(--muted); } +.qt-win { display: grid; gap: 4px; } +.qt-win + .qt-win { margin-top: 8px; } +.qt-fig { font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; } +.qt-name { font-weight: 400; color: var(--muted); } +.qt-reset { font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; } +.qt .qt-msg { color: var(--muted); } .subscription-card { padding: 10px 12px 11px; border: 1px solid var(--line); border-radius: 10px; background: var(--card); min-width: 0; } /* a card's captions (resets, the period, a curve's dates) read at 4.5:1 or better on the card, below its figures (Jiabubu on Discord): light's --muted is 3.7:1 on white, so a card takes the controls' quiet text; dark's --muted is 4.6:1 already */ -.subscription-card, .pq-card, .quota-all { --muted: var(--ctl-fg); } -@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card) { --muted: inherit; } } -:root[data-theme="dark"] :is(.subscription-card, .pq-card) { --muted: inherit; } +.subscription-card, .pq-card, .quota-all, .qt-wrap { --muted: var(--ctl-fg); } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; } } +:root[data-theme="dark"] :is(.subscription-card, .pq-card, .qt-wrap) { --muted: inherit; } .subscription-head { display: flex; align-items: center; gap: 7px; margin-bottom: 9px; } .subscription-head:last-child { margin-bottom: 0; } .subscription-head .ic { width: 17px; height: 17px; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 433177595..454652099 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -14604,6 +14604,10 @@ function quotaAllJS() { return (quotaAllJS.p ||= import("./quotaall.js").then(() => renderQuotas(), () => {})); } const quotaAllOf = (...a) => window.quotaAll ? quotaAll(...a) : void quotaAllJS(); +// quotatable.js: the allowances as a table, loaded once chosen. Cards or +// table is the reader's own pick on this computer, cards until then. +let quotaView = kept("quotaView", "cards"); +const quotaTableJS = () => (quotaTableJS.p ||= import("./quotatable.js").then(() => renderQuotas(), () => {})); // tiersText: a family's windows, one a line, for its tooltip. function tiersText(w) { return (w.tiers || []).map((x) => t(x.name) + " " + quotaText(x) @@ -15983,6 +15987,16 @@ function renderQuotas(lazy) { } slide(pick, "quotaMode"); } + const views = $("#quotaView"); + views.hidden = !quotas?.length; + if (!views.hidden) { + views.replaceChildren(...[["cards", "Cards"], ["table", "Table"]].map(([v, name]) => { + const b = el("button", "opt" + (v === quotaView ? " on" : ""), t(name)); + b.onclick = () => { if (v !== quotaView) { quotaView = v; keep("quotaView", v); renderQuotas(); } }; + return b; + })); + slide(views, "quotaView"); + } renderQuotaTrend(); renderQuotaHid(); if (!quotas) { @@ -16000,6 +16014,19 @@ function renderQuotas(lazy) { // less the ones hidden from it (overviewCards, the Usage page's) const shown = overviewCards(quotas); subscriptions.hidden = !shown.length; + // the table: a row an account, in the cards' order + const rows = quotaView === "table" && shown.length && (window.quotaTable ? quotaTable(byUsageOrder(keyCards(shown))) : void quotaTableJS()); + subscriptions.classList.toggle("tabled", !!rows); + if (rows) { + usagePack.disconnect(); + usagePacked = null; + subscriptions.classList.remove("packed"); + subscriptions.style.gridTemplateColumns = ""; + subscriptions.append(rows); + restoreFlash(); + restoreRefresh(); + return; + } // an agent with several accounts is one card, a section per account const groups = []; keepIcons(...was); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7383b5d5b..795d5cbf3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4,6 +4,8 @@ // works. {name} slots are filled by t(str, vars). const I18N = { zh: { + "Cards": "卡片", + "Table": "表格", "Quick check": "快速检测", "Test all": "全部测试", "One real call each, at the provider's price": "每项真实调用一次,按服务商的价格计费", @@ -5122,6 +5124,8 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。", }, "zh-TW": { + "Cards": "卡片", + "Table": "表格", "Quick check": "快速檢測", "Test all": "全部測試", "One real call each, at the provider's price": "每項真實呼叫一次,按服務商的價格計費", @@ -10225,6 +10229,8 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。", }, ja: { + "Cards": "カード", + "Table": "表", "Quick check": "クイックチェック", "Test all": "すべてテスト", "One real call each, at the provider's price": "それぞれ実際に 1 回呼び出し、プロバイダの料金がかかります", @@ -15330,6 +15336,8 @@ const I18N = { "This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。", }, de: { + "Cards": "Karten", + "Table": "Tabelle", "Quick check": "Schnelltest", "Test all": "Alle testen", "One real call each, at the provider's price": "Je ein echter Aufruf, zum Preis des Anbieters", diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index 410aba4ad..cf77af6a6 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -36,6 +36,7 @@ magpie.plugin("usage", (ctx) => { +
diff --git a/internal/gui/assets/quotatable.js b/internal/gui/assets/quotatable.js new file mode 100644 index 000000000..d0e207e80 --- /dev/null +++ b/internal/gui/assets/quotatable.js @@ -0,0 +1,138 @@ +// The Usage page's allowances as a table (zysicyj on X: a dozen-plus +// accounts are hard to scan as cards): a row an account, the subscription +// and the account first, then its windows' used (or left) share with the +// time they start again, the same readings the cards draw. app.js imports +// this once the table is chosen (quotaTableJS), so it weighs nothing on the +// core. +// +// The columns are the windows most accounts have ("5 hours", "7 days"); +// the rest of an account's go in the last column. A click on a head sorts +// by it, again the other way, a third time back to the cards' order. +const TABLE_WINDOWS = 4; +let sorted = null; // { key, down } + +// the figure a window sorts and bars by: the share as the page shows it +// (used, or left), -1 when it has none +const share = (w) => (!w || w.unlimited || quotaNoShare(w) ? -1 : quotaFill(w)); +const spanOf = (name) => { + const m = /^(\d+)\s*(hour|day|week)s?$/i.exec(name || ""); + return m ? m[1] * { hour: 1, day: 24, week: 168 }[m[2].toLowerCase()] : Infinity; +}; + +// a window's cell: its share and bar, and when it starts again +function windowCell(w, long) { + const box = el("div", "qt-win"); + if (!w) return box; + const top = el("div", "qt-fig"); + const text = quotaText(w); + const bar = share(w) >= 0; + top.append(el("span", "qt-n", bar ? quotaFill(w) + "%" : text)); + if (long) top.prepend(el("span", "qt-name", t(w.name)), " "); + box.append(top); + if (bar) { + const track = el("div", "quota-track"), fill = el("i"); + fill.style.width = quotaFill(w) + "%"; + track.append(fill); + box.append(track); + } + const at = w.resetsAt ? new Date(w.resetsAt) : null; + if (at) box.append(el("div", "qt-reset", at > Date.now() ? resetClock(at) : t("Reset time passed"))); + box.title = tipLines(t(w.name) + " · " + text, at && resetText(at, at.toLocaleString(intlLang())), w.tiers && tiersText(w)); + return box; +} + +function quotaTable(subs) { + const rows = subs.map((sub, order) => ({ sub, order, ws: sub.error ? [] : familyWindows(sub.windows) || [] })); + // the windows most rows have, by their span + const count = new Map(); + for (const r of rows) for (const w of new Set(r.ws.filter((x) => !x.members).map((x) => x.name))) count.set(w, (count.get(w) || 0) + 1); + const names = [...count.keys()].map((n, i) => [n, i]).sort(([a, i], [b, j]) => count.get(b) - count.get(a) || i - j).slice(0, TABLE_WINDOWS) + .sort(([a, i], [b, j]) => spanOf(a) - spanOf(b) || i - j).map(([n]) => n); + const extra = (r) => r.ws.filter((w) => !names.includes(w.name)); + const bare = (r) => r.sub.balance && !r.ws.length && !r.sub.error; // a balance and no window + const more = rows.some((r) => extra(r).length || (r.sub.balance && r.ws.length)) || (!names.length && rows.some(bare)); + const value = (r, key) => key === "sub" ? quotaName(r.sub).toLowerCase() + : key === "acct" ? (r.sub.alias || r.sub.user || "").toLowerCase() || null + : Math.max(-1, ...r.ws.filter((w) => w.name === key).map(share)); + if (sorted && sorted.key !== "sub" && sorted.key !== "acct" && !names.includes(sorted.key)) sorted = null; + const list = sorted ? [...rows].sort((a, b) => { + const x = value(a, sorted.key), y = value(b, sorted.key); + // a row with nothing here stays below the rest either way + const none = (v) => v === null || v < 0; + if (none(x) !== none(y)) return none(x) ? 1 : -1; + return (x < y ? -1 : x > y ? 1 : 0) * (sorted.down ? -1 : 1) || a.order - b.order; + }) : rows; + + const wrap = el("div", "qt-wrap"); + const table = el("table", "qt"); + const head = el("tr"); + const th = (key, label, cls = "") => { + const c = el("th", cls); + const on = sorted?.key === key; + c.scope = "col"; + c.setAttribute("aria-sort", on ? (sorted.down ? "descending" : "ascending") : "none"); + const b = el("button", "qt-sort" + (on ? " on" : ""), label); + b.type = "button"; + const arrow = el("span", "qt-arrow", on ? (sorted.down ? "↓" : "↑") : ""); + arrow.setAttribute("aria-hidden", "true"); + b.append(arrow); + b.onclick = () => { + // windows start at the most used, names at A + const first = key !== "sub" && key !== "acct"; + sorted = !on ? { key, down: first } : sorted.down === first ? { key, down: !first } : null; + renderQuotas(); + }; + c.append(b); + return c; + }; + head.append(th("sub", t("Subscription"), "qt-sub"), th("acct", t("Account"), "qt-acct")); + for (const n of names) head.append(th(n, t(n), "qt-w")); + if (more) head.append(el("th", "qt-w", t("Other"))); + table.append(el("thead", "", head)); + + const body = el("tbody"); + for (const { sub, ws } of list) { + const tr = el("tr"); + tr.dataset.card = trayCardID(sub); + tr.dataset.provider = sub.provider; + const s = el("td", "qt-sub"); + const who = el("div", "qt-id"); + who.append(icon(sub.icon), el("b", "", quotaName(sub))); + s.append(who); + if (sub.plan || sub.until) s.append(planSpan(sub)); + const a = el("td", "qt-acct"); + const name = el("div", "subscription-account"); + name.append(...quotaWho(sub)); + a.append(name); + tr.append(s, a); + const cols = names.length + (more ? 1 : 0); + if (sub.error) { + const e = el("td", "qt-msg", quotaError(sub.error, sub)); + e.colSpan = cols; + e.title = sub.error; + tr.append(e); + } else { + if (bare({ sub, ws })) { + const b = el("td", "qt-msg", t("{n} left", { n: sub.balance })); + b.colSpan = cols; + tr.append(b); + } else for (const n of names) { + const w = ws.find((x) => x.name === n); + const c = el("td", "qt-w"); + if (w) c.append(windowCell(w)); + tr.append(c); + } + if (more && !bare({ sub, ws })) { + const o = el("td", "qt-w qt-other"); + for (const w of extra({ ws })) o.append(windowCell(w, true)); + if (sub.balance) o.append(el("div", "qt-fig", t("{n} left", { n: sub.balance }))); + tr.append(o); + } + } + body.append(tr); + } + table.append(body); + wrap.append(table); + return wrap; +} +window.quotaTable = quotaTable; diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index e2ecbeb9b..99b4e26d1 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -150,7 +150,7 @@ test("compat.js is the first of the page's own scripts", async () => { // the pointer comes over the sidebar, whatsnew.js when release notes // open, claudemode.js when a Claude provider's editor opens, ctxtext.js // when a context window part is opened, resetask.js when a Codex reset's - // Use is pressed, quotaall.js when a provider has two accounts, + // Use is pressed, quotaall.js when a provider has two accounts, quotatable.js when the Usage page's table is picked, // quitask.js when a Quit asks first, proxies.js when Settings draws its saved proxies, checkinnow.js when Settings' Check // in now for one account is pressed, autobackup.js when Settings draws // Sync, scrollends.js on the window's first scroll, profilerename.js @@ -178,7 +178,7 @@ test("compat.js is the first of the page's own scripts", async () => { // pipecheck.js when Settings draws Models; // 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", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.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"].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", "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"].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/usage-quota-table.test.cjs b/internal/gui/tests/usage-quota-table.test.cjs new file mode 100644 index 000000000..1c19dde72 --- /dev/null +++ b/internal/gui/tests/usage-quota-table.test.cjs @@ -0,0 +1,153 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Usage page's allowances as a table beside the cards (zysicyj on X: "a +// dozen-plus accounts, the waterfall is hard to scan, could it be a +// table"). Cards stay the default and the table is the reader's own pick, +// remembered on this computer: a row an account, its subscription and +// account first, then its windows' share and when they start again; a click +// on a head sorts by it, again the other way, a third time back to the +// cards' order. A narrow window scrolls the table in its own box, never the +// page. Both engines, every language, wide and narrow; no backend, the API +// is faked here. +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 H = 3600e3; +const at = (h) => new Date(Date.now() + h * H).toISOString(); +const w = (name, used, h) => ({ name, used, resetsAt: at(h) }); +// as a user with a dozen-plus accounts has them: several of one agent, +// plans with other windows, a balance, a failed read +const quotas = [ + ...[["a", 20, 40], ["b", 90, 10], ["c", 55, 75], ["d", 5, 99]].map(([u, five, week]) => ( + { provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Plus", user: u + "@example.com", windows: [w("5 hours", five, 2), w("7 days", week, 90)] })), + ...[["e", 33, 12], ["f", 71, 61], ["g", 9, 3]].map(([u, five, week]) => ( + { provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Max 5x", user: u + "@example.com", windows: [w("5 hours", five, 3), w("7 days", week, 80), w("7 days Opus", 14, 80)] })), + { provider: "antigravity", name: "Antigravity", icon: "antigravity-color", plan: "Google AI Pro", user: "h@example.com", windows: [ + { name: "Gemini 3 Flash", family: "Gemini", used: 100, resetsAt: at(13) }, { name: "Claude Sonnet 4.6", family: "Claude", used: 0, resetsAt: at(5) }] }, + { provider: "kimi", name: "Kimi", icon: "kimi", user: "i@example.com", windows: [w("Weekly", 42, 70)] }, + { provider: "zai", name: "Z.ai", icon: "zai", user: "j@example.com", windows: [w("5 hours", 64, 1), w("Weekly", 12, 70)] }, + { provider: "deepseek", name: "DeepSeek", icon: "deepseek", windows: [], balance: "¥17.41" }, + { provider: "minimax", name: "MiniMax", icon: "minimax", user: "k@example.com", windows: [], error: "unauthorized" }, + { provider: "codex", name: "Codex", kind: "subscription", icon: "codex-color", plan: "Pro", user: "l@example.com", windows: [w("5 hours", 0, 5), w("7 days", 0, 160)] }, + { provider: "claude", name: "Claude Code", kind: "subscription", icon: "claude-color", plan: "Pro", user: "m@example.com", windows: [w("5 hours", 12, 4), w("7 days", 25, 100)] }, + { provider: "kimi", name: "Kimi", icon: "kimi", user: "n@example.com", windows: [w("Weekly", 77, 70)] }, +]; + +function serve(lang, left) { + const settings = { theme: "light", lang, tray: "panel", quotaLeft: left, currency: "usd" }; + 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: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: [], profiles: [], settings }); + if (url.pathname === "/api/settings") return json(settings); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/usage/quotas") return json(quotas); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + 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 CARDS = { en: "Cards", zh: "卡片", "zh-TW": "卡片", ja: "カード", de: "Karten" }; +const TABLE = { en: "Table", zh: "表格", "zh-TW": "表格", ja: "表", de: "Tabelle" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1100, 420]) { + test(`${engine} ${lang} ${width}px: the allowances as cards or a table`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, false)); + await page.goto("http://magpie.test/?view=usage"); + await page.waitForSelector("#subscriptionUsage .subscription-card"); + + // cards until the reader picks the table + assert.equal(await page.locator(".qt").count(), 0); + assert.equal(await page.locator("#quotaView .opt.on").innerText(), CARDS[lang]); + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), null, "nothing is saved until the reader picks"); + + await page.locator("#quotaView .opt", { hasText: TABLE[lang] }).click(); + await page.waitForSelector("#subscriptionUsage .qt tbody tr"); + assert.equal(await page.locator("#subscriptionUsage .subscription-card").count(), 0); + // a row an account (a card's several accounts are rows too) + const accounts = quotas.length; + assert.equal(await page.locator(".qt tbody tr").count(), accounts); + const heads = await page.$$eval(".qt thead th", (ths) => ths.map((x) => x.textContent.trim())); + assert.equal(heads.length, 2 + 4 + 1, `${heads}`); + // the cards' figures, the same readings + const row = await page.$eval('.qt tbody tr:nth-child(1)', (tr) => tr.innerText.replace(/\s+/g, " ")); + assert.match(row, /Codex/); + assert.match(row, /a@example\.com/); + assert.match(row, /20%/); + assert.match(row, /40%/); + // when each starts again + assert.ok((await page.$$eval(".qt .qt-reset", (x) => x.length)) >= accounts, "resets are shown"); + // a failed read and a balance say so across the windows + assert.equal(await page.locator('.qt tbody tr:has-text("¥17.41")').count(), 1); + assert.equal(await page.locator(".qt tbody tr .qt-msg").count(), 2); + + // the pick is remembered + assert.equal(await page.evaluate(() => localStorage.getItem("magpie.quotaView")), '"table"'); + await page.reload(); + await page.waitForSelector("#subscriptionUsage .qt tbody tr"); + assert.equal(await page.locator("#quotaView .opt.on").innerText(), TABLE[lang]); + + // sorted by a window: the most used first, again the least, then the cards' order + const first = () => page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " ")); + const fiveHours = page.locator(".qt thead th.qt-w .qt-sort").first(); + await fiveHours.click(); + assert.match(await first(), /b@example\.com/); + assert.equal(await page.locator('.qt thead th[aria-sort="descending"]').count(), 1); + await page.locator(".qt thead th.qt-w .qt-sort").first().click(); + assert.match(await first(), /l@example\.com/, "ascending: unused first"); + assert.equal(await page.locator('.qt thead th[aria-sort="ascending"]').count(), 1); + await page.locator(".qt thead th.qt-w .qt-sort").first().click(); + assert.match(await first(), /a@example\.com/, "back to the cards' order"); + assert.equal(await page.locator('.qt thead th[aria-sort]:not([aria-sort="none"])').count(), 0); + // by account, A first + await page.locator(".qt thead th.qt-acct .qt-sort").click(); + assert.match(await first(), /a@example\.com/); + + // the page itself never scrolls sideways; the table scrolls in its box + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + const box = await page.$eval(".qt-wrap", (b) => ({ w: b.clientWidth, s: b.scrollWidth, page: document.documentElement.clientWidth, right: b.getBoundingClientRect().right })); + assert.ok(box.right <= box.page + 1, "the table's box stays inside the page"); + if (width === 420) assert.ok(box.s > box.w, "a narrow table scrolls in its box"); + + // back to the cards + await page.locator("#quotaView .opt", { hasText: CARDS[lang] }).click(); + await page.waitForSelector("#subscriptionUsage .subscription-card"); + assert.equal(await page.locator(".qt").count(), 0); + assert.equal(await page.evaluate(() => document.querySelector("#subscriptionUsage").classList.contains("tabled")), false); + assert.deepEqual(errors, []); + }); + } + } + test(`${engine}: Left reads in the table too`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 800 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + await page.addInitScript(() => localStorage.setItem("magpie.quotaView", '"table"')); + await page.route("**/*", serve("en", true)); + await page.goto("http://magpie.test/?view=usage"); + await page.waitForSelector("#subscriptionUsage .qt tbody tr"); + const row = await page.$eval(".qt tbody tr:nth-child(1)", (tr) => tr.innerText.replace(/\s+/g, " ")); + assert.match(row, /80%/); + assert.match(row, /60%/); + }); +}