Files
magpie/internal/gui/assets/quotaall.js
T
yetone 251cce2059 usage: a click on All N accounts folds that provider's accounts under it (justfreefall on X)
justfreefall on X (CODEX (2), "既然已经有汇总信息了,能不能出个按钮把下面两个折叠?"):
the All N accounts strip already sums the accounts, so its accounts can go.
The strip gets the per-account card's own chevron (quota-acct-fold, aria-expanded,
Fold/Unfold title, no new strings). A click on the strip or the chevron, or
Enter/Space on the chevron, folds that provider's account cards in the Usage
page and in the tray panel's Allowances; again unfolds. Default open. Kept per
provider in localStorage magpie.usageAllFolded beside the other view choices,
and a storage event redraws the other window. The head's "Show ..." button
stays in its room, hidden and inert, so the strip does not move under the
pointer. A menu-bar cell that asks for one folded account unfolds them first
(focusQuotaCard). quotaall.js reads the choice on first use, so loading it
touches no app.js global (usage-merge runs it in a bare vm).

Core script budget: not raised. app.js +35 bytes, met by shortening comments.

Run (mote, macOS 27, unless said):
- go test -tags nogui ./internal/gui/: ok at the rebased head (130s); Budget
  tests again after the last edit: ok. gofmt -l: clean.
- usage-all-fold.test.cjs (new): 10/10, chromium + webkit x en zh zh-TW ja de,
  window 440x520 and panel 360x760. Broken by hand: with main's assets it is
  red (no .quota-all-fold).
- usage-merge, usage-all-fold, tray-cell-click, quota-caption-contrast, old-webkit
  after the last edit: all ok except tray-cell-click 4/4, red the same at
  origin/main fcc0daa23 (#5215).
- Usage/quota files alone, base fcc0daa23 vs this: usage-fold ("several accounts",
  "17 subscriptions"), usage-agents-hide, usage-compact-counts, usage-ledger
  Requests red the same on both (32 each); usage-merge was red only here
  (kept is not defined) and is fixed above.
- i18n-keys "a plugin's words are its own": red the same on base (#5332).
- account-eye webkit "Usage card's eye" on WSL: base 9/10 red, this 5/10 (#5052, #4244).
- click-scroll webkit "a wheel the page hears of after its scroll": red on base too (WSL).
- Whole GUI suite on WSL (concurrency 8) before the usage-merge fix: ~40 reds
  outside usage (Connect, Copilot GHE, gateway keys, groups, skills, routing
  headers, plugins), the class #5475 records on main; each usage/quota/panel
  red was rerun against base above.
Not run: go test ./..., cross-OS vet (assets and one .cjs only); the real app.
2026-11-06 19:27:42 +08:00

143 lines
7.5 KiB
JavaScript

// A provider's accounts together (CryptoSarom on X: how much of a model is
// left matters more than which account it is on). app.js imports this once
// some provider has two accounts (quotaAllJS), and the Routing page once a
// group's row says what its accounts have left, so it weighs nothing on
// the core.
//
// mergeQuotas: one provider's accounts as one figure a window. Only what
// reads alike is put together: a counted window (WorkBuddy's credits) adds
// its amounts and limits, a wallet its balances, each in one unit; a window
// said only as a share is averaged, and only over accounts on one plan,
// whose windows are the same size, so the mean is the share of their
// allowance together. A share is never added to a count. An account whose
// reading failed is not 0 but unknown: it is left out and counted as that;
// so is a window an earlier reading (asOf) stands in for whose reset has
// passed. A window only the vendor's text says has nothing to add up and is
// left out. A window the account can't spend, held by another used up that
// starts again after it (heldBy: 0% of 7 days left, 100% of 5 hours), has
// nothing left to count: it adds its whole as used (#4791). Unlimited only where every account read says so, and one
// account's window alone is that account's, already below: only what two
// or more have goes together (a Plus and a Pro account have no 5 hours in
// common). The windows keep their family and pool, so familyWindows folds
// them as an account's. accounts: those with a reading; unknown: those
// without.
//
// quotaAll: the strip of them under a Usage card's or the tray panel's
// head: "All 3 accounts", each window's figure and a thin bar, and how many
// couldn't be read. Nothing when fewer than two accounts read, or nothing
// of theirs adds up. No account is named in it (Hide accounts). A click on
// it, or its chevron, folds the accounts under it away (justfreefall on X),
// remembered by provider for the window and the panel alike
// (magpie.usageAllFolded): quotaAllFolded says whether a provider's are.
function mergeQuotas(subs, now = Date.now()) {
const read = subs.filter((q) => !q.error && (q.windows?.length || q.balance));
const unknown = subs.length - read.length;
const plans = new Set(read.map((q) => q.plan || ""));
const by = new Map();
for (const q of read) {
for (const w of q.windows || []) {
if (w.text) continue;
const kind = w.unlimited ? "u" : w.limit > 0 ? "c" : w.balance != null ? "b" : w.used != null ? "p:" + (q.plan || "") : "";
if (!kind) continue;
const k = JSON.stringify([w.name, w.family || "", w.pool || "", w.unit || "", kind]);
let m = by.get(k);
if (!m) by.set(k, (m = { w, kind, plan: q.plan || "", n: 0, stale: 0, held: 0, amount: 0, limit: 0, balance: 0, used: 0, soon: null }));
if (q.asOf && w.resetsAt && Date.parse(w.resetsAt) <= now) { m.stale++; continue; }
m.n++;
const held = w.heldBy && kind !== "u" && kind !== "b";
if (held) m.held++;
if (kind === "c") { m.amount += held ? w.limit : Math.max(0, w.amount || 0); m.limit += w.limit; }
else if (kind === "b") m.balance += w.balance;
else if (kind !== "u") m.used += held ? 100 : to100(w.used);
const at = w.resetsAt && Date.parse(w.resetsAt);
if (at > now && (m.soon == null || at < m.soon)) m.soon = at;
}
}
const windows = [];
for (const m of by.values()) {
if (m.n < 2) continue; // one account's is already below
if (m.kind === "u" && m.n < read.length) continue;
const { w } = m;
const out = { name: w.name, family: w.family, pool: w.pool, unit: w.unit, accounts: m.n, unknown: m.stale, held: m.held, how: m.kind[0] };
if (m.kind === "u") out.unlimited = true;
else if (m.kind === "c") Object.assign(out, { amount: m.amount, limit: m.limit, used: (100 * m.amount) / m.limit });
else if (m.kind === "b") out.balance = m.balance;
else {
out.used = Math.round((10 * m.used) / m.n) / 10;
if (plans.size > 1) out.plan = m.plan;
}
if (m.soon) out.firstReset = new Date(m.soon).toISOString();
windows.push(out);
}
return { accounts: read.length, unknown, windows };
}
// quotaAll: the strip (above)
function quotaAll(subs, cls = "", max = Infinity) {
if (subs.length < 2) return null;
const all = mergeQuotas(subs);
if (all.accounts < 2 || !all.windows.length) return null;
const box = el("div", "quota-all" + (cls ? " " + cls : ""));
const lead = el("span", "quota-all-head", t("All {n} accounts", { n: subs.length }));
lead.title = t("These accounts' windows together: amounts of one unit are added up; a window said only as a share is the mean of the accounts on one plan, which have the same allowance. Each account is below.");
const p = subs[0].provider, open = !quotaAllFolded(p);
const fold = el("button", "quota-acct-fold quota-all-fold");
fold.type = "button";
fold.append(svg(CHEV, 11, 1.6));
fold.setAttribute("aria-expanded", String(open));
fold.title = t(open ? "Fold" : "Unfold");
box.dataset.fold = p;
box.append(lead, fold);
box.onclick = () => {
// text being selected in it is not a click on it
if (String(getSelection()).trim() && box.contains(getSelection().anchorNode)) return;
const had = document.activeElement === fold;
setQuotaAllFolded(p, open);
if (had) document.querySelector(`.quota-all[data-fold="${CSS.escape(p)}"] .quota-all-fold`)?.focus(NO_SCROLL);
if (mode !== "panel") backToReader($("#view-usage"));
};
const ws = familyWindows(all.windows);
for (const w of ws.slice(0, max)) {
const item = el("span", "quota-all-w");
const name = t(w.name) + (w.plan ? " · " + w.plan : "");
item.append(el("span", "quota-all-name", name), el("span", "quota-all-n", quotaText(w)));
if (!w.unlimited && !quotaNoShare(w)) {
const bar = el("span", "quota-all-bar" + (to100(w.used) >= 90 ? " full" : ""));
const fill = el("i");
fill.style.width = quotaFill(w) + "%";
bar.append(fill);
item.append(bar);
}
item.title = tipLines(
name + " · " + quotaText(w),
t(w.how === "p" ? "The mean of {n} accounts on one plan" : w.how === "u" ? "Unlimited on each of {n} accounts" : "Added up over {n} accounts", { n: w.accounts }),
w.unknown && t("{n} more read before it started again: left out", { n: w.unknown }),
w.held && t("{n} of them can't spend theirs before a longer window used up starts again: counted as none left", { n: w.held }),
w.firstReset && t("The first of them starts again {when}", { when: resetClock(new Date(w.firstReset)) }),
w.tiers && "\n" + tiersText(w));
box.append(item);
}
if (all.unknown) {
const u = el("span", "quota-all-unknown", t("{n} couldn't be read", { n: all.unknown }));
u.title = t("An account whose reading failed isn't counted as empty or full: it is left out of these figures");
box.append(u);
}
return box;
}
// read on first use: loading this file touches nothing of app.js's
let allFolded;
const allFolds = () => (allFolded ||= new Set(kept("usageAllFolded", [])));
globalThis.addEventListener?.("storage", (e) => { if (e.key === "magpie.usageAllFolded") { allFolded = null; renderQuotas(); } });
const quotaAllFolded = (p) => allFolds().has(p);
// setQuotaAllFolded: true when it changed
function setQuotaAllFolded(p, fold) {
if (fold === allFolds().has(p)) return false;
if (fold) allFolded.add(p); else allFolded.delete(p);
keep("usageAllFolded", [...allFolded]);
renderQuotas();
return true;
}
window.mergeQuotas = mergeQuotas;
window.quotaAllFolded = quotaAllFolded;
window.setQuotaAllFolded = setQuotaAllFolded;
window.quotaAll = quotaAll;