Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions src/components/ContextMenu.js
Original file line number Diff line number Diff line change
@@ -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 (
<div
ref={ref}
role="menu"
aria-label={label}
className={`fixed z-[60] min-w-[200px] py-1 rounded-lg shadow-xl ${theme.app.dropdown_bg}`}
style={{
left: position?.left ?? x,
top: position?.top ?? y,
visibility: position ? 'visible' : 'hidden',
}}
onContextMenu={(e) => e.preventDefault()}
>
{items.map((item, index) =>
item.separator ? (
<div
key={`separator-${index}`}
role="separator"
className={`my-1 border-t ${theme.window.border}`}
/>
) : (
<button
key={item.label}
type="button"
role="menuitem"
disabled={item.disabled}
className={`w-full text-left px-4 py-2 text-sm flex items-center gap-3 focus:outline-none ${theme.app.text} ${
item.disabled
? 'opacity-50 cursor-not-allowed'
: `${theme.app.dropdown_item_hover} ${theme.app.dropdown_item_focus ?? ''}`
}`}
// Hover moves focus too, so mouse and keyboard share one highlight.
onPointerMove={(e) => e.currentTarget.focus()}
onClick={() => {
onClose();
item.onClick?.();
}}
>
{item.icon && (
<span aria-hidden="true" className="w-4 text-center">
{item.icon}
</span>
)}
<span className="flex-1">{item.label}</span>
{item.shortcut && (
<span className={`text-xs ml-4 ${theme.app.text_subtle}`}>
{item.shortcut}
</span>
)}
</button>
),
)}
</div>
);
}
49 changes: 28 additions & 21 deletions src/components/Desktop.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// src/components/Desktop.js

import React, { useState, useEffect, useCallback } from 'react';
import React, { useState, useEffect } from 'react';
import { useApp } from '@/context/AppContext';
import { useTheme } from '@/context/ThemeContext';
import { useSettings } from '@/context/SettingsContext';
import { useAuth } from '@/context/AuthContext';
import useStartupSound from '@/hooks/useStartupSound';
import useDesktopLayout from '@/hooks/useDesktopLayout';
import { useI18n } from '@/context/I18nContext';
import { useContextMenu } from '@/context/ContextMenuContext';

import AppIcon from './AppIcon';
import DesktopContextMenu from './DesktopContextMenu';
import Window from './Window';
import EnhancedWindow from './EnhancedWindow';
import Taskbar from './Taskbar';
Expand All @@ -22,6 +22,7 @@ import TopBarDropdownService from '@/system/services/TopBarDropdownService';
import TopBarInfoAboutService from '@/system/services/TopBarInfoAboutService';
import WindowTopBarKeyShortcutRegistrationService from '@/system/services/WindowTopBarKeyShortcutRegistrationService';
import AppRegistry from '@/system/services/AppRegistry';
import SettingsAppDefinition from '@/system/apps/SettingsApp';

// App component imports for the mapping
import NotesApp from '@/pages/apps/notes';
Expand Down Expand Up @@ -109,9 +110,10 @@ const DynamicApp = ({ appId }) => {
};

export default function Desktop() {
const { state } = useApp();
const { state, dispatch } = useApp();
const { theme } = useTheme();
const { wallpaper } = useSettings();
const { wallpaper, availableWallpapers, changeWallpaper } = useSettings();
const { openMenu } = useContextMenu();
const { user, refreshUser } = useAuth();
// Plays the startup sound once per session when enabled in Settings.
useStartupSound();
Expand All @@ -129,13 +131,31 @@ export default function Desktop() {
const { layout, grid, move, sortByName, autoArrange } =
useDesktopLayout(desktopApps);

const [menu, setMenu] = useState(null); // { x, y } of the desktop menu
const closeMenu = useCallback(() => setMenu(null), []);
const nextWallpaper = () => {
if (!availableWallpapers?.length) return;
const i = availableWallpapers.indexOf(wallpaper);
changeWallpaper(availableWallpapers[(i + 1) % availableWallpapers.length]);
};

const openSettings = () => {
dispatch({ type: 'OPEN_APP', payload: SettingsAppDefinition });
dispatch({ type: 'SET_ACTIVE_APP', payload: SettingsAppDefinition.id });
};

const handleDesktopContextMenu = (e) => {
// Only the empty desktop: windows, icons and the taskbar keep their own.
if (e.target !== e.currentTarget) return;
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY });
openMenu(
e,
[
{ label: t('desktop.sortByName'), onClick: sortByName },
{ label: t('desktop.autoArrange'), onClick: autoArrange },
{ separator: true },
{ label: t('desktop.nextWallpaper'), onClick: nextWallpaper },
{ label: t('desktop.settings'), onClick: openSettings },
],
{ label: t('desktop.menu') },
);
};

const createAppServices = (app) => {
Expand Down Expand Up @@ -462,19 +482,6 @@ export default function Desktop() {
/>
))}

{menu && (
<DesktopContextMenu
x={menu.x}
y={menu.y}
label={t('desktop.menu')}
onClose={closeMenu}
items={[
{ label: t('desktop.sortByName'), onSelect: sortByName },
{ label: t('desktop.autoArrange'), onSelect: autoArrange },
]}
/>
)}

{/* Desktop Widgets */}
<WeatherWidget />

Expand Down
74 changes: 0 additions & 74 deletions src/components/DesktopContextMenu.js

This file was deleted.

73 changes: 73 additions & 0 deletions src/context/ContextMenuContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// One right-click menu for the whole OS (#94). Any component opens it with
//
// const { openMenu } = useContextMenu();
// <div onContextMenu={(e) => 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 (
<ContextMenuContext.Provider value={value}>
{children}
{menu &&
createPortal(
// A new key per open re-runs placement and focuses the first item.
<ContextMenu
key={menu.id}
x={menu.x}
y={menu.y}
label={menu.label}
items={menu.items}
onClose={closeMenu}
/>,
document.body,
)}
</ContextMenuContext.Provider>
);
}

export function useContextMenu() {
const context = useContext(ContextMenuContext);
if (!context) {
throw new Error('useContextMenu must be used inside ContextMenuProvider');
}
return context;
}
Loading
Loading