diff --git a/src/components/ContextMenu.js b/src/components/ContextMenu.js
new file mode 100644
index 0000000..2c5211a
--- /dev/null
+++ b/src/components/ContextMenu.js
@@ -0,0 +1,150 @@
+// Right-click menu (#94), rendered by ContextMenuProvider. Started as the
+// desktop-only menu from #93; any component can now open one through
+// useContextMenu() (see src/context/ContextMenuContext.js).
+//
+// Item shape: { label, onClick, icon?, shortcut?, disabled? }, or
+// { separator: true } for a divider.
+import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { useTheme } from '@/context/ThemeContext';
+
+const EDGE = 8; // px kept free between the menu and the screen edge
+
+/**
+ * Where to put a menu of the given size opened at (x, y): at the cursor,
+ * flipped to the other side of it when it would cross the right or bottom
+ * edge, and clamped so it never leaves the screen.
+ */
+export function placeMenu(x, y, width, height, viewport) {
+ let left = x + width > viewport.width - EDGE ? x - width : x;
+ let top = y + height > viewport.height - EDGE ? y - height : y;
+ left = Math.max(EDGE, Math.min(left, viewport.width - width - EDGE));
+ top = Math.max(EDGE, Math.min(top, viewport.height - height - EDGE));
+ return { left, top };
+}
+
+const enabledItems = (menu) => [
+ ...menu.querySelectorAll('[role="menuitem"]:not([disabled])'),
+];
+
+export default function ContextMenu({ x, y, label, items, onClose }) {
+ const { theme } = useTheme();
+ const ref = useRef(null);
+ const returnFocus = useRef(null);
+ const [position, setPosition] = useState(null);
+
+ // Measure before paint so the menu never flashes off screen.
+ useLayoutEffect(() => {
+ const { offsetWidth, offsetHeight } = ref.current;
+ setPosition(
+ placeMenu(x, y, offsetWidth, offsetHeight, {
+ width: window.innerWidth,
+ height: window.innerHeight,
+ }),
+ );
+ }, [x, y, items]);
+
+ // Focus the first item once placed: while hidden for measuring it can't
+ // take focus.
+ useEffect(() => {
+ if (position && !ref.current.contains(document.activeElement)) {
+ enabledItems(ref.current)[0]?.focus();
+ }
+ }, [position]);
+
+ useEffect(() => {
+ returnFocus.current = document.activeElement;
+
+ // Keys are read on the window so they work even if focus is elsewhere.
+ const onKeyDown = (e) => {
+ if (e.key === 'Escape' || e.key === 'Tab') {
+ e.preventDefault();
+ onClose();
+ // Esc/Tab give focus back to where it was before the menu opened.
+ returnFocus.current?.focus?.();
+ return;
+ }
+ if (!ref.current) return;
+ const buttons = enabledItems(ref.current);
+ const i = buttons.indexOf(document.activeElement);
+ const next = {
+ ArrowDown: (i + 1) % buttons.length,
+ ArrowUp: (i - 1 + buttons.length) % buttons.length,
+ Home: 0,
+ End: buttons.length - 1,
+ }[e.key];
+ if (next === undefined) return;
+ e.preventDefault();
+ buttons[next]?.focus();
+ };
+ const outside = (e) => !ref.current?.contains(e.target);
+ const onPointerDown = (e) => outside(e) && onClose();
+ const onScroll = (e) => outside(e) && onClose();
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('pointerdown', onPointerDown);
+ window.addEventListener('scroll', onScroll, true);
+ window.addEventListener('blur', onClose);
+ window.addEventListener('resize', onClose);
+ return () => {
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('pointerdown', onPointerDown);
+ window.removeEventListener('scroll', onScroll, true);
+ window.removeEventListener('blur', onClose);
+ window.removeEventListener('resize', onClose);
+ };
+ }, [onClose]);
+
+ return (
+
openMenu(e, items, { label: 'Desktop' })} />
+//
+// Items are described in src/components/ContextMenu.js. Only one menu is open
+// at a time; the innermost element that calls openMenu wins.
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { createPortal } from 'react-dom';
+import ContextMenu from '@/components/ContextMenu';
+
+const ContextMenuContext = createContext(null);
+
+export function ContextMenuProvider({ children }) {
+ const [menu, setMenu] = useState(null); // { id, x, y, items, label }
+ const nextId = useRef(0);
+
+ const closeMenu = useCallback(() => setMenu(null), []);
+
+ const openMenu = useCallback((event, items, { label } = {}) => {
+ event.preventDefault();
+ // Stop outer handlers (e.g. the desktop behind an icon) from replacing
+ // this menu with their own.
+ event.stopPropagation();
+ let x = event.clientX;
+ let y = event.clientY;
+ // Shift+F10 / the context-menu key report no pointer position: open
+ // under the element instead.
+ if (!x && !y && event.currentTarget?.getBoundingClientRect) {
+ const rect = event.currentTarget.getBoundingClientRect();
+ x = rect.left;
+ y = rect.bottom;
+ }
+ nextId.current += 1;
+ setMenu({ id: nextId.current, x, y, items, label });
+ }, []);
+
+ const value = useMemo(() => ({ openMenu, closeMenu }), [openMenu, closeMenu]);
+
+ return (
+
+ {children}
+ {menu &&
+ createPortal(
+ // A new key per open re-runs placement and focuses the first item.
+ ,
+ document.body,
+ )}
+
+ );
+}
+
+export function useContextMenu() {
+ const context = useContext(ContextMenuContext);
+ if (!context) {
+ throw new Error('useContextMenu must be used inside ContextMenuProvider');
+ }
+ return context;
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index dcc06af..eaa11c8 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -48,7 +48,9 @@
"desktop": {
"menu": "Schreibtisch",
"sortByName": "Nach Name sortieren",
- "autoArrange": "Symbole automatisch anordnen"
+ "autoArrange": "Symbole automatisch anordnen",
+ "nextWallpaper": "Nächstes Hintergrundbild",
+ "settings": "Einstellungen"
},
"launcher": {
"title": "Suche",
diff --git a/src/locales/en.json b/src/locales/en.json
index dc04e4a..46dffaa 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -48,7 +48,9 @@
"desktop": {
"menu": "Desktop",
"sortByName": "Sort by name",
- "autoArrange": "Auto-arrange icons"
+ "autoArrange": "Auto-arrange icons",
+ "nextWallpaper": "Next wallpaper",
+ "settings": "Settings"
},
"launcher": {
"title": "Search",
diff --git a/src/locales/es.json b/src/locales/es.json
index a4ee142..87fbd49 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -48,7 +48,9 @@
"desktop": {
"menu": "Escritorio",
"sortByName": "Ordenar por nombre",
- "autoArrange": "Organizar iconos automáticamente"
+ "autoArrange": "Organizar iconos automáticamente",
+ "nextWallpaper": "Siguiente fondo de pantalla",
+ "settings": "Configuración"
},
"launcher": {
"title": "Buscar",
diff --git a/src/locales/zh-CN.json b/src/locales/zh-CN.json
index ed44dda..db0da70 100644
--- a/src/locales/zh-CN.json
+++ b/src/locales/zh-CN.json
@@ -48,7 +48,9 @@
"desktop": {
"menu": "桌面",
"sortByName": "按名称排序",
- "autoArrange": "自动排列图标"
+ "autoArrange": "自动排列图标",
+ "nextWallpaper": "下一张壁纸",
+ "settings": "设置"
},
"launcher": {
"title": "搜索",
diff --git a/src/locales/zh-HK.json b/src/locales/zh-HK.json
index f5ce766..6c8aecc 100644
--- a/src/locales/zh-HK.json
+++ b/src/locales/zh-HK.json
@@ -48,7 +48,9 @@
"desktop": {
"menu": "桌面",
"sortByName": "按名稱排序",
- "autoArrange": "自動排列圖示"
+ "autoArrange": "自動排列圖示",
+ "nextWallpaper": "下一張桌布",
+ "settings": "設定"
},
"launcher": {
"title": "搜尋",
diff --git a/src/pages/_app.js b/src/pages/_app.js
index 82f6e81..2af3319 100644
--- a/src/pages/_app.js
+++ b/src/pages/_app.js
@@ -11,6 +11,7 @@ import { AuthProvider, useAuth } from '@/context/AuthContext';
import { DriveProvider } from '@/context/DriveContext';
import { MusicProvider } from '@/context/MusicContext';
import { I18nProvider } from '@/context/I18nContext';
+import { ContextMenuProvider } from '@/context/ContextMenuContext';
function LockContent({ children }) {
const { user } = useAuth();
@@ -40,7 +41,9 @@ export default function MyApp({ Component, pageProps }) {
-
+
+
+
diff --git a/src/themes/darkTheme.js b/src/themes/darkTheme.js
index 1f10415..d8e6bc4 100644
--- a/src/themes/darkTheme.js
+++ b/src/themes/darkTheme.js
@@ -51,6 +51,7 @@ export const darkTheme = {
dropdown_bg: 'bg-black border border-white',
dropdown_item_hover: 'hover:bg-yellow-400 hover:text-black',
+ dropdown_item_focus: 'focus:bg-yellow-400 focus:text-black',
toolbar_button_active: 'bg-yellow-400 text-black',
},
diff --git a/src/themes/draculaTheme.js b/src/themes/draculaTheme.js
index 30cfa9b..889cbd5 100644
--- a/src/themes/draculaTheme.js
+++ b/src/themes/draculaTheme.js
@@ -50,6 +50,7 @@ export const draculaTheme = {
dropdown_bg: 'bg-[#282a36]/95 backdrop-blur-md border border-[#44475a]',
dropdown_item_hover: 'hover:bg-[#bd93f9] hover:text-[#282a36]',
+ dropdown_item_focus: 'focus:bg-[#bd93f9] focus:text-[#282a36]',
toolbar_button_active: 'bg-[#44475a] text-[#8be9fd]',
},
diff --git a/src/themes/highContrastTheme.js b/src/themes/highContrastTheme.js
index bf6ecfc..74fdd5d 100644
--- a/src/themes/highContrastTheme.js
+++ b/src/themes/highContrastTheme.js
@@ -51,6 +51,7 @@ export const highContrastTheme = {
dropdown_bg: 'bg-black border border-white',
dropdown_item_hover: 'hover:bg-yellow-400 hover:text-black',
+ dropdown_item_focus: 'focus:bg-yellow-400 focus:text-black',
toolbar_button_active: 'bg-yellow-400 text-black',
},
diff --git a/src/themes/lightTheme.js b/src/themes/lightTheme.js
index c2df6ab..1d91f36 100644
--- a/src/themes/lightTheme.js
+++ b/src/themes/lightTheme.js
@@ -49,6 +49,7 @@ export const lightTheme = {
dropdown_bg: 'bg-white/95 backdrop-blur-md border border-gray-200',
dropdown_item_hover: 'hover:bg-blue-500 hover:text-white',
+ dropdown_item_focus: 'focus:bg-blue-500 focus:text-white',
toolbar_button_active: 'bg-blue-200 text-blue-800',
},
diff --git a/src/themes/nordTheme.js b/src/themes/nordTheme.js
index 15fb8a6..bce505b 100644
--- a/src/themes/nordTheme.js
+++ b/src/themes/nordTheme.js
@@ -50,6 +50,7 @@ export const nordTheme = {
dropdown_bg: 'bg-[#2e3440]/95 backdrop-blur-md border border-[#4c566a]',
dropdown_item_hover: 'hover:bg-[#5e81ac] hover:text-[#eceff4]',
+ dropdown_item_focus: 'focus:bg-[#5e81ac] focus:text-[#eceff4]',
toolbar_button_active: 'bg-[#5e81ac] text-[#eceff4]',
},
diff --git a/src/themes/solarizedTheme.js b/src/themes/solarizedTheme.js
index c2d7f6c..4985b3e 100644
--- a/src/themes/solarizedTheme.js
+++ b/src/themes/solarizedTheme.js
@@ -51,6 +51,7 @@ export const solarizedTheme = {
dropdown_bg: 'bg-[#fdf6e3]/95 backdrop-blur-md border border-[#93a1a1]/50',
dropdown_item_hover: 'hover:bg-[#268bd2] hover:text-[#fdf6e3]',
+ dropdown_item_focus: 'focus:bg-[#268bd2] focus:text-[#fdf6e3]',
toolbar_button_active: 'bg-[#b3dce8] text-[#075985]',
},
diff --git a/tests/ContextMenu.test.js b/tests/ContextMenu.test.js
new file mode 100644
index 0000000..6e8ea11
--- /dev/null
+++ b/tests/ContextMenu.test.js
@@ -0,0 +1,221 @@
+import React from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { placeMenu } from '@/components/ContextMenu';
+import {
+ ContextMenuProvider,
+ useContextMenu,
+} from '@/context/ContextMenuContext';
+
+jest.mock('@/context/ThemeContext', () => ({
+ useTheme: () => ({
+ theme: {
+ app: {
+ dropdown_bg: 'menu-bg',
+ dropdown_item_hover: 'hover:item',
+ dropdown_item_focus: 'focus:item',
+ text: '',
+ text_subtle: '',
+ },
+ window: { border: '' },
+ },
+ }),
+}));
+
+function Target({ items, label = 'Test menu', children }) {
+ const { openMenu } = useContextMenu();
+ return (
+
openMenu(e, items, { label })}
+ >
+ {children}
+
+ );
+}
+
+const setup = (items) => {
+ render(
+
+ outside
+
+ ,
+ );
+ const opened = fireEvent.contextMenu(screen.getByTestId('target'), {
+ clientX: 40,
+ clientY: 50,
+ });
+ return { opened };
+};
+
+describe('placeMenu', () => {
+ const viewport = { width: 1000, height: 800 };
+
+ it('opens at the cursor when the menu fits', () => {
+ expect(placeMenu(100, 100, 200, 150, viewport)).toEqual({
+ left: 100,
+ top: 100,
+ });
+ });
+
+ it('flips to the other side of the cursor near the right and bottom edges', () => {
+ expect(placeMenu(950, 750, 200, 150, viewport)).toEqual({
+ left: 750,
+ top: 600,
+ });
+ });
+
+ it('never leaves the screen', () => {
+ expect(placeMenu(10, 10, 200, 900, viewport)).toEqual({
+ left: 10,
+ top: 8,
+ });
+ expect(placeMenu(150, 5, 200, 150, viewport).left).toBeGreaterThanOrEqual(
+ 8,
+ );
+ });
+});
+
+describe('ContextMenuProvider', () => {
+ it('replaces the browser menu with a labelled, themed menu', () => {
+ const { opened } = setup([{ label: 'Open', onClick: jest.fn() }]);
+
+ // fireEvent returns false when the default (browser menu) was prevented.
+ expect(opened).toBe(false);
+ const menu = screen.getByRole('menu', { name: 'Test menu' });
+ expect(menu).toHaveClass('menu-bg');
+ expect(screen.getByRole('menuitem', { name: 'Open' })).toHaveClass(
+ 'hover:item',
+ 'focus:item',
+ );
+ });
+
+ it('focuses the first item and moves with the arrow keys, skipping disabled items and separators', () => {
+ setup([
+ { label: 'First', onClick: jest.fn() },
+ { label: 'Disabled', onClick: jest.fn(), disabled: true },
+ { separator: true },
+ { label: 'Last', onClick: jest.fn() },
+ ]);
+ const menu = screen.getByRole('menu');
+ const first = screen.getByRole('menuitem', { name: 'First' });
+ const last = screen.getByRole('menuitem', { name: 'Last' });
+
+ expect(first).toHaveFocus();
+ fireEvent.keyDown(menu, { key: 'ArrowDown' });
+ expect(last).toHaveFocus();
+ fireEvent.keyDown(menu, { key: 'ArrowDown' });
+ expect(first).toHaveFocus();
+ fireEvent.keyDown(menu, { key: 'ArrowUp' });
+ expect(last).toHaveFocus();
+ fireEvent.keyDown(menu, { key: 'Home' });
+ expect(first).toHaveFocus();
+ fireEvent.keyDown(menu, { key: 'End' });
+ expect(last).toHaveFocus();
+ expect(screen.getByRole('separator')).toBeInTheDocument();
+ });
+
+ it('runs the action and closes when an item is chosen', () => {
+ const onClick = jest.fn();
+ setup([{ label: 'Open', onClick }]);
+
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Open' }));
+
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ });
+
+ it('does not run disabled items', () => {
+ const onClick = jest.fn();
+ setup([{ label: 'Nope', onClick, disabled: true }]);
+
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Nope' }));
+
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('closes on Escape and gives focus back', () => {
+ render(
+
+
+ trigger
+
+ ,
+ );
+ const trigger = screen.getByRole('button', { name: 'trigger' });
+ trigger.focus();
+ fireEvent.contextMenu(trigger, { clientX: 10, clientY: 10 });
+ expect(screen.getByRole('menuitem', { name: 'Open' })).toHaveFocus();
+
+ fireEvent.keyDown(screen.getByRole('menu'), { key: 'Escape' });
+
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ expect(trigger).toHaveFocus();
+ });
+
+ it('closes on a click outside, a scroll and a resize', () => {
+ const items = [{ label: 'Open', onClick: jest.fn() }];
+
+ setup(items);
+ fireEvent.pointerDown(screen.getByRole('button', { name: 'outside' }));
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+
+ fireEvent.contextMenu(screen.getByTestId('target'));
+ fireEvent.scroll(document);
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+
+ fireEvent.contextMenu(screen.getByTestId('target'));
+ fireEvent(window, new Event('resize'));
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ });
+
+ it('stays open when clicking inside the menu', () => {
+ setup([{ label: 'Open', onClick: jest.fn() }]);
+
+ fireEvent.pointerDown(screen.getByRole('menu'));
+
+ expect(screen.getByRole('menu')).toBeInTheDocument();
+ });
+
+ it('lets the innermost element win over its parent', () => {
+ function Nested() {
+ const { openMenu } = useContextMenu();
+ return (
+
+ openMenu(e, [{ label: 'Outer', onClick: jest.fn() }])
+ }
+ >
+
+ openMenu(e, [{ label: 'Inner', onClick: jest.fn() }])
+ }
+ />
+
+ );
+ }
+ render(
+
+
+ ,
+ );
+
+ fireEvent.contextMenu(screen.getByTestId('inner'));
+
+ expect(screen.getByRole('menuitem', { name: 'Inner' })).toBeInTheDocument();
+ expect(screen.queryByRole('menuitem', { name: 'Outer' })).toBeNull();
+ });
+
+ it('throws a clear error outside the provider', () => {
+ jest.spyOn(console, 'error').mockImplementation(() => {});
+ const Lonely = () => {
+ useContextMenu();
+ return null;
+ };
+
+ expect(() => render(
)).toThrow(
+ 'useContextMenu must be used inside ContextMenuProvider',
+ );
+ console.error.mockRestore();
+ });
+});