46 lines
1.4 KiB
TypeScript
46 lines
1.4 KiB
TypeScript
import { storageGet, storageSet } from "./storage";
|
|
|
|
/**
|
|
* 减少动态效果 (HEL-649 §五). The OS setting always wins (app.css also reacts
|
|
* to `prefers-reduced-motion` directly, so it cannot be switched off here);
|
|
* otherwise the top-bar switch decides. The effective value is mirrored to
|
|
* `<html data-reduce="1">`, which is what every reduced-motion rule keys on.
|
|
*/
|
|
const STORAGE_KEY = "aigc-reduce-motion";
|
|
const QUERY = "(prefers-reduced-motion: reduce)";
|
|
|
|
export const reduceMotion = $state({ system: false, manual: false });
|
|
|
|
let stop: (() => void) | null = null;
|
|
|
|
function apply() {
|
|
document.documentElement.dataset.reduce =
|
|
reduceMotion.system || reduceMotion.manual ? "1" : "0";
|
|
}
|
|
|
|
/** Call once on the client (root layout). Returns the teardown. */
|
|
export function initReduceMotion(): () => void {
|
|
if (typeof window === "undefined") return () => {};
|
|
stop?.();
|
|
const mq = window.matchMedia(QUERY);
|
|
reduceMotion.system = mq.matches;
|
|
reduceMotion.manual = storageGet(STORAGE_KEY) === "1";
|
|
apply();
|
|
const onChange = (e: MediaQueryListEvent) => {
|
|
reduceMotion.system = e.matches;
|
|
apply();
|
|
};
|
|
mq.addEventListener("change", onChange);
|
|
stop = () => mq.removeEventListener("change", onChange);
|
|
return () => {
|
|
stop?.();
|
|
stop = null;
|
|
};
|
|
}
|
|
|
|
export function setReduceMotion(on: boolean) {
|
|
reduceMotion.manual = on;
|
|
storageSet(STORAGE_KEY, on ? "1" : "0");
|
|
apply();
|
|
}
|