usage: a dragged card moves alone, a slot shows where it lands, and it lands there (jen_celeus on X)

jen_celeus (macOS 27 beta 3, 0.1.3511): the first drag of a Usage card
moved the whole card area, nothing showed where it would go, and on
release it landed after a different card.

- dragScroll: an edge scrolls only once the pointer has left it. With
  the page scrolled a little, a first-row logo sits inside the 36px top
  edge, so pressing it scrolled the whole view at once. dragRows shares
  it.
- dragCards takes a layout: each frame it picks the order that puts the
  card nearest where it is held (8px hysteresis) and moves the others to
  where that order puts them. The Usage page passes usageLayout, the
  packing's own columns (usagePlace, split out of packUsage), so cards
  of different heights no longer overlap in the preview. The panel's
  pq-alist keeps the default (card k where card k is now).
- A dashed .drag-slot under the cards shows where the card will land
  (ease-out .22s move, .15s fade in, no movement under reduced motion).
- packUsage's column-count key is the sorted card keys: a reorder used
  to re-choose 3 columns or 2, so the card landed somewhere other than
  where the preview showed it.
- TestCoreScriptBudget: comments in the Usage and tray-usage code were
  shortened to stay in the core budget with no raise (within
  1,533,802 at this head).

Run at this head: internal/gui/tests/usage-drag.test.cjs (new) in
chromium and webkit, en and zh, 4 of 4, on mote; the 25 related GUI
files (usage-*, drag/grip/arrange/order/sort tests, click-scroll,
view-middle-autoscroll, i18n-keys) on Linux (wsl-run), 424 of 426:
the two reds are click-scroll's webkit "a wheel the page hears of after
its scroll" and its parent, red the same with this change's app.js and
app.css taken out (#4385, open); after rebasing on a45dd9c65,
usage-drag, usage-pack, usage-arrange and i18n-keys again, 20 of 20;
go test -run Budget ./internal/gui ok; go vet ./internal/gui for
darwin, linux (nogui) and windows ok. JS and CSS only, so no gofmt.

Broken by hand, usage-drag red each time: origin/main's app.js and
app.css (4 of 4: the page scrolled with the first drag; on webkit zh no
slot); the edge arming removed (webkit en, the page scrolled); the keys
left unsorted (4 of 4, zai landed at another place than its slot); no
usageLayout passed (webkit, antigravity and codex overlapped while
dragged).

Not tried: the real macOS app's WKWebView (Playwright's WebKit only),
the related GUI files on mote (its suite lock queue was hours deep),
and the tray panel's pq-alist drag beyond its existing tests.
This commit is contained in:
yetone
2026-11-10 13:33:13 +08:00
parent a45dd9c657
commit 0a44c1c845
3 changed files with 245 additions and 80 deletions
+10 -1
View File
@@ -4510,8 +4510,17 @@ body.panel .modal { padding: 16px 12px; }
.subscription-usage.sorting > .subscription-card { transition: transform .22s cubic-bezier(.22, 1, .36, 1); }
.subscription-usage.sorting .us-handle { cursor: grabbing; }
.subscription-usage > .subscription-card.dragging { position: relative; z-index: 2; box-shadow: 0 8px 22px rgba(20, 22, 30, .14), 0 0 0 1px var(--line); transition: none; }
/* where a dragged card lands (dragCards): a dashed slot its size, gliding
to the next place as the others make room */
.subscription-usage.sorting, .pq-alist.sorting { position: relative; }
.drag-slot {
position: absolute; left: 0; top: 0; box-sizing: border-box; pointer-events: none;
border: 1.5px dashed color-mix(in srgb, var(--accent) 55%, transparent); border-radius: 10px;
background: color-mix(in srgb, var(--accent) 7%, transparent);
transition: transform .22s cubic-bezier(.23, 1, .32, 1); animation: fade-in .15s cubic-bezier(.23, 1, .32, 1);
}
@media (prefers-reduced-motion: reduce) {
.accts.sorting > [data-account-id], #agents.sorting > .row, .subscription-usage.sorting > .subscription-card { transition: none; }
.accts.sorting > [data-account-id], #agents.sorting > .row, .subscription-usage.sorting > .subscription-card, .pq-alist.sorting > .pq-arow, .drag-slot { transition: none; }
}
/* the show while the session files are indexed: the words on the left, a
field of dots that light up as the files land on the right, a hairline
+100 -79
View File
@@ -3162,8 +3162,14 @@ function dragScroll(list) {
while (scroll && !/(auto|scroll)/.test(getComputedStyle(scroll).overflowY)) scroll = scroll.parentElement;
scroll ||= document.scrollingElement;
const bounds = scroll.getBoundingClientRect(), edge = 36;
return { scroll, scroll0: scroll.scrollTop, speedAt: (y) => y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge)
: y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0 };
// an edge scrolls once the pointer has left it
let up = false, down = false;
return { scroll, scroll0: scroll.scrollTop, speedAt: (y) => {
if (y >= bounds.top + edge) up = true;
if (y <= bounds.bottom - edge) down = true;
return up && y < bounds.top + edge ? -Math.min(1, (bounds.top + edge - y) / edge)
: down && y > bounds.bottom - edge ? Math.min(1, (y - bounds.bottom + edge) / edge) : 0;
} };
}
// dragListen: a drag's listeners (letting go saves; Escape, blur, resize cancel)
function dragListen(handle, move, finish) {
@@ -3205,9 +3211,7 @@ function dragRows(e, handle, row, list, rows, commit, start = () => {}, idle = (
to = from;
if (d > 0) { while (to < rows.length - 1 && mid >= tops[to + 1] + heights[to + 1] / 2) to++; }
else { while (to > 0 && mid <= tops[to - 1] + heights[to - 1] / 2) to--; }
// held at the top or the foot it goes there, though the first row is a
// pixel shorter than the rest (they have a border over them) and its
// middle was out of reach (#499)
// held at the top or the foot it goes there (#499)
if (d <= lo && from > 0) to = 0;
else if (d >= hi && from < rows.length - 1) to = rows.length - 1;
rows.forEach((r, i) => {
@@ -3260,18 +3264,24 @@ function dragRows(e, handle, row, list, rows, commit, start = () => {}, idle = (
return true;
}
// dragCards is dragRows for cards laid out in a grid: the card follows the
// pointer both ways, the slot nearest its middle is where it goes, and the
// cards between move a slot over to make room.
function dragCards(e, handle, card, list, cards, commit, idle = () => {}) {
// dragCards is dragRows for a grid: the card goes to the order that puts it
// nearest where it is held, and a slot shows where. layout(rects) gives each
// card's place in an order; by default card k stands where card k is now.
function dragCards(e, handle, card, list, cards, commit, idle = () => {}, layout = null) {
if (e.button !== 0 || e.isPrimary === false || cards.length < 2) return false;
const from = cards.indexOf(card);
if (from < 0) return false;
const rects = cards.map((c) => c.getBoundingClientRect());
const place = layout?.(rects) || ((order) => {
const at = [];
order.forEach((i, k) => { at[i] = { left: rects[k].left, top: rects[k].top }; });
return at;
});
const orderTo = (to) => { const o = cards.map((_, i) => i); o.splice(to, 0, ...o.splice(from, 1)); return o; };
const { scroll, scroll0, speedAt } = dragScroll(list);
let dragging = false, ended = false, to = from, x = e.clientX, y = e.clientY, frame = 0, lastTime = 0;
let dragging = false, ended = false, to = from, x = e.clientX, y = e.clientY, frame = 0, lastTime = 0, slot = null;
const x0 = x, y0 = y, t0 = performance.now(), pointer = e.pointerId;
const r0 = rects[from];
const r0 = rects[from], box = list.getBoundingClientRect();
const paint = (time) => {
frame = 0;
if (!card.isConnected) return finish(false);
@@ -3282,17 +3292,28 @@ function dragCards(e, handle, card, list, cards, commit, idle = () => {}) {
if (speed) scroll.scrollTop += speed * dt * .6;
const dx = x - x0, dy = y - y0 + scroll.scrollTop - scroll0;
card.style.transform = `translate(${dx}px, ${dy}px)`;
const cx = r0.left + r0.width / 2 + dx, cy = r0.top + r0.height / 2 + dy;
let best = Infinity;
rects.forEach((r, i) => {
const d = (cx - r.left - r.width / 2) ** 2 + (cy - r.top - r.height / 2) ** 2;
if (d < best) { best = d; to = i; }
});
// the order shown is kept until another is clearly nearer
const fx = r0.left + dx, fy = r0.top + dy, far = (at) => Math.hypot(at[from].left - fx, at[from].top - fy);
let at = place(orderTo(to)), best = far(at) - 8;
for (let i = 0; i < cards.length; i++) {
if (i === to) continue;
const a = place(orderTo(i)), d = far(a);
if (d < best) { best = d; to = i; at = a; }
}
cards.forEach((c, i) => {
if (i === from) return;
const j = i > from && i <= to ? i - 1 : i < from && i >= to ? i + 1 : i;
c.style.transform = j !== i ? `translate(${rects[j].left - rects[i].left}px, ${rects[j].top - rects[i].top}px)` : "";
const mx = at[i].left - rects[i].left, my = at[i].top - rects[i].top;
c.style.transform = Math.abs(mx) > .5 || Math.abs(my) > .5 ? `translate(${mx}px, ${my}px)` : "";
});
const fresh = !slot;
if (fresh) {
slot = el("div", "drag-slot");
slot.setAttribute("aria-hidden", "true");
slot.style.width = r0.width + "px";
slot.style.height = r0.height + "px";
}
slot.style.transform = `translate(${at[from].left - box.left - list.clientLeft}px, ${at[from].top - box.top - list.clientTop}px)`;
if (fresh) list.prepend(slot);
if (speed) frame = requestAnimationFrame(paint);
};
const move = (ev) => {
@@ -3328,6 +3349,7 @@ function dragCards(e, handle, card, list, cards, commit, idle = () => {}) {
if (handle.hasPointerCapture(pointer)) handle.releasePointerCapture(pointer);
list.classList.remove("sorting");
card.classList.remove("dragging");
slot?.remove();
cards.forEach((c) => { c.style.transform = ""; });
if (save && dragging && to !== from) commit(to);
idle();
@@ -16280,20 +16302,16 @@ function usageAcctFold(q, open) {
return b;
}
// The Usage page's cards in the order they were dragged to (settings
// usageOrder, by provider id), as the Agents page's rows are; one it doesn't
// name keeps the order magpie sends them in after them, the Providers
// page's (provider.InProviderOrder). The tray panel's Usage tab follows it
// too.
// The Usage cards in their dragged order (usageOrder); the rest after, in
// provider.InProviderOrder. The tray's Usage tab follows it too.
function byUsageOrder(list) {
const order = state.settings?.usageOrder || [];
const rank = (q) => { const i = order.indexOf(q.provider); return i < 0 ? order.length : i; };
return list.map((q, i) => [q, i]).sort(([a, i], [b, j]) => rank(a) - rank(b) || i - j).map(([q]) => q);
}
// keyCards puts a key's balance on its plan's card, a row under the
// windows, rather than a second card of one name (#1658); one that failed
// keeps its own card. balanceCard is its id, for the menu bar.
// keyCards puts a key's balance on its plan's card (#1658); a failed one
// keeps its own. balanceCard is its id, for the menu bar.
function keyCards(list) {
list = sharedBalances(list);
const plan = (q) => q.windows?.length && !q.balance && !q.error;
@@ -16311,10 +16329,8 @@ function keyCards(list) {
return gone.size ? list.filter((q) => !gone.has(q)).map((q) => merged.get(q) || q) : list;
}
// packUsage lays the Usage cards in 260px columns, the next card to the
// column that ends highest, the order still the page's (#860); each card
// as tall as what it holds, none stretched down to the tallest's end
// (jen_celeus on X: a Zen card with no windows stood as tall as Claude's).
// packUsage lays the Usage cards in 260px columns, each card to the column
// that ends highest (#860), as tall as what it holds (jen_celeus on X).
const USAGE_MIN = 260, USAGE_GAP = 7;
let usagePacked = null, usagePackFrame = 0;
function packUsage() {
@@ -16330,16 +16346,11 @@ function packUsage() {
usagePacked = null;
return;
}
const keys = cards.map((c) => c.dataset.key || "").join();
// sorted: a drag keeps the columns it was shown in
const keys = cards.map((c) => c.dataset.key || "").sort().join();
const most = Math.max(1, Math.min(cards.length, Math.floor((width + USAGE_GAP) / (USAGE_MIN + USAGE_GAP))));
const place = (n, hs) => {
const ends = Array(n).fill(0), at = [];
for (const h of hs.map(Math.ceil)) {
// the leftmost of those ending within a pixel of the highest
const low = Math.min(...ends), c = ends.findIndex((e) => e <= low + 1);
at.push([c, ends[c], h]);
ends[c] += h + USAGE_GAP;
}
const { at, ends } = usagePlace(n, hs);
const tall = Math.max(...ends) - USAGE_GAP;
// what stands empty under the columns' ends, by the columns' width
const empty = ends.reduce((s, e) => s + tall - (e - USAGE_GAP), 0) * (width - (n - 1) * USAGE_GAP) / n;
@@ -16376,12 +16387,37 @@ function packUsage() {
if (cards[i].style.minHeight) cards[i].style.minHeight = "";
});
}
// a card's height or the page's width moved: packed again on the next frame
// (in the observer's own call the change is owed to it in the same frame,
// which WebKit reports as a ResizeObserver loop). A packed card is held to
// the rows it was given, so one whose content only shrinks (a curve made
// small again) keeps its own size: what is in it is watched too (#2059,
// mengyianx: 剩余额度走势 closed left the box as tall as when open).
// usagePlace packs heights hs into n columns: [column, top, height] each
function usagePlace(n, hs) {
const ends = Array(n).fill(0), at = [];
for (const h of hs.map(Math.ceil)) {
// the leftmost of those ending within a pixel of the highest
const low = Math.min(...ends), c = ends.findIndex((e) => e <= low + 1);
at.push([c, ends[c], h]);
ends[c] += h + USAGE_GAP;
}
return { at, ends };
}
// usageLayout: dragCards' layout for the packed Usage cards
function usageLayout(rects) {
const list = $("#subscriptionUsage");
const n = usagePacked?.n;
if (!n || !list?.classList.contains("packed")) return null;
const hs = rects.map((r) => r.height), now = usagePlace(n, hs).at;
const left = [];
now.forEach(([c], i) => { left[c] ??= rects[i].left; });
if (left.length < n || left.includes(undefined)) return null;
const top0 = rects[0].top - now[0][1];
return (order) => {
const at = [];
usagePlace(n, order.map((i) => hs[i])).at.forEach(([c, top], k) => { at[order[k]] = { left: left[c], top: top0 + top }; });
return at;
};
}
// a card's height or the page's width moved: packed on the next frame (in
// the observer's call WebKit reports a ResizeObserver loop). What is in a
// card is watched too, so one that only shrinks is packed again (#2059).
const usagePack = new ResizeObserver(() => { if (!usagePackFrame) usagePackFrame = requestAnimationFrame(packUsage); });
function packUsageNow(list) {
packUsage();
@@ -16393,9 +16429,8 @@ function packUsageNow(list) {
}
}
// usageHandle is a card's logo, which is also its handle: drag it to move
// the card among the others, Alt+arrows move it from the keyboard. The grip
// that says so shows by the logo on hover (app.css).
// usageHandle: a card's logo is its handle (drag, or Alt+arrows); a grip
// shows by it on hover.
let usageArranging = false, usageRenderPending = false;
function usageHandle(sub, card) {
const b = el("button", "ag-handle us-handle");
@@ -16418,7 +16453,7 @@ function usageHandle(sub, card) {
usageArranging = dragCards(e, b, card, list, [...list.children], (to) => moveUsage(sub.provider, to), () => {
usageArranging = false;
if (usageRenderPending) { usageRenderPending = false; renderQuotas(); }
});
}, usageLayout);
};
return b;
}
@@ -16449,12 +16484,9 @@ async function moveUsage(key, to) {
}
}
// creditDays: the credits (or money, in its unit's currency) one of an
// account's windows used each day of the period, as magpie counted them
// from its readings of the vendor's meter, which tells only what the cycle
// has used so far — a bar a day, and the period's sum; a day before magpie
// first read it is not known rather than nothing. named: the window's name
// beside the head, for a card with several.
// creditDays: what a window used each day of the period, from magpie's
// readings of the meter (a day before the first is unknown, not nothing).
// named: the window's name by the head, for a card with several.
function creditDays(daily, named) {
const box = el("div", "credit-days");
const { since, days, window: pool, unit } = daily;
@@ -16684,12 +16716,10 @@ function quotaCycle(l, now) {
// (balanceFitSpan): what a window is spending now, not what its whole cycle
// averaged, and never a run long enough to have changed its mind
const quotaEtaSpan = 7 * 86400e3;
// quotaEta: where a window's own readings are taking it — the points since
// it last refilled, within the week, fitted to a line and carried to where
// they meet zero: {out} the hour that is, {lasts} whether it is after the
// reset. null where there is nothing to say: fewer than three readings, an
// hour of them, nothing left, a line that is not falling, or one already
// past zero. A shape in a 52px box cannot be read off; this can (#2079).
// quotaEta: the readings since the last refill (within a week) fitted to a
// line carried to zero: {out} that hour, {lasts} whether it is after the
// reset. null with under three readings, an hour of them, nothing left, a
// line not falling or already past zero (#2079).
function quotaEta(l, now) {
const c = l.cycle || quotaCycle(l, now);
// a cycle already over (a past one picked) has no pace left to tell
@@ -16902,12 +16932,9 @@ function balanceAmount(sub, v) {
const m = (sub.balance || "").match(/^(.*?)-?\d[\d,]*(?:\.\d+)?(.*)$/);
return m ? m[1] + n + m[2] : n;
}
// balanceCurve: a key's balance over time, as magpie read it, under its
// figure on the Usage page (TJHHHH on Discord): the line, the least-squares
// line through it since the last top-up dashed on to where it meets zero
// when that is near, and when it runs out at that pace in the head. The
// range the allowances' curves have ("2 days", or all it has: two weeks);
// none while they are off, or with one reading only.
// balanceCurve: a key's balance over time (TJHHHH on Discord), its fit
// since the last top-up dashed on to zero when near, and when it runs out
// in the head. The allowances' range; none while off or with one reading.
function balanceCurve(sub) {
if (quotaRange === "off") return null;
const tr = sub.balanceTrend;
@@ -17242,12 +17269,9 @@ if (mode === "panel") {
setPanelTab(panelTab);
}
// The panel's Usage tab: what the requests of a period add up to — four
// totals, a small chart of them by the hour or day, and who they were of —
// as the window's Requests draws it, from the same answer (a page of one row
// is all the panel asks for). A provider picked lists only its requests, and
// the chart then tells its models apart. A click on someone in the ranking
// picks them; "Open Usage" takes the window to their requests.
// The panel's Usage tab: a period's totals, chart and ranking, from the
// window's Requests answer. A provider picked shows its models apart; a
// click in the ranking picks; "Open Usage" opens the window at them.
let panelUse = null; // the answer for the period, and provider, shown
// the window's Usage periods, All among them (#860)
const PANEL_USE_PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]];
@@ -17259,12 +17283,9 @@ try {
} catch {}
let panelUseAt = 0;
// One read at a time: a 10 s timer must not start a second behind a slow one,
// and a read asked for while one is (a period or a provider picked, the tab
// shown) is kept and served when it is done, so a pick is never dropped.
// quiet: the timer or the panel opened again asked, not the reader: what is
// shown isn't dimmed meanwhile, and is drawn again only when it changed, so
// the chart doesn't blink every 10 s or at each focus.
// One read at a time; one asked for meanwhile is served after, so a pick is
// never dropped. quiet (the timer or a reopen asked): nothing dims, and it
// is drawn again only when it changed, so the chart doesn't blink.
let panelUseFlight = null, panelUseQueued = false, panelUseQueuedLoud = false;
function loadPanelUse(quiet = false) {
if (mode !== "panel") return Promise.resolve();
+135
View File
@@ -0,0 +1,135 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Dragging a Usage card among cards of different heights (jen_celeus on X:
// "第一次拖拽会出现整个卡片界面都跟着拖动…拖到某个下面后没有明确的反馈,松手后
// 结果是插到别的卡片后"). With the page scrolled down, a press on a first-row
// card sat in the scroll edge and the first drag scrolled the whole page;
// the others were moved to slots of other cards' sizes, overlapping, with
// nothing saying where the card would go; and the drop packed the cards
// anew, into another column count, so it landed elsewhere. Now only the
// card moves, a dashed slot shows where it lands, the others stand where
// the packing puts them in that order, and letting go leaves every card
// where it was shown. Chromium and WebKit, English and Chinese; 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 iso = (ms) => new Date(ms).toISOString();
function fixtures(now) {
const w = (name, used, h) => ({ name, used, resetsAt: iso(now + h * H) });
const ag = (name, family, used, h) => ({ name, family, used, resetsAt: iso(now + h * H) });
return [
{ provider: "claude", name: "Claude Code", icon: "claude-color", user: "me@example.com", plan: "Max 5x", windows: [w("5 hours", 23, 3), w("7 days", 41, 90)] },
{ provider: "opencode-zen-free", name: "OpenCode Zen", icon: "opencode", plan: "OpenCode Zen Free", windows: [] },
{ provider: "codex", name: "Codex", icon: "codex-color", user: "me@example.com", plan: "Plus", windows: [w("5 hours", 8, 2)] },
{ provider: "antigravity", name: "Antigravity", icon: "antigravity-color", user: "ag@example.com", plan: "Google AI Pro", windows: [
ag("Gemini 3.1 Pro (High)", "Gemini", 100, 13), ag("Gemini 3 Flash", "Gemini", 20, 13), ag("Claude Sonnet 4.6", "Claude", 0, 5),
ag("GPT-OSS 120B (Medium)", "GPT-OSS", 0, 5), ag("Gemini 2.5 Flash Image", "Image", 40, 5), ag("Tab completion", "Tab", 0, 5)] },
{ provider: "kimi", name: "Kimi", icon: "kimi", windows: [w("Weekly", 55, 90)] },
{ provider: "zai", name: "Z.ai", icon: "zai", windows: [w("5 hours", 5, 2), w("7 days", 15, 50), w("MCP", 2, 50)] },
];
}
function serve(lang, settings, saved, quotas) {
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 });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/usage/arrange") {
const { order } = route.request().postDataJSON();
saved.push(order);
settings.usageOrder = order;
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.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: "" }); }
};
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a Usage card dragged among cards of other heights lands where its slot showed`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const settings = { theme: "light", lang, tray: "panel", currency: "usd" };
const saved = [], errors = [];
const page = await (await browser.newContext({ viewport: { width: 1100, height: 480 } })).newPage();
page.setDefaultTimeout(5000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, settings, saved, fixtures(Date.now())));
await page.goto("http://magpie.test/?view=usage");
const handle = (key) => page.locator(`#subscriptionUsage > [data-key="${key}"] .us-handle`);
await handle("zai").waitFor();
await page.waitForTimeout(500);
// the page scrolled down until the first row's logos sit under the
// scroll edge, 6px below the view's top
const dy = await page.evaluate(() => {
const v = document.querySelector("#subscriptionUsage").closest(".view");
return document.querySelector("#subscriptionUsage > .subscription-card").getBoundingClientRect().top - v.getBoundingClientRect().top - 6;
});
await page.mouse.move(600, 400);
await page.mouse.wheel(0, Math.round(dy));
await page.waitForTimeout(400);
const scrollTop = () => page.evaluate(() => document.querySelector("#subscriptionUsage").closest(".view").scrollTop);
const top0 = await scrollTop();
assert.ok(top0 > 0, "the page scrolls");
const view = await page.evaluate(() => document.querySelector("#subscriptionUsage").closest(".view").getBoundingClientRect().top);
const box = async (sel) => page.locator(sel).evaluate((e) => { const r = e.getBoundingClientRect(); return [r.x, r.y, r.width, r.height].map(Math.round); });
const shown = () => page.evaluate(() => Object.fromEntries([...document.querySelectorAll("#subscriptionUsage > .subscription-card")]
.map((c) => { const r = c.getBoundingClientRect(); return [c.dataset.key, [r.x, r.y, r.width, r.height].map(Math.round)]; })));
const overlap = (a, b) => a[0] < b[0] + b[2] - 1 && b[0] < a[0] + a[2] - 1 && a[1] < b[1] + b[3] - 1 && b[1] < a[1] + a[3] - 1;
const near = (a, b, msg) => a.forEach((v, i) => assert.ok(Math.abs(v - b[i]) <= 2, `${msg}: ${a} vs ${b}`));
const drag = async (key, target, check) => {
const h = await handle(key).boundingBox(), to = await box(`#subscriptionUsage > [data-key="${target}"]`);
await page.mouse.move(h.x + h.width / 2, h.y + h.height / 2);
await page.mouse.down();
const ex = to[0] + to[2] / 2, ey = to[1] + 20;
for (let i = 1; i <= 12; i++) await page.mouse.move(h.x + (ex - h.x) * i / 12, h.y + (ey - h.y) * i / 12);
await page.waitForTimeout(400);
await check?.();
assert.equal(await page.locator("#subscriptionUsage > .drag-slot").count(), 1, "a slot shows where the card lands");
const slot = await box("#subscriptionUsage > .drag-slot");
const before = await shown();
delete before[key];
const keys = Object.keys(before);
for (const a of keys) for (const b of keys) if (a < b) assert.ok(!overlap(before[a], before[b]), `${a} and ${b} overlap while dragged`);
for (const a of keys) assert.ok(!overlap(before[a], slot), `${a} stands over the slot`);
await page.mouse.up();
await page.waitForTimeout(400);
assert.equal(await page.locator("#subscriptionUsage > .drag-slot").count(), 0);
const after = await shown();
near(after[key], slot, `${key} lands in its slot`);
for (const a of keys) near(after[a], before[a], `${a} stays where it was shown`);
return saved.at(-1);
};
// a first-row card dragged across: only the card moves, not the page
const press = await handle("claude").boundingBox();
assert.ok(press.y + press.height / 2 < view + 36, `the press is in the scroll edge: ${press.y} ${view}`);
const order = await drag("claude", "codex", async () => {
assert.equal(await scrollTop(), top0, "the page doesn't scroll with the first drag");
});
assert.notEqual(order[0], "claude", "the order is saved");
assert.equal(await scrollTop(), top0);
// a card dragged up its column onto the first: in that order two
// columns would leave less empty, but the drop keeps the three it
// was shown in
const n = saved.length;
await drag("zai", "claude");
assert.equal(saved.length, n + 1, "the second drag moves the card too");
assert.deepEqual(errors, []);
});
}
}