Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 补齐壁纸选择器键盘导航

kirozeng2f1e53cebebd
diff --git a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
index 826db7f709..9d133142d8 100644
--- a/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WallpaperSection.tsx
@@ -1,6 +1,6 @@
import { useTranslation } from 'react-i18next';
import { RotateCcw, ImagePlus, Film } from 'lucide-react';
-import { useEffect, useCallback, useState } from 'react';
+import { useEffect, useCallback, useRef, useState } from 'react';
import { extractIpcError } from '@/utils/ipcError';
import { DownloadMeter } from './DownloadMeter';
@@ -16,12 +16,15 @@ import {
DEFAULT_APPEARANCE_SETTINGS,
isCustomWallpaperVideo,
SELECTABLE_WALLPAPER_IDS,
+ type WallpaperId,
} from '@/../shared/appearanceSettings';
export function WallpaperSection() {
const { t } = useTranslation();
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
+ const buttons = useRef(new Map<WallpaperId, HTMLButtonElement>());
+ const [focusedWallpaperId, setFocusedWallpaperId] = useState<WallpaperId | null>(null);
const {
wallpaperId,
wallpaperOverlay,
@@ -42,6 +45,10 @@ export function WallpaperSection() {
setMotion,
resetWallpaper,
} = useWallpaperSettings();
+ const entryId =
+ focusedWallpaperId ??
+ SELECTABLE_WALLPAPER_IDS.find((id) => id === wallpaperId) ??
+ SELECTABLE_WALLPAPER_IDS[0];
// The shared slider restores its starting value during cancellation. Clear
// that temporary preview after its handler, returning to the latest saved value.
const cancelBlurPreview = useCallback(() => {
@@ -129,8 +136,11 @@ export function WallpaperSection() {
className="grid grid-cols-[repeat(auto-fill,minmax(6rem,1fr))] gap-2"
role="radiogroup"
aria-label={t('settings.appearance.wallpaper.aria')}
+ onBlur={(event) => {
+ if (!event.currentTarget.contains(event.relatedTarget)) setFocusedWallpaperId(null);
+ }}
>
- {SELECTABLE_WALLPAPER_IDS.map((id) => {
+ {SELECTABLE_WALLPAPER_IDS.map((id, index) => {
const selected = wallpaperId === id;
const label = t('settings.appearance.wallpaper.options.' + id);
const background =
@@ -140,11 +150,52 @@ export function WallpaperSection() {
return (
<Tip key={id} text={label}>
<button
+ ref={(button) => {
+ if (button) buttons.current.set(id, button);
+ else buttons.current.delete(id);
+ }}
type="button"
role="radio"
aria-checked={selected}
aria-label={label}
disabled={busy}
+ tabIndex={!busy && id === entryId ? 0 : -1}
+ onFocus={() => setFocusedWallpaperId(id)}
+ onKeyDown={(event) => {
+ if (busy || event.altKey || event.ctrlKey || event.metaKey) return;
+ const rtl = getComputedStyle(event.currentTarget).direction === 'rtl';
+ let next: number;
+ switch (event.key) {
+ case 'ArrowRight':
+ next = index + (rtl ? -1 : 1);
+ break;
+ case 'ArrowLeft':
+ next = index + (rtl ? 1 : -1);
+ break;
+ case 'ArrowDown':
+ next = index + 1;
+ break;
+ case 'ArrowUp':
+ next = index - 1;
+ break;
+ case 'Home':
+ next = 0;
+ break;
+ case 'End':
+ next = SELECTABLE_WALLPAPER_IDS.length - 1;
+ break;
+ default:
+ return;
+ }
+ event.preventDefault();
+ const count = SELECTABLE_WALLPAPER_IDS.length;
+ const target = SELECTABLE_WALLPAPER_IDS[(next + count) % count];
+ buttons.current.get(target)?.focus();
+ // An empty custom tile needs explicit activation to open the file picker.
+ if (target !== wallpaperId && (target !== 'custom' || customWallpaperUrl)) {
+ setWallpaper(target);
+ }
+ }}
onClick={() =>
id === 'custom' && !customWallpaperUrl ? void chooseWallpaper() : setWallpaper(id)
}
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.keyboard.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.keyboard.test.tsx
new file mode 100644
index 0000000000..105831e8d6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/WallpaperSection.keyboard.test.tsx
@@ -0,0 +1,207 @@
+// @vitest-environment jsdom
+import React from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { WallpaperSection } from '../WallpaperSection';
+import { WallpaperSettingsProvider } from '@/hooks/useWallpaperSettings';
+import {
+ DEFAULT_APPEARANCE_SETTINGS,
+ type AppearanceSettings,
+ type WallpaperId,
+} from '@/../shared/appearanceSettings';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+let saved: AppearanceSettings;
+let changed: (settings: AppearanceSettings) => void;
+let setPatch: ReturnType<typeof vi.fn>;
+let importWallpaper: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ saved = { ...DEFAULT_APPEARANCE_SETTINGS };
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ vi.stubGlobal('electronAPI', {
+ appearanceSettings: {
+ getSync: () => saved,
+ onChanged: (listener: typeof changed) => {
+ changed = listener;
+ return () => {};
+ },
+ setPatch: (setPatch = vi.fn(async (patch: Partial<AppearanceSettings>) => {
+ saved = { ...saved, ...patch };
+ changed(saved);
+ })),
+ importWallpaper: (importWallpaper = vi.fn(async () => null)),
+ },
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+function view() {
+ return render(
+ <WallpaperSettingsProvider>
+ <button>Before</button>
+ <WallpaperSection />
+ </WallpaperSettingsProvider>,
+ );
+}
+const grid = () => screen.getByRole('radiogroup', { name: 'settings.appearance.wallpaper.aria' });
+const options = () => within(grid()).getAllByRole('radio') as HTMLButtonElement[];
+const tile = (id: WallpaperId) =>
+ within(grid()).getByRole('radio', {
+ name: 'settings.appearance.wallpaper.options.' + id,
+ });
+const tabStops = () => options().filter((button) => button.tabIndex === 0);
+const chooseButton = () =>
+ screen.getByRole('button', { name: 'settings.appearance.wallpaper.customChoose' });
+
+async function expectSelected(id: WallpaperId) {
+ await waitFor(() => expect(saved.wallpaperId).toBe(id));
+ expect(tile(id).getAttribute('aria-checked')).toBe('true');
+ expect(document.activeElement).toBe(tile(id));
+ expect(tabStops()).toEqual([tile(id)]);
+}
+
+describe('wallpaper keyboard navigation', () => {
+ it('uses one Tab stop for the whole group and allows Tab / Shift+Tab to leave and re-enter', async () => {
+ const user = userEvent.setup();
+ view();
+ await user.tab();
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Before' }));
+ await user.tab();
+ expect(document.activeElement).toBe(tile('none'));
+ expect(tabStops()).toEqual([tile('none')]);
+ await user.tab();
+ expect(document.activeElement).toBe(chooseButton());
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(tile('none'));
+ expect(setPatch).not.toHaveBeenCalled();
+ });
+
+ it('enters at the saved visible selection and updates the entry after pointer selection', async () => {
+ const user = userEvent.setup();
+ saved.wallpaperId = 'cindy-whisper';
+ view();
+ expect(tabStops()).toEqual([tile('cindy-whisper')]);
+ await user.click(tile('dune-dawn'));
+ await expectSelected('dune-dawn');
+ await user.tab();
+ expect(document.activeElement).toBe(chooseButton());
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(tile('dune-dawn'));
+ });
+
+ it('offers the first tile for a hidden saved selection without rewriting that preference', async () => {
+ saved.wallpaperId = 'blue-gaze';
+ view();
+ expect(tabStops()).toEqual([tile('none')]);
+ act(() => tile('none').focus());
+ expect(saved.wallpaperId).toBe('blue-gaze');
+ expect(setPatch).not.toHaveBeenCalled();
+ });
+
+ it('moves focus and selection with all four arrows and Home', async () => {
+ const user = userEvent.setup();
+ view();
+ act(() => tile('none').focus());
+ await user.keyboard('{ArrowRight}');
+ await expectSelected('cindy-window');
+ await user.keyboard('{ArrowDown}');
+ await expectSelected('cindy-studio');
+ await user.keyboard('{ArrowLeft}');
+ await expectSelected('cindy-window');
+ await user.keyboard('{ArrowUp}');
+ await expectSelected('none');
+ await user.keyboard('{ArrowRight}{Home}');
+ await expectSelected('none');
+ });
+
+ it('wraps across both ends and lets End select an existing custom image', async () => {
+ const user = userEvent.setup();
+ saved.customWallpaperUrl = 'cindy-media://client-wallpaper/' + 'a'.repeat(64) + '.webp';
+ view();
+ act(() => tile('none').focus());
+ await user.keyboard('{ArrowLeft}');
+ await expectSelected('custom');
+ await user.keyboard('{ArrowRight}');
+ await expectSelected('none');
+ await user.keyboard('{End}');
+ await expectSelected('custom');
+ expect(importWallpaper).not.toHaveBeenCalled();
+ });
+
+ it.each(['{Enter}', ' '])(
+ 'requires explicit %s activation to import an empty custom tile',
+ async (key) => {
+ const user = userEvent.setup();
+ view();
+ act(() => tile('none').focus());
+ await user.keyboard('{End}');
+ expect(document.activeElement).toBe(tile('custom'));
+ expect(tabStops()).toEqual([tile('custom')]);
+ expect(saved.wallpaperId).toBe('none');
+ expect(setPatch).not.toHaveBeenCalled();
+ expect(importWallpaper).not.toHaveBeenCalled();
+ await user.keyboard(key);
+ await waitFor(() => expect(importWallpaper).toHaveBeenCalledOnce());
+ expect(saved.wallpaperId).toBe('none');
+ expect(setPatch).not.toHaveBeenCalled();
+ },
+ );
+
+ it('returns the Tab entry to the selected item after leaving the empty custom tile', async () => {
+ const user = userEvent.setup();
+ view();
+ act(() => tile('none').focus());
+ await user.keyboard('{End}');
+ await user.tab();
+ expect(document.activeElement).toBe(chooseButton());
+ expect(tabStops()).toEqual([tile('none')]);
+ await user.tab({ shift: true });
+ expect(document.activeElement).toBe(tile('none'));
+ expect(importWallpaper).not.toHaveBeenCalled();
+ });
+
+ it('honors RTL for horizontal keys without reversing vertical navigation', async () => {
+ const user = userEvent.setup();
+ saved.wallpaperId = 'cindy-window';
+ view();
+ for (const button of options()) button.style.direction = 'rtl';
+ act(() => tile('cindy-window').focus());
+ await user.keyboard('{ArrowRight}');
+ await expectSelected('none');
+ await user.keyboard('{ArrowLeft}');
+ await expectSelected('cindy-window');
+ await user.keyboard('{ArrowDown}');
+ await expectSelected('cindy-studio');
+ });
+
+ it('keeps busy options out of the Tab order and ignores key presses while importing', async () => {
+ let finish!: (value: null) => void;
+ importWallpaper.mockReturnValueOnce(
+ new Promise<null>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ view();
+ fireEvent.click(tile('custom'));
+ expect(options().every((button) => button.disabled)).toBe(true);
+ expect(tabStops()).toEqual([]);
+ fireEvent.keyDown(tile('none'), { key: 'ArrowRight' });
+ expect(setPatch).not.toHaveBeenCalled();
+ await act(async () => finish(null));
+ expect(options().every((button) => !button.disabled)).toBe(true);
+ expect(tabStops()).toEqual([tile('none')]);
+ });
+});
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index ed1842ffd1..ac2ddb6acd 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -102,6 +102,10 @@ and a 4px gap before each readable name. At the standard 1280px window width thi
shows eight columns; narrower windows naturally show fewer. Keep direct click-to-apply
selection, the existing selected/focus treatment, and full names in accessible labels
and hover/focus tooltips when the visible label is truncated.
+The grid has one Tab entry, using the selected visible tile or the first tile for
+a hidden saved selection. Arrow keys move focus and selection with wrapping; Home /
+End reach the first / last tile. An empty Custom tile only receives focus during
+arrow navigation; Enter / Space explicitly opens the file picker.
Custom wallpaper is available through Choose Wallpaper, Replace Wallpaper and Remove Wallpaper
in the same section (user addition, 2026-10-01; video support, 2026-10-05). Accept local PNG/JPEG/WebP up to
20 MB and 40 megapixels, store a metadata-free static image up to 3840 pixels