Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Make resource action menus keyboard operable

pulse-triage[bot]d3196f64a0b0
diff --git a/frontend-modern/src/components/shared/useMenuButton.ts b/frontend-modern/src/components/shared/useMenuButton.ts
new file mode 100644
index 0000000000..f2fc0eb94b
--- /dev/null
+++ b/frontend-modern/src/components/shared/useMenuButton.ts
@@ -0,0 +1,122 @@
+import { createEffect, createUniqueId } from 'solid-js';
+import type { Accessor } from 'solid-js';
+
+type MenuFocusTarget = 'first' | 'last';
+
+interface MenuButtonOptions {
+ isOpen: Accessor<boolean>;
+ setOpen: (open: boolean) => void;
+ trigger: () => HTMLElement | undefined;
+ menu: () => HTMLElement | undefined;
+}
+
+const MENU_ITEM_SELECTOR = '[role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]';
+
+function getEnabledMenuItems(menu: HTMLElement | undefined): HTMLElement[] {
+ return Array.from(menu?.querySelectorAll<HTMLElement>(MENU_ITEM_SELECTOR) ?? []).filter(
+ (item) => !item.hasAttribute('disabled') && item.getAttribute('aria-disabled') !== 'true',
+ );
+}
+
+/**
+ * Focus and keyboard behavior shared by action-menu buttons.
+ *
+ * Menu content may be portaled away from its trigger, so relying on document
+ * tab order would make operators traverse the rest of the page before reaching
+ * it. This helper explicitly moves focus into the menu and implements the APG
+ * menu-button arrow, Home, End, Escape, and Tab behaviors.
+ */
+export function useMenuButton(options: MenuButtonOptions) {
+ const uniqueId = createUniqueId();
+ const triggerId = `pulse-menu-trigger-${uniqueId}`;
+ const menuId = `pulse-menu-${uniqueId}`;
+ let requestedFocus: MenuFocusTarget = 'first';
+
+ const menuItems = () => getEnabledMenuItems(options.menu());
+
+ const focusItem = (target: MenuFocusTarget) => {
+ queueMicrotask(() => {
+ const items = menuItems();
+ (target === 'last' ? items.at(-1) : items[0])?.focus();
+ });
+ };
+
+ const openMenu = (target: MenuFocusTarget = 'first') => {
+ requestedFocus = target;
+ options.setOpen(true);
+ focusItem(target);
+ };
+
+ const closeMenu = (restoreFocus = false) => {
+ options.setOpen(false);
+ if (restoreFocus) queueMicrotask(() => options.trigger()?.focus());
+ };
+
+ const toggleMenu = () => {
+ if (options.isOpen()) {
+ closeMenu();
+ return;
+ }
+ openMenu();
+ };
+
+ createEffect(() => {
+ if (!options.isOpen()) return;
+ const target = requestedFocus;
+ requestedFocus = 'first';
+ focusItem(target);
+ });
+
+ const handleTriggerKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape' && options.isOpen()) {
+ event.preventDefault();
+ closeMenu(true);
+ return;
+ }
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
+ event.preventDefault();
+ openMenu(event.key === 'ArrowUp' ? 'last' : 'first');
+ };
+
+ const handleMenuKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ closeMenu(true);
+ return;
+ }
+ if (event.key === 'Tab') {
+ // Return focus to the trigger synchronously, then let the browser's
+ // native Tab/Shift+Tab action move to the adjacent page control.
+ // If the focused portaled item were removed first, browsers could
+ // restart sequential navigation at the beginning of the document.
+ options.trigger()?.focus({ preventScroll: true });
+ options.setOpen(false);
+ return;
+ }
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
+
+ const items = menuItems();
+ if (items.length === 0) return;
+ event.preventDefault();
+ const currentIndex = items.indexOf(document.activeElement as HTMLElement);
+ let nextIndex = 0;
+ if (event.key === 'End') {
+ nextIndex = items.length - 1;
+ } else if (event.key === 'ArrowDown') {
+ nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % items.length;
+ } else if (event.key === 'ArrowUp') {
+ nextIndex = currentIndex <= 0 ? items.length - 1 : currentIndex - 1;
+ }
+ items[nextIndex]?.focus();
+ };
+
+ return {
+ closeMenu,
+ handleMenuKeyDown,
+ handleTriggerKeyDown,
+ menuId,
+ openMenu,
+ toggleMenu,
+ triggerId,
+ };
+}
diff --git a/frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx b/frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx
index c6337fd94d..c9556f0db0 100644
--- a/frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx
+++ b/frontend-modern/src/features/alerts/ResourceMonitoringPolicyAction.tsx
@@ -10,6 +10,7 @@ import {
} from '@/api/resourceOperatorState';
import { notificationStore } from '@/stores/notifications';
import { describeResourceInventoryOwnership } from '@/utils/resourceMonitoringPolicy';
+import { useMenuButton } from '@/components/shared/useMenuButton';
interface ResourceMonitoringPolicyActionProps {
resourceId: string;
@@ -34,6 +35,12 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
const [menuPosition, setMenuPosition] = createSignal({ left: 0, top: 0 });
let triggerRef: HTMLButtonElement | undefined;
let menuRef: HTMLDivElement | undefined;
+ const menuButton = useMenuButton({
+ isOpen: menuOpen,
+ setOpen: setMenuOpen,
+ trigger: () => triggerRef,
+ menu: () => menuRef,
+ });
// The menu renders through a portal with fixed positioning so it can extend
// past the alert card's scroll container: rendered in place, the last card's
@@ -58,7 +65,7 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
if (target instanceof Element && target.closest('[data-monitoring-policy-menu-root]')) {
return;
}
- setMenuOpen(false);
+ menuButton.closeMenu();
};
window.addEventListener('resize', updateMenuPosition);
window.addEventListener('scroll', updateMenuPosition, true);
@@ -126,7 +133,7 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
note: current?.note,
};
await setResourceOperatorState(props.resourceId, input);
- setMenuOpen(false);
+ menuButton.closeMenu(true);
notificationStore.success(`${choice.label} saved for ${props.resourceName}`);
} catch (error) {
notificationStore.error(
@@ -146,11 +153,16 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
<button
type="button"
ref={triggerRef}
+ id={menuButton.triggerId}
+ aria-haspopup="menu"
+ aria-expanded={menuOpen()}
+ aria-controls={menuButton.menuId}
class="inline-flex min-h-9 cursor-pointer items-center rounded-md border border-border bg-surface px-2.5 py-1 text-xs font-medium text-base-content transition-colors hover:bg-surface-hover"
+ onKeyDown={menuButton.handleTriggerKeyDown}
onClick={(event) => {
event.stopPropagation();
updateMenuPosition();
- setMenuOpen((open) => !open);
+ menuButton.toggleMenu();
}}
>
{saving() ? 'Saving…' : 'Monitoring'}
@@ -159,15 +171,17 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
<Portal mount={document.body}>
<div
ref={menuRef}
+ id={menuButton.menuId}
data-monitoring-policy-menu-root
role="menu"
+ aria-labelledby={menuButton.triggerId}
class="fixed z-[9999] w-72 rounded-md border border-border bg-surface p-1.5 shadow-lg"
style={{ left: `${menuPosition().left}px`, top: `${menuPosition().top}px` }}
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
- if (event.key === 'Escape') setMenuOpen(false);
+ menuButton.handleMenuKeyDown(event);
}}
>
<p class="px-2 pb-1.5 text-[11px] text-muted">
@@ -177,6 +191,8 @@ export function ResourceMonitoringPolicyAction(props: ResourceMonitoringPolicyAc
{(choice) => (
<button
type="button"
+ role="menuitem"
+ tabindex="-1"
disabled={saving()}
class="block w-full rounded px-2 py-2 text-left hover:bg-surface-hover disabled:opacity-50"
onClick={() => void applyChoice(choice)}
diff --git a/frontend-modern/src/features/alerts/__tests__/ResourceMonitoringPolicyAction.test.tsx b/frontend-modern/src/features/alerts/__tests__/ResourceMonitoringPolicyAction.test.tsx
index 0b69340087..6a2e6870f9 100644
--- a/frontend-modern/src/features/alerts/__tests__/ResourceMonitoringPolicyAction.test.tsx
+++ b/frontend-modern/src/features/alerts/__tests__/ResourceMonitoringPolicyAction.test.tsx
@@ -72,6 +72,73 @@ describe('ResourceMonitoringPolicyAction', () => {
expect(menu.className).toContain('fixed');
});
+ it('moves keyboard focus through policy choices and returns it on Escape', async () => {
+ operatorStateMock.get.mockResolvedValue(null);
+ render(() => (
+ <ResourceMonitoringPolicyAction
+ resourceId="vm:101"
+ resourceName="legacy-lxc"
+ resourceType="system-container"
+ />
+ ));
+
+ const trigger = screen.getByRole('button', { name: 'Monitoring' });
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });
+ const choices = await screen.findAllByRole('menuitem');
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByRole('menu')).toHaveAccessibleName('Monitoring');
+ await waitFor(() => expect(choices[0]).toHaveFocus());
+
+ fireEvent.keyDown(choices[0], { key: 'ArrowDown' });
+ expect(choices[1]).toHaveFocus();
+ fireEvent.keyDown(choices[1], { key: 'End' });
+ expect(choices.at(-1)).toHaveFocus();
+
+ fireEvent.keyDown(choices.at(-1)!, { key: 'Escape' });
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());
+ expect(trigger).toHaveFocus();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('opens on ArrowUp with the last policy choice focused', async () => {
+ operatorStateMock.get.mockResolvedValue(null);
+ render(() => (
+ <ResourceMonitoringPolicyAction
+ resourceId="vm:101"
+ resourceName="legacy-lxc"
+ resourceType="system-container"
+ />
+ ));
+
+ const trigger = screen.getByRole('button', { name: 'Monitoring' });
+ fireEvent.keyDown(trigger, { key: 'ArrowUp' });
+ const choices = await screen.findAllByRole('menuitem');
+ await waitFor(() => expect(choices.at(-1)).toHaveFocus());
+ });
+
+ it('closes before native Tab navigation leaves the portaled menu', async () => {
+ operatorStateMock.get.mockResolvedValue(null);
+ render(() => (
+ <ResourceMonitoringPolicyAction
+ resourceId="vm:101"
+ resourceName="legacy-lxc"
+ resourceType="system-container"
+ />
+ ));
+
+ const trigger = screen.getByRole('button', { name: 'Monitoring' });
+ fireEvent.click(trigger);
+ const firstChoice = (await screen.findAllByRole('menuitem'))[0];
+ await waitFor(() => expect(firstChoice).toHaveFocus());
+
+ fireEvent.keyDown(firstChoice, { key: 'Tab' });
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ expect(trigger).toHaveFocus();
+ });
+
it('retires provider inventory without changing its previous monitoring mode', async () => {
operatorStateMock.get.mockResolvedValue({
canonicalId: 'vm:101',
diff --git a/frontend-modern/src/features/docker/DockerContainerLifecycleControls.tsx b/frontend-modern/src/features/docker/DockerContainerLifecycleControls.tsx
index e36f742837..ebeddb8219 100644
--- a/frontend-modern/src/features/docker/DockerContainerLifecycleControls.tsx
+++ b/frontend-modern/src/features/docker/DockerContainerLifecycleControls.tsx
@@ -16,6 +16,7 @@ import RotateCwIcon from 'lucide-solid/icons/rotate-cw';
import SquareIcon from 'lucide-solid/icons/square';
import { ResourceActionsAPI } from '@/api/resourceActions';
import { ActionReviewDialog } from '@/features/actions/ActionReviewDialog';
+import { useMenuButton } from '@/components/shared/useMenuButton';
import { notificationStore } from '@/stores/notifications';
import type { ActionDetailResponse } from '@/types/actionAudit';
import type { Resource } from '@/types/resource';
@@ -82,6 +83,13 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
const [menuOpen, setMenuOpen] = createSignal(false);
const [menuPosition, setMenuPosition] = createSignal({ left: 0, top: 0 });
let menuTriggerRef: HTMLButtonElement | undefined;
+ let menuRef: HTMLDivElement | undefined;
+ const menuButton = useMenuButton({
+ isOpen: menuOpen,
+ setOpen: setMenuOpen,
+ trigger: () => menuTriggerRef,
+ menu: () => menuRef,
+ });
const updateMenuPosition = () => {
if (!menuTriggerRef || typeof window === 'undefined') return;
@@ -100,7 +108,7 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
const closeOnOutsidePointer = (event: PointerEvent) => {
const target = event.target;
if (target instanceof Element && target.closest('[data-docker-lifecycle-menu-root]')) return;
- setMenuOpen(false);
+ menuButton.closeMenu();
};
window.addEventListener('resize', updateMenuPosition);
window.addEventListener('scroll', updateMenuPosition, true);
@@ -201,20 +209,22 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
<button
ref={menuTriggerRef}
type="button"
+ id={menuButton.triggerId}
class={`inline-flex h-7 w-7 shrink-0 items-center justify-center rounded border ${enabledButtonClass}`}
title={`Container actions for ${dockerContainerLifecycleName(props.resource)}`}
aria-label={`Container actions for ${dockerContainerLifecycleName(props.resource)}`}
aria-haspopup="menu"
aria-expanded={menuOpen() ? 'true' : 'false'}
+ aria-controls={menuButton.menuId}
onMouseDown={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
- if (event.key === 'Escape') setMenuOpen(false);
+ menuButton.handleTriggerKeyDown(event);
}}
onClick={(event) => {
event.stopPropagation();
updateMenuPosition();
- setMenuOpen((open) => !open);
+ menuButton.toggleMenu();
}}
>
<MoreHorizontalIcon class="h-4 w-4" aria-hidden="true" />
@@ -223,16 +233,19 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
<Show when={menuOpen()}>
<Portal mount={document.body}>
<div
+ ref={menuRef}
+ id={menuButton.menuId}
data-prevent-toggle
data-docker-lifecycle-menu-root
role="menu"
+ aria-labelledby={menuButton.triggerId}
class="fixed z-[9999] w-52 rounded-md border border-border bg-surface p-1 text-left shadow-lg"
style={{ left: `${menuPosition().left}px`, top: `${menuPosition().top}px` }}
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
- if (event.key === 'Escape') setMenuOpen(false);
+ menuButton.handleMenuKeyDown(event);
}}
>
<For each={DOCKER_CONTAINER_LIFECYCLE_ACTIONS}>
@@ -247,6 +260,7 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
<button
type="button"
role="menuitem"
+ tabindex="-1"
class="flex w-full items-center gap-2 rounded px-2 py-2 text-left text-xs font-medium text-base-content transition-colors hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/60 disabled:cursor-not-allowed disabled:opacity-50"
disabled={disabled()}
title={titleForAction(spec.action, spec.label)}
@@ -254,7 +268,7 @@ export const DockerContainerLifecycleControls: Component<DockerContainerLifecycl
data-docker-container-action={spec.action}
onClick={(event) => {
event.stopPropagation();
- setMenuOpen(false);
+ menuButton.closeMenu(true);
void prepareLifecycleReview(spec.action);
}}
>
diff --git a/frontend-modern/src/features/docker/__tests__/DockerNativeTables.test.tsx b/frontend-modern/src/features/docker/__tests__/DockerNativeTables.test.tsx
index 41d5c4a81c..05bc670e31 100644
--- a/frontend-modern/src/features/docker/__tests__/DockerNativeTables.test.tsx
+++ b/frontend-modern/src/features/docker/__tests__/DockerNativeTables.test.tsx
@@ -937,10 +937,30 @@ describe('Docker native tables', () => {
name: 'Container actions for edge-web',
}),
);
+ const lifecycleMenu = screen.getByRole('menu', {
+ name: 'Container actions for edge-web',
+ });
const restartButton = screen.getByRole('menuitem', {
name: 'Review restart for edge-web',
});
- fireEvent.click(restartButton);
+ await waitFor(() =>
+ expect(
+ within(lifecycleMenu).getByRole('menuitem', { name: 'Review stop for edge-web' }),
+ ).toHaveFocus(),
+ );
+ fireEvent.keyDown(restartButton, { key: 'Escape' });
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument());
+ const lifecycleTrigger = screen.getByRole('button', {
+ name: 'Container actions for edge-web',
+ });
+ expect(lifecycleTrigger).toHaveFocus();
+ fireEvent.keyDown(lifecycleTrigger, { key: 'ArrowUp' });
+ await waitFor(() => expect(screen.getAllByRole('menuitem').at(-1)).toHaveFocus());
+ fireEvent.click(
+ screen.getByRole('menuitem', {
+ name: 'Review restart for edge-web',
+ }),
+ );
await waitFor(() =>
expect(ResourceActionsAPI.planAction).toHaveBeenCalledWith(