diff --git a/internal/gui/api.go b/internal/gui/api.go index 47b742a47..e4c552e6a 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -857,6 +857,9 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if s.Colorblind { boot["colorblind"] = true } + if s.ReduceMotion { + boot["reduceMotion"] = true + } // a browser tab keeps its own font choice (fonts.js) if !isWeb(w) { boot["uiFont"], boot["codeFont"] = s.UIFont, s.CodeFont @@ -1289,6 +1292,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { if _, sent := fields["classifyTimeout"]; !sent { in.ClassifyTimeout = cur.ClassifyTimeout } + // nor whether animations are stilled (#3813) + if _, sent := fields["reduceMotion"]; !sent { + in.ReduceMotion = cur.ReduceMotion + } in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown in.Window, in.WindowMaximised = cur.Window, cur.WindowMaximised // the window's own, as it was last resized // and what other pages keep here: which models an agent is shown, and diff --git a/internal/gui/api_settings_test.go b/internal/gui/api_settings_test.go index accb96d80..a51cd5c11 100644 --- a/internal/gui/api_settings_test.go +++ b/internal/gui/api_settings_test.go @@ -351,3 +351,47 @@ func TestSettingsRedactWordsWholeKept(t *testing.T) { } } } + +// Reduce motion (#3813) is saved by the Settings page, handed to the page +// in boot.js so it is still from the first paint, and kept by a save from +// a page from before it, which doesn't send it. +func TestSettingsReduceMotion(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + handler := Handler(nil, nil) + + getBoot := func() string { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest("GET", "/boot.js", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("GET /boot.js: %d %s", rec.Code, rec.Body) + } + return rec.Body.String() + } + if boot := getBoot(); strings.Contains(boot, `"reduceMotion"`) { + t.Fatalf("reduceMotion off by default, got boot.js: %s", boot) + } + for _, tc := range []struct { + body string + want bool + }{ + {`{"theme":"dark","reduceMotion":true}`, true}, + {`{"theme":"light"}`, true}, + {`{"theme":"dark","reduceMotion":false}`, false}, + } { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(tc.body))) + if rec.Code != http.StatusOK { + t.Fatalf("%s: %d %s", tc.body, rec.Code, rec.Body) + } + if got := settings.Load().ReduceMotion; got != tc.want { + t.Fatalf("%s: ReduceMotion = %v, want %v", tc.body, got, tc.want) + } + if boot := getBoot(); strings.Contains(boot, `"reduceMotion":true`) != tc.want { + t.Fatalf("%s: boot.js = %s, want reduceMotion=%v", tc.body, boot, tc.want) + } + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ccb5dd199..670ff3db8 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -8297,7 +8297,8 @@ const SPRING = CSS.supports?.("animation-timing-function", "linear(0, 1)") : "cubic-bezier(.2, .9, .25, 1.02)"; const IOS_EASE = "cubic-bezier(.32, .72, 0, 1)"; // a declaration, so code above it can ask too -function calm() { return matchMedia("(prefers-reduced-motion: reduce)").matches; } +// the system's Reduce Motion, or Settings' (#3813) +function calm() { return document.documentElement.dataset.motion === "reduce" || matchMedia("(prefers-reduced-motion: reduce)").matches; } // magpie's bird in parts, its wing and tail free to move (the header's logo // holds the shapes) const BIRD = ``; @@ -18981,6 +18982,7 @@ function applyPrefs(s, rate) { if (applyPrefs.ready) { tintPanel(450); tintTitleBar(460); } } } + if (!!s.reduceMotion !== (root.dataset.motion === "reduce")) window.holdStill(!!s.reduceMotion); if (!!s.colorblind !== !!root.dataset.colorblind) { if (s.colorblind) root.dataset.colorblind = "1"; else delete root.dataset.colorblind; @@ -19424,6 +19426,8 @@ function renderSettings() { $("#themeSegs").replaceChildren(segs(THEMES.map(([id, name]) => [id, t(name)]), s.theme, (theme) => savePrefs({ ...keep, theme }))); $("#colorblindSegs").title = t("Colorblind-safe chart colors, and each allowance window's line in a dash of its own"); $("#colorblindSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.colorblind ? "on" : "off", (v) => savePrefs({ ...keep, colorblind: v === "on" }))); + $("#reduceMotionSegs").title = t("Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy"); + $("#reduceMotionSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.reduceMotion ? "on" : "off", (v) => savePrefs({ ...keep, reduceMotion: v === "on" }))); renderLangPick(s, keep); renderGatewayMode(s); // a browser tab has its own zoom, and magpie leaves it to it @@ -22721,7 +22725,7 @@ function wbCheckinLine(r) { // prefsKeep is what the settings page sends of s, all of it each time. function prefsKeep(s) { - return { theme: s.theme, colorblind: !!s.colorblind, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, proxy: s.proxy || "", + return { theme: s.theme, colorblind: !!s.colorblind, reduceMotion: !!s.reduceMotion, lang: s.lang, tray: s.tray, dock: !!s.dock, dockWindow: !!s.dockWindow, lightweight: s.lightweight, keepAwake: !!s.keepAwake, keepAwakeDisplay: !!s.keepAwakeDisplay, noWSLAgents: !!s.noWSLAgents, proxy: s.proxy || "", sessionTerminal: s.sessionTerminal || "", uiFont: s.uiFont || null, codeFont: s.codeFont || null, otel: s.otel || {}, diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7fbd035af..2b45bc132 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3016,6 +3016,8 @@ const I18N = { "Unavailable app ({id})": "应用不可用({id})", "Appearance": "外观", "Colorblind mode": "色盲模式", + "Reduce motion": "减弱动态效果", + "Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy": "动画静止不动,如同系统的「减弱动态效果」,让 magpie 少占用电脑", "Colorblind-safe chart colors, and each allowance window's line in a dash of its own": "图表改用色盲友好配色,每个额度窗口的走势线使用各自的线型", "Follows the Omarchy theme, as picked in Omarchy's menu": "跟随 Omarchy 主题,在 Omarchy 菜单里切换", "Language": "语言", @@ -7032,6 +7034,8 @@ const I18N = { "Unavailable app ({id})": "應用不可用({id})", "Appearance": "外觀", "Colorblind mode": "色盲模式", + "Reduce motion": "減少動態效果", + "Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy": "動畫靜止不動,如同系統的「減少動態效果」,讓 magpie 少佔用電腦", "Colorblind-safe chart colors, and each allowance window's line in a dash of its own": "圖表改用色盲友善配色,每個額度時段的走勢線使用各自的線型", "Follows the Omarchy theme, as picked in Omarchy's menu": "跟隨 Omarchy 主題,在 Omarchy 選單裡切換", "Language": "語言", @@ -11060,6 +11064,8 @@ const I18N = { "Unavailable app ({id})": "利用できないアプリ({id})", "Appearance": "外観", "Colorblind mode": "色覚サポート", + "Reduce motion": "視差効果を減らす", + "Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy": "システムの「視差効果を減らす」と同じくアニメーションを止め、コンピュータの負荷を減らします", "Colorblind-safe chart colors, and each allowance window's line in a dash of its own": "グラフを色覚に配慮した配色にし、利用枠のウィンドウごとに推移線の線種を変えます", "Follows the Omarchy theme, as picked in Omarchy's menu": "Omarchy のメニューで選んだ Omarchy テーマに従います", "Language": "言語", @@ -15098,6 +15104,8 @@ const I18N = { "Unavailable app ({id})": "Nicht verfügbare App ({id})", "Appearance": "Darstellung", "Colorblind mode": "Farbenblind-Modus", + "Reduce motion": "Bewegung reduzieren", + "Animations stand still, as with the system's Reduce Motion, so magpie keeps the computer less busy": "Animationen stehen still wie bei „Bewegung reduzieren“ des Systems, damit magpie den Computer weniger beansprucht", "Colorblind-safe chart colors, and each allowance window's line in a dash of its own": "Farbenblind-taugliche Diagrammfarben, und jedes Zeitfenster eines Kontingents mit eigenem Strichmuster", "Follows the Omarchy theme, as picked in Omarchy's menu": "Folgt dem im Omarchy-Menü gewählten Omarchy-Theme", "Language": "Sprache", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 21961f7b3..e9256c9cf 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -172,6 +172,10 @@
Colorblind mode
+
+
Reduce motion
+
+
Language
diff --git a/internal/gui/assets/layout.js b/internal/gui/assets/layout.js index 1d9289f48..6de88575b 100644 --- a/internal/gui/assets/layout.js +++ b/internal/gui/assets/layout.js @@ -5,6 +5,7 @@ var mode = new URLSearchParams(location.search).get("mode") || "window"; var web = !!(window.bootPrefs && window.bootPrefs.web); document.body.classList.add(mode); + if (window.bootPrefs && window.bootPrefs.reduceMotion) window.holdStill(true); if (web) document.body.classList.add("web"); // Preserve the existing iOS viewport policy before app.js runs. if (web && (/iP(hone|ad|od)/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1))) { diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 9e093d135..342505535 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -755,7 +755,7 @@ magpie.plugin("library", (ctx) => { if (!mk || !window.scrollOnPurpose?.(e, 1500)) return; // its heading just under the strip, however many lines that takes const top = mk.getBoundingClientRect().top - page.getBoundingClientRect().top + page.scrollTop - head.getBoundingClientRect().height - 8; - page.scrollTo({ top, behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); + page.scrollTo({ top, behavior: calm() ? "auto" : "smooth" }); mk.querySelector("input")?.focus({ preventScroll: true }); }); go.append(glyph(GLYPH.search, "lib-mini"), el("span", "", t("Discover"))); diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 2ad3c2505..866f6ec5e 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -44,7 +44,7 @@ function routingPage(part) { const box = $("#rt"); if (!box) return; const NS = "http://www.w3.org/2000/svg"; - const still = () => matchMedia("(prefers-reduced-motion: reduce)").matches; + const still = calm; const shown = () => !$("#view-routing").hidden && !document.hidden; // steady redraws a part of the page where the reader is: WebKit has no // scroll anchoring, and a part emptied and filled again, measured between, diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 95403a196..2d89a9aad 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -435,7 +435,7 @@ button.rt-session { cursor: pointer; } .rt-livedot { width: 6px; height: 6px; margin-left: 7px; border-radius: 50%; background: var(--green); --fg: var(--green); } /* it pulses while a request is under way only (#2827) */ .rt-livedot.on { animation: rtlive 1.8s infinite; } -@media (prefers-reduced-motion: reduce) { .rt-livedot { animation: none; } } +@media (prefers-reduced-motion: reduce) { .rt-livedot.on { animation: none; } } /* routing groups, and the providers routing over several of their own */ .rt-gsec { display: grid; gap: 6px; margin-top: 16px; } .rt-gsec .row-head .note { margin-right: 6px; } diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 6dc4cf90f..9d39bba18 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2566,7 +2566,7 @@ function sessIndexHero() { bar.append(fill); hero.append(words, field, bar); - const reduced = matchMedia("(prefers-reduced-motion: reduce)").matches; + const reduced = calm(); let frac = 0, shown = 0, known = false, tipAt = Date.now(), tipI = 0, rate = 0, last = null; let done = false; hero.update = (p) => { diff --git a/internal/gui/assets/theme.js b/internal/gui/assets/theme.js index d487d96b9..217d06a08 100644 --- a/internal/gui/assets/theme.js +++ b/internal/gui/assets/theme.js @@ -9,5 +9,20 @@ var theme = asked || (saved && saved !== "system" ? saved : ""); if (theme) document.documentElement.dataset.theme = theme; if (prefs && prefs.colorblind) document.documentElement.dataset.colorblind = "1"; + if (prefs && prefs.reduceMotion) document.documentElement.dataset.motion = "reduce"; if (prefs) document.documentElement.style.setProperty("--zoom", prefs.web ? 1 : (prefs.textSize || 100) / 100); })(); + +// Settings' Reduce motion (#3813) applies the stylesheets' reduced-motion +// rules, their media set to all and back; calm() in app.js follows it +(function () { + var held = []; + window.holdStill = function (on) { + var root = document.documentElement; + if (on) root.dataset.motion = "reduce"; else delete root.dataset.motion; + held.forEach(function (h) { h[0].media.mediaText = h[1]; }); + held = []; + if (on) for (var i = 0, s = document.styleSheets; i < s.length; i++) for (var j = 0, r = s[i].cssRules; j < r.length; j++) + if (r[j].media && /reduced-motion: *reduce/.test(r[j].media.mediaText)) held.push([r[j], r[j].media.mediaText]), r[j].media.mediaText = "all"; + }; +})(); diff --git a/internal/gui/tests/reduce-motion.test.cjs b/internal/gui/tests/reduce-motion.test.cjs new file mode 100644 index 000000000..363254cbb --- /dev/null +++ b/internal/gui/tests/reduce-motion.test.cjs @@ -0,0 +1,96 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Reduce motion in Settings → General (#3813, linull24 and CupOfBread: the +// moving Routing page kept a phone and a computer busy, and only the +// system's own switch stilled it). In both engines, with the API faked: +// - saved on, the page is still from the first paint: every stylesheet's +// (prefers-reduced-motion: reduce) rule applies, and calm() says so, as +// with the system's switch; +// - turned off in Settings, the rules are the system's again, and the +// Routing page's live dot pulses; turned on, it stops, with no reload; +// - the choice is saved as reduceMotion. +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"); + +function serve(st, posted) { + const settings = () => ({ lang: "en", theme: "light", searchVendors: [], searchAPIs: [], ...st }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang: "en", theme: "light", web: false, ...(st.reduceMotion ? { reduceMotion: true } : {}) })};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") { + if (r.request().method() === "POST") { + const b = JSON.parse(r.request().postData()); + posted.push(b); + Object.assign(st, b); + } + return json(settings()); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") 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)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +// how many of the stylesheets' reduced-motion rules apply now, of all of +// them; and what a live dot, put in the page, does +const looks = (page) => page.evaluate(() => { + let reduce = 0, all = 0; + for (const sh of document.styleSheets) for (const r of sh.cssRules) { + if (!r.media) continue; + if (/prefers-reduced-motion:\s*reduce/.test(r.media.mediaText)) reduce++; + else if (r.media.mediaText === "all") all++; + } + const dot = document.createElement("i"); + dot.className = "rt-livedot on"; + document.body.append(dot); + const anim = getComputedStyle(dot).animationName; + dot.remove(); + return { reduce, all, anim, calm: calm(), motion: document.documentElement.dataset.motion || "" }; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: Reduce motion stills magpie as the system's switch does`, 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: 1000, height: 800 }, reducedMotion: "no-preference" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const st = { reduceMotion: true }, posted = []; + await page.route("**/*", serve(st, posted)); + await page.goto("http://magpie.test/?view=settings"); + const on = page.locator("#reduceMotionSegs .opt", { hasText: /^On$/ }); + const off = page.locator("#reduceMotionSegs .opt", { hasText: /^Off$/ }); + await on.waitFor(); + + const first = await looks(page); + assert(first.all > 20, `the reduced-motion rules must apply from the start (${JSON.stringify(first)})`); + assert.deepEqual({ ...first, all: 0 }, { reduce: 0, all: 0, anim: "none", calm: true, motion: "reduce" }); + assert.match(await on.getAttribute("class"), /\bon\b/); + + await off.click(); + await page.waitForFunction(() => !document.documentElement.dataset.motion); + const moving = await looks(page); + assert.deepEqual({ ...moving, reduce: 0 }, { reduce: 0, all: 0, anim: "rtlive", calm: false, motion: "" }); + assert.equal(moving.reduce, first.all, "every rule held must be the system's again"); + assert.equal(posted.at(-1).reduceMotion, false); + + await on.click(); + await page.waitForFunction(() => document.documentElement.dataset.motion === "reduce"); + assert.deepEqual(await looks(page), first, "turned on again, the page is as still as it started"); + assert.equal(posted.at(-1).reduceMotion, true); + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tests/settings-general.test.cjs b/internal/gui/tests/settings-general.test.cjs index 4967b541f..7def87157 100644 --- a/internal/gui/tests/settings-general.test.cjs +++ b/internal/gui/tests/settings-general.test.cjs @@ -30,7 +30,7 @@ const names = { en: "English", zh: "简体中文", "zh-TW": "繁體中文", ja: const appearance = { en: "Appearance", zh: "外观", "zh-TW": "外觀", ja: "外観", de: "Darstellung" }; const system = { en: "System", zh: "跟随系统", "zh-TW": "跟隨系統", ja: "システム", de: "System" }; // the rows whose name says enough, found by the control they hold -const bare = ["#themeSegs", "#colorblindSegs", "#langPick", "#textSizeSegs", "#traySegs", "#plainNamesSegs", "#loginSegs", "#dockSegs"]; +const bare = ["#themeSegs", "#colorblindSegs", "#reduceMotionSegs", "#langPick", "#textSizeSegs", "#traySegs", "#plainNamesSegs", "#loginSegs", "#dockSegs"]; // the rows that keep a line, one each const kept = ["#lightweightSegs", "#keepAwakeSegs", "#sessionTerminalRow .sess-pick"]; diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 1e8dd085c..93d5c316f 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -45,9 +45,13 @@ type Settings struct { // Colorblind switches chart series (--c1…--c7) to an Okabe–Ito palette // and gives each quota curve window, and its legend key, a dash of its // own (#2073). - Colorblind bool `json:"colorblind,omitempty"` - Lang string `json:"lang,omitempty"` // system | en | zh - Tray string `json:"tray,omitempty"` // what clicking the tray icon opens: panel | window + Colorblind bool `json:"colorblind,omitempty"` + // ReduceMotion stills magpie's animations as the system's Reduce + // Motion does, for a computer or phone that the moving Routing page + // keeps busy (#3813). + ReduceMotion bool `json:"reduceMotion,omitempty"` + Lang string `json:"lang,omitempty"` // system | en | zh + Tray string `json:"tray,omitempty"` // what clicking the tray icon opens: panel | window // SessionTerminal is the Mac app that opens a resumed session, by bundle // id. "" and "system" follow the .command file association. This // computer's own (KeepOwn): another Mac may not have that app.