A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
feat(settings): enhance Windows preferences handling and improve notification controls
CristianOlivera1a0647e3a8c3f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0dd4936..e5ab3fe 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -34,6 +34,7 @@ jobs:working-directory: apps/settingsrun: |pnpm install --frozen-lockfile+ pnpm testpnpm build- run: cargo fmt --all --checkdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a938da6..01b796e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,14 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- Fixed notification controls and stray conditional text appearing in Menu Bar+ settings. Each page now starts at the top when selected. Failed preference+ writes remain retryable and keep Settings open until changes can be saved.+- Fixed stale reset-confirmation timers; added Settings rendering and save-failure+ regression checks to CI without new runtime dependencies.+- Settings now shows the actual Windows state for automatic Search, Task View,+ Widgets and battery-percentage switches. Explicit choices remain authoritative;+ system values are display-only and refresh on focus without idle polling.- Added macOS-style glass notification banners supporting configurable screen positions (top-right or bottom-right), auto-dismiss with hover pause, click-to-activate, and dismiss button or middle-click.- Added red unread notification count badges on dock icons, cleared automatically when the app is focused or dismissed.- Added dock icon attention bounce on shell alert events (`HSHELL_FLASH`), respecting Windows reduced-motion settings.@@ -28,6 +36,16 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Corregidas las opciones de Notificaciones y el texto de una condición que+ aparecían en Barra superior. Cada sección comienza arriba al seleccionarla.+ Los cambios que fallen al guardarse se conservan para reintentar y Ajustes+ permanece abierto hasta poder guardarlos.+- Corregidos los temporizadores antiguos de confirmación al restablecer;+ añadidas pruebas de pantallas y fallos de guardado a CI sin nuevas dependencias.+- Ajustes muestra el estado real de Windows en los interruptores automáticos de+ Búsqueda, Vista de tareas, Widgets y porcentaje de batería. Las elecciones+ explícitas tienen prioridad; los valores del sistema solo se muestran y se+ releen al recuperar el foco, sin sondeo en reposo.- Incorporadas alertas en banners de cristal estilo macOS con posición configurable (superior o inferior derecha), desaparición automática con pausa al pasar el cursor, clic para activar y botón de cierre o clic central para descartar.- Incorporadas insignias rojas de contador de notificaciones pendientes en los iconos del dock, eliminadas automáticamente al enfocar la app o descartar sus avisos.- Incorporada animación de rebote de atención en el dock cuando una app solicita atención (`HSHELL_FLASH`), respetando las preferencias de movimiento reducido de Windows.diff --git a/apps/settings/package.json b/apps/settings/package.jsonindex 3a99abc..55fc3cf 100644--- a/apps/settings/package.json+++ b/apps/settings/package.json@@ -5,6 +5,7 @@"type": "module","scripts": {"dev": "vite",+ "test": "node --test tests/*.test.mjs","build": "tsc --noEmit && vite build","tauri": "tauri"},diff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsindex 5467e69..d4532ee 100644--- a/apps/settings/src-tauri/src/main.rs+++ b/apps/settings/src-tauri/src/main.rs@@ -46,11 +46,28 @@ async fn set_config(patch: serde_json::Map<String, serde_json::Value>) -> Result.map_err(|error| error.to_string())?}-/// Windows' own animation setting, which the genie follows: off, the-/// genie does not play, and the window says so.+/// Read-only system defaults for the Settings view, separate from saved+/// overrides. Reuse the menu bar's readers so both agree on absent values.+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct WindowsPreferences {+ animations: bool,+ menu_bar_search: bool,+ menu_bar_task_view: bool,+ menu_bar_widgets: bool,+ menu_bar_battery_percent: bool,+}+#[tauri::command]-fn windows_animations() -> bool {- muelle_shell::system::animations_enabled()+fn windows_preferences() -> WindowsPreferences {+ let buttons = muelle_shell::status::taskbar_buttons();+ WindowsPreferences {+ animations: muelle_shell::system::animations_enabled(),+ menu_bar_search: buttons.search,+ menu_bar_task_view: buttons.task_view,+ menu_bar_widgets: buttons.widgets,+ menu_bar_battery_percent: muelle_shell::status::battery_percentage_enabled(),+ }}/// The page of Windows Settings with that switch: "Animation effects" on@@ -329,7 +346,7 @@ fn main() {set_config,get_autostart,set_autostart,- windows_animations,+ windows_preferences,open_animation_settings,pick_folder,check_update,diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxindex 4143cd8..8962e90 100644--- a/apps/settings/src/App.tsx+++ b/apps/settings/src/App.tsx@@ -9,13 +9,14 @@ import {type IslandStyle,type Language,type UpdateInfo,+ type WindowsPreferences,ICON_SIZE,MAX_MAGNIFIED_SIZE,checkUpdate,defaultConfig,getAutostart,openAnimationSettings,- windowsAnimations,+ loadWindowsPreferences,installUpdate,loadConfig,loadWallpaperPreview,@@ -76,18 +77,20 @@ function textsFor(language: Language): Texts {export function App() {const [config, setConfig] = useState<Config | null>(null);const [autostart, setAutostartState] = useState(false);- // Assumed on until asked, so the notice never flashes on a normal PC.- const [animations, setAnimations] = useState(true);+ const [windowsPreferences, setWindowsPreferences] = useState<WindowsPreferences | null>(null);+ // Keep the animation notice from flashing while the initial system read is pending.+ const animations = windowsPreferences?.animations ?? true;useEffect(() => {+ let alive = true;const check = () => {- windowsAnimations()- .then(setAnimations)+ loadWindowsPreferences()+ .then((values) => { if (alive) setWindowsPreferences(values); }).catch(() => {});};check();- // Back from Windows Settings after turning them on: the notice goes.+ // One shared focus listener, with no polling while Settings is idle or closed.window.addEventListener("focus", check);- return () => window.removeEventListener("focus", check);+ return () => { alive = false; window.removeEventListener("focus", check); };}, []);const [section, setSection] = useState<SectionId>("dock");const [failed, setFailed] = useState(false);@@ -104,19 +107,29 @@ export function App() {/** "Later" hides the banner until Settings is opened again. */const [bannerDismissed, setBannerDismissed] = useState(false);const pending = useRef<Partial<Config> | null>(null);- const writes = useRef(Promise.resolve());+ const writes = useRef(Promise.resolve(true));const timer = useRef<number | undefined>(undefined);const resetTimer = useRef<number | undefined>(undefined);const flushSettings = useCallback(() => {window.clearTimeout(timer.current);- const latest = pending.current;- pending.current = null;- if (latest) {- writes.current = writes.current- .then(() => saveConfig(latest))- .then(() => setFailed(false))- .catch(() => setFailed(true));+ if (pending.current) {+ writes.current = writes.current.then(async () => {+ // Take the patch when its turn starts. A failed earlier write can then+ // rejoin the queue without overwriting a newer choice for the same key.+ const latest = pending.current;+ if (!latest) return true;+ pending.current = null;+ try {+ await saveConfig(latest);+ setFailed(false);+ return true;+ } catch {+ pending.current = Object.assign({}, latest, pending.current);+ setFailed(true);+ return false;+ }+ });}return writes.current;}, []);@@ -153,10 +166,14 @@ export function App() {}closing = true;// A change can be buffered or queued while an earlier write finishes.- let drained: Promise<void>;+ let drained: Promise<boolean>;do {drained = flushSettings();- await drained;+ if (!await drained) {+ event.preventDefault();+ closing = false;+ return;+ }} while (pending.current || writes.current !== drained);});return () => {@@ -219,6 +236,7 @@ export function App() {resetTimer.current = window.setTimeout(() => setConfirmingReset(false), RESET_CONFIRM_MS);return;}+ window.clearTimeout(resetTimer.current);setConfirmingReset(false);defaultConfig().then(({ pinned: _pinned, recent: _recent, shortcutsFolder: _folder, ...defaults }) =>@@ -304,7 +322,7 @@ export function App() {onNotes={() => showNotes(waiting)}/>) : null}- <div className="content-body">+ <div className="content-body" key={section}>{section === "dock" ? (<><Card title={t.groupAppearance}>@@ -441,7 +459,6 @@ export function App() {</Card></>) : section === "menubar" ? (-<><Card><Row icon={<SettingIcon name="menu" />} label={t.menuBarShow} hint={t.menuBarHint}>@@ -508,33 +525,34 @@ export function App() {<Row icon={<SettingIcon name="battery" />} label={t.menuBarBatteryPercent} hint={t.menuBarBatteryPercentHint}><Togglelabel={t.menuBarBatteryPercent}- checked={config.menuBarBatteryPercent ?? false}+ checked={config.menuBarBatteryPercent ?? windowsPreferences?.menuBarBatteryPercent}onChange={(menuBarBatteryPercent) => update({ menuBarBatteryPercent })}/></Row><Row icon={<SettingIcon name="search" />} label={t.menuBarSearch} hint={t.menuBarSearchHint}><Togglelabel={t.menuBarSearch}- checked={config.menuBarSearch ?? true}+ checked={config.menuBarSearch ?? windowsPreferences?.menuBarSearch}onChange={(menuBarSearch) => update({ menuBarSearch })}/></Row><Row icon={<SettingIcon name="windows" />} label={t.menuBarTaskView} hint={t.menuBarTaskViewHint}><Togglelabel={t.menuBarTaskView}- checked={config.menuBarTaskView ?? true}+ checked={config.menuBarTaskView ?? windowsPreferences?.menuBarTaskView}onChange={(menuBarTaskView) => update({ menuBarTaskView })}/></Row><Row icon={<SettingIcon name="widgets" />} label={t.menuBarWidgets} hint={t.menuBarWidgetsHint}><Togglelabel={t.menuBarWidgets}- checked={config.menuBarWidgets ?? true}+ checked={config.menuBarWidgets ?? windowsPreferences?.menuBarWidgets}onChange={(menuBarWidgets) => update({ menuBarWidgets })}/></Row></Card>)}+ </>) : section === "notifications" ? (<><Card>@@ -591,7 +609,6 @@ export function App() {</Row></Card></>- </>) : (<><Card>diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsindex 79d44cc..186b04d 100644--- a/apps/settings/src/config.ts+++ b/apps/settings/src/config.ts@@ -56,8 +56,20 @@ export const loadConfig = () => invoke<Config>("get_config");export const defaultConfig = () => invoke<Config>("default_config");export const saveConfig = (patch: Partial<Config>) => invoke<Config>("set_config", { patch });export const getAutostart = () => invoke<boolean>("get_autostart");-/** Windows' animation setting; the genie only plays while it is on. */-export const windowsAnimations = () => invoke<boolean>("windows_animations");+/** Current Windows values for display only; never merge these into Config. */+export interface WindowsPreferences {+ animations: boolean;+ menuBarSearch: boolean;+ menuBarTaskView: boolean;+ menuBarWidgets: boolean;+ menuBarBatteryPercent: boolean;+}++let windowsPreferencesRequest: Promise<WindowsPreferences> | undefined;+/** Coalesce overlapping focus/StrictMode reads, but reread after returning from Windows Settings. */+export const loadWindowsPreferences = () =>+ windowsPreferencesRequest ??= invoke<WindowsPreferences>("windows_preferences")+ .finally(() => { windowsPreferencesRequest = undefined; });export const openAnimationSettings = () => invoke<void>("open_animation_settings");export const setAutostart = (enabled: boolean) => invoke<void>("set_autostart", { enabled });/** The folder the user picks, or null if they cancel. */diff --git a/apps/settings/src/controls.tsx b/apps/settings/src/controls.tsxindex e1ba7a1..231d599 100644--- a/apps/settings/src/controls.tsx+++ b/apps/settings/src/controls.tsx@@ -58,22 +58,26 @@ export function SubRow({ open, ...row }: SubRowProps) {}interface ToggleProps {- checked: boolean;+ /** Undefined while an inherited system value is still being read. */+ checked: boolean | undefined;label: string;onChange: (checked: boolean) => void;}export function Toggle({ checked, label, onChange }: ToggleProps) {+ const pending = checked === undefined;return (<buttontype="button"- role="switch"+ role={pending ? undefined : "switch"}aria-checked={checked}aria-label={label}+ aria-busy={pending || undefined}+ disabled={pending}className="toggle"- onClick={() => onChange(!checked)}+ onClick={() => { if (!pending) onChange(!checked); }}>- <span className="toggle-knob" />+ {pending ? <span className="toggle-pending" aria-hidden="true">…</span> : <span className="toggle-knob" />}</button>);}diff --git a/apps/settings/src/styles.css b/apps/settings/src/styles.cssindex ad9ad97..b63a0ea 100644--- a/apps/settings/src/styles.css+++ b/apps/settings/src/styles.css@@ -408,6 +408,9 @@ input:focus-visible {background: #34c759;}+.toggle[aria-busy="true"] { opacity: 0.55; }+.toggle-pending { display: block; color: var(--text-dim); line-height: 18px; }+.toggle-knob {display: block;width: 18px;diff --git a/apps/settings/tests/app.test.mjs b/apps/settings/tests/app.test.mjsnew file mode 100644index 0000000..2f7f36f--- /dev/null+++ b/apps/settings/tests/app.test.mjs@@ -0,0 +1,175 @@+import assert from "node:assert/strict";+import { readFileSync, readdirSync } from "node:fs";+import { createRequire } from "node:module";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { runInThisContext } from "node:vm";+import test from "node:test";+import * as React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { transformWithEsbuild } from "vite";++// Exercise the actual App and controls without WebView, registry, network or timers.+// Compilation alone cannot catch a conditional accidentally rendered as JSX text.+const source = fileURLToPath(new URL("../src/", import.meta.url));+const require = createRequire(import.meta.url);+const compiled = new Map();+for (const file of readdirSync(source).filter((name) => /\.tsx?$/.test(name))) {+ const filename = path.join(source, file);+ const { code } = await transformWithEsbuild(readFileSync(filename, "utf8"), filename, {+ format: "cjs", jsx: "automatic",+ });+ compiled.set(filename, runInThisContext(`(function(require,module,exports){${code}\n})`, { filename }));+}+const texts = Object.fromEntries(["en", "es", "fr"].map((language) => [+ language, JSON.parse(readFileSync(path.join(source, "i18n", `${language}.json`), "utf8")),+]));+const base = {+ language: "en", menuBar: true, notifications: true, notificationDuration: 5,+ notificationPosition: "top-right", iconSize: 48, magnifiedSize: 77,+ magnification: true, dockPosition: "bottom", genie: true, genieSpeed: "normal",+ menuBarIslandStyle: "notch", menuBarSearch: null, menuBarTaskView: null,+ menuBarWidgets: null, menuBarBatteryPercent: null, checkUpdates: false,+ pinned: [], recent: [], mutedApps: [], shortcutsFolder: null,+};+const settle = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };+function* elements(node) {+ if (Array.isArray(node)) { for (const child of node) yield* elements(child); }+ else if (React.isValidElement(node)) { yield node; yield* elements(node.props.children); }+}++function fixture(section = "menubar", config = {}, save = async () => {}) {+ const states = [], refs = [], effects = [], timers = new Map(), calls = [];+ let stateIndex = 0, refIndex = 0, nextTimer = 0, close;+ const loaded = { ...base, ...config };+ const browser = {+ addEventListener() {}, removeEventListener() {},+ setTimeout(callback, delay) { const id = ++nextTimer; timers.set(id, { callback, delay }); return id; },+ clearTimeout(id) { timers.delete(id); },+ };+ globalThis.window = browser;+ const hooks = {+ ...React,+ useState(initial) {+ const index = stateIndex++;+ if (!(index in states)) states[index] = index === 0 ? loaded : initial === "dock" ? section : initial;+ return [states[index], (value) => { states[index] = typeof value === "function" ? value(states[index]) : value; }];+ },+ useRef(initial) { const index = refIndex++; return refs[index] ??= { current: initial }; },+ useCallback(callback) { return callback; },+ useEffect(callback) { effects.push(callback); },+ };+ const nativeWindow = { onCloseRequested(callback) { close = callback; return Promise.resolve(() => {}); } };+ const mocks = {+ "@tauri-apps/api/app": { getVersion: async () => "0.1.18" },+ "@tauri-apps/api/event": { listen: async () => () => {} },+ "@tauri-apps/api/window": { getCurrentWindow: () => nativeWindow },+ "@tauri-apps/api/core": { invoke: async (command, args) => {+ switch (command) {+ case "get_config": return loaded;+ case "get_autostart": return false;+ case "windows_preferences": return { animations: true, menuBarSearch: false };+ case "wallpaper_preview": return null;+ case "default_config": return base;+ case "set_config": calls.push({ ...args.patch }); return save(args.patch);+ default: throw new Error(`Unexpected native call: ${command}`);+ }+ } },+ };+ const modules = new Map();+ function load(filename) {+ if (modules.has(filename)) return modules.get(filename).exports;+ if (filename.endsWith(".json")) return JSON.parse(readFileSync(filename, "utf8"));+ const module = { exports: {} };+ modules.set(filename, module);+ compiled.get(filename)((id) => {+ if (id === "react" && filename === path.join(source, "App.tsx")) return hooks;+ if (id in mocks) return mocks[id];+ if (!id.startsWith(".")) return require(id);+ const resolved = path.resolve(path.dirname(filename), id);+ return load(compiled.has(`${resolved}.tsx`) ? `${resolved}.tsx` : compiled.has(`${resolved}.ts`) ? `${resolved}.ts` : resolved);+ }, module, module.exports);+ return module.exports;+ }+ const { App } = load(path.join(source, "App.tsx"));+ function render() { stateIndex = refIndex = 0; effects.length = 0; return App(); }+ function find(predicate) { const node = [...elements(render())].find(predicate); assert.ok(node); return node; }+ return {+ calls, timers, render,+ async mount() { render(); const cleanup = effects.map((effect) => effect()); await settle(); return () => cleanup.forEach((fn) => fn?.()); },+ change(label, value) { find((node) => node.props.label === label && typeof node.props.onChange === "function").props.onChange(value); },+ button(text) { find((node) => node.type === "button" && node.props.children === text).props.onClick(); },+ body() { return find((node) => node.props.className === "content-body"); },+ fire(delay) { for (const [id, timer] of [...timers]) if (timer.delay === delay) { timers.delete(id); timer.callback(); } },+ async close() { let prevented = false; await close({ preventDefault() { prevented = true; } }); return prevented; },+ };+}++test("each section renders only its own controls, in every language and visibility state", () => {+ const markers = { dock: "size", windows: "genie", menubar: "menuBarShow", notifications: "notificationsEnabled", system: "autostart" };+ for (const language of Object.keys(texts)) for (const menuBar of [true, false]) for (const notifications of [true, false]) {+ for (const section of Object.keys(markers)) {+ const view = fixture(section, { language, menuBar, notifications });+ const body = view.body();+ const html = renderToStaticMarkup(body);+ assert.doesNotMatch(html, /section\s*===|\)\s*:\s*section/);+ for (const [other, key] of Object.entries(markers)) {+ const escaped = renderToStaticMarkup(React.createElement("span", null, texts[language][key])).slice(6, -7);+ assert.equal(html.includes(escaped), other === section, `${language}/${section}: ${other}`);+ }+ assert.equal(body.key, section, "navigation resets the scroll container");+ }+ }+});++test("failed writes remain retryable and prevent closing until saved", async () => {+ let fail = true;+ const view = fixture("menubar", {}, async () => { if (fail) throw new Error("disk busy"); });+ const unmount = await view.mount();+ try {+ view.change(texts.en.menuBarSearch, false);+ view.fire(60);+ await settle();+ assert.equal(await view.close(), true);+ assert.equal(view.calls.length, 2);+ assert.ok(renderToStaticMarkup(view.body()).includes(texts.en.saveError));+ fail = false;+ assert.equal(await view.close(), false);+ assert.deepEqual(view.calls, Array(3).fill({ menuBarSearch: false }));+ assert.ok(!renderToStaticMarkup(view.body()).includes(texts.en.saveError));+ } finally { unmount(); }+});++test("a queued newer choice wins over an earlier failed write", async () => {+ let rejectFirst;+ const view = fixture("menubar", {}, () => view.calls.length === 1+ ? new Promise((_, reject) => { rejectFirst = reject; }) : Promise.resolve());+ const unmount = await view.mount();+ try {+ view.change(texts.en.menuBarSearch, false);+ view.fire(60);+ await settle();+ view.change(texts.en.menuBarSearch, true);+ view.change(texts.en.menuBarWidgets, false);+ view.fire(60);+ rejectFirst(new Error("disk busy"));+ await settle();+ assert.deepEqual(view.calls, [{ menuBarSearch: false }, { menuBarSearch: true, menuBarWidgets: false }]);+ assert.equal(await view.close(), false);+ assert.equal(view.calls.length, 2, "the obsolete value must not be replayed on close");+ } finally { unmount(); }+});++test("confirming reset cancels its old confirmation timer", async () => {+ const view = fixture("system");+ const unmount = await view.mount();+ try {+ view.button(texts.en.resetButton);+ assert.equal([...view.timers.values()].filter((timer) => timer.delay === 4000).length, 1);+ view.button(texts.en.resetConfirm);+ assert.equal([...view.timers.values()].filter((timer) => timer.delay === 4000).length, 0);+ await settle();+ view.button(texts.en.resetButton);+ assert.equal([...view.timers.values()].filter((timer) => timer.delay === 4000).length, 1);+ } finally { unmount(); }+});