fix(menu): open context menus instead of toggling them shut (#1431)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fixes #

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-28 03:51:09 +00:00
commit fc6d0552fc
7 files changed
+186 -19

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix context menus dismissing themselves instead of opening.
@@ -0,0 +1,71 @@
import type { ReactNode } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { MenuAnchor } from '$hooks/useMenuAnchor';
import { SidebarTab } from './SidebarTab';
vi.mock('$components/sidebar', () => ({
SidebarItemLeft: ({ children }: { children: ReactNode }) => <div>{children}</div>,
SidebarItemTooltip: ({ children }: { children: (ref: unknown) => ReactNode }) => children(null),
SidebarUnreadBadge: () => null,
SidebarAvatar: ({ children, ...props }: { children: ReactNode }) => (
<button type="button" {...props}>
{children}
</button>
),
}));
vi.mock('$components/ResponsiveMenu', () => ({
ResponsiveMenu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
const menuAnchorStub = (longPressFired: boolean): MenuAnchor<HTMLButtonElement> => ({
anchor: undefined,
isPressing: false,
close: vi.fn<() => void>(),
openAt: vi.fn<() => void>(),
open: vi.fn<() => void>(),
consumeLongPressFired: () => longPressFired,
triggerProps: {
onClick: vi.fn<() => void>(),
onContextMenu: vi.fn<() => void>(),
onTouchStart: vi.fn<() => void>(),
onTouchEnd: vi.fn<() => void>(),
onTouchMove: vi.fn<() => void>(),
onTouchCancel: vi.fn<() => void>(),
},
});
const renderTab = (longPressFired: boolean, onClick: () => void) =>
render(
<SidebarTab
icon={<span>icon</span>}
selected={false}
tooltip="Home"
onClick={onClick}
menu={<span>menu</span>}
menuAnchor={menuAnchorStub(longPressFired)}
/>
);
describe('SidebarTab', () => {
it('does not navigate on the click that follows a long press', () => {
const onClick = vi.fn<() => void>();
renderTab(true, onClick);
// WKWebView sends no contextmenu on long press, so the release still produces a
// click; acting on it would navigate away from the menu just opened.
fireEvent.click(screen.getByRole('button'));
expect(onClick).not.toHaveBeenCalled();
});
it('navigates on an ordinary click', () => {
const onClick = vi.fn<() => void>();
renderTab(false, onClick);
fireEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalledTimes(1);
});
});
+9 -2
View File
@@ -31,7 +31,14 @@ export function SidebarTab({
unreadCount = 0,
dm = false,
}: SidebarTabProps) {
const { anchor, close, triggerProps } = menuAnchor;
const { anchor, close, triggerProps, consumeLongPressFired } = menuAnchor;
// Platforms that do not fire `contextmenu` on a long press (WKWebView) still send a
// synthetic click on release, which would navigate away from the menu just opened.
const handleClick = () => {
if (consumeLongPressFired()) return;
onClick();
};
return (
<SidebarItemLeft active={selected}>
@@ -48,7 +55,7 @@ export function SidebarTab({
as="button"
ref={triggerRef}
outlined
onClick={onClick}
onClick={handleClick}
onContextMenu={triggerProps.onContextMenu}
onTouchStart={triggerProps.onTouchStart}
onTouchEnd={triggerProps.onTouchEnd}
+3 -14
View File
@@ -266,7 +266,6 @@ type WrappedMessageProps = {
handleSwipeReply?: () => void;
handleSwipeEdit?: () => void;
handleSwipeActionChange?: (mode: SwipeActionMode) => void;
handleContextMenu: MouseEventHandler<HTMLDivElement>;
align?: 'left' | 'right';
};
function WrappedMessage({
@@ -277,7 +276,6 @@ function WrappedMessage({
handleSwipeReply,
handleSwipeEdit,
handleSwipeActionChange,
handleContextMenu,
align,
}: WrappedMessageProps) {
if (messageLayout === undefined) return <>{msgContentJSX}</>;
@@ -289,9 +287,7 @@ function WrappedMessage({
onEdit={handleSwipeEdit}
onActionModeChange={handleSwipeActionChange}
>
<CompactLayout before={headerJSX} onContextMenu={handleContextMenu}>
{msgContentJSX}
</CompactLayout>
<CompactLayout before={headerJSX}>{msgContentJSX}</CompactLayout>
</SwipeableMessageWrapper>
);
if (messageLayout === MessageLayout.Bubble)
@@ -301,12 +297,7 @@ function WrappedMessage({
onEdit={handleSwipeEdit}
onActionModeChange={handleSwipeActionChange}
>
<BubbleLayout
before={avatarJSX}
header={headerJSX}
onContextMenu={handleContextMenu}
align={align}
>
<BubbleLayout before={avatarJSX} header={headerJSX} align={align}>
{msgContentJSX}
</BubbleLayout>
</SwipeableMessageWrapper>
@@ -317,7 +308,7 @@ function WrappedMessage({
onEdit={handleSwipeEdit}
onActionModeChange={handleSwipeActionChange}
>
<ModernLayout before={avatarJSX} onContextMenu={handleContextMenu}>
<ModernLayout before={avatarJSX}>
{headerJSX}
{msgContentJSX}
</ModernLayout>
@@ -880,7 +871,6 @@ function MessageInternal(
avatarJSX={avatarJSX()}
msgContentJSX={msgContentJSX}
messageLayout={messageLayout}
handleContextMenu={() => {}}
align={useRightBubbles && senderId === mx.getUserId() ? 'right' : 'left'}
/>
</div>
@@ -1009,7 +999,6 @@ function MessageInternal(
handleSwipeReply={handleSwipeReply}
handleSwipeEdit={handleSwipeEdit}
handleSwipeActionChange={setSwipeActionMode}
handleContextMenu={contextMenuHandler}
align={useRightBubbles && senderId === mx.getUserId() ? 'right' : 'left'}
/>
</div>
+81
View File
@@ -127,6 +127,23 @@ describe('useMenuAnchor', () => {
});
});
describe('open', () => {
it('moves an already open menu to another element instead of closing it', () => {
const { result } = renderHook(() => useMenuAnchor());
act(() => {
result.current.open(createMockElement({ x: 10 }));
});
expect(result.current.anchor?.x).toBe(10);
// The toggling `openAt` would close here, stranding the caller's new target.
act(() => {
result.current.open(createMockElement({ x: 90 }));
});
expect(result.current.anchor?.x).toBe(90);
});
});
describe('onClick', () => {
it('opens the menu at the clicked element', () => {
const { result } = renderHook(() => useMenuAnchor());
@@ -234,6 +251,70 @@ describe('useMenuAnchor', () => {
expect(result.current.anchor).not.toBeUndefined();
expect(result.current.anchor!.x).toBe(50);
});
it('stays open when the native contextmenu beats the long-press timer', () => {
const { result } = renderHook(() => useMenuAnchor());
const element = createMockElement({ x: 50, y: 100 });
act(() => {
result.current.triggerProps.onTouchStart({
currentTarget: element,
touches: [{ clientX: 50, clientY: 100 } as Touch],
changedTouches: [{ clientX: 50, clientY: 100 } as Touch],
preventDefault: vi.fn<() => void>(),
nativeEvent: new TouchEvent('touchstart'),
} as unknown as React.TouchEvent<HTMLElement>);
});
// The platform's own long press lands just before our timer does.
act(() => {
result.current.triggerProps.onContextMenu({
currentTarget: element,
preventDefault: vi.fn<() => void>(),
stopPropagation: vi.fn<() => void>(),
nativeEvent: { clientX: 120, clientY: 300 } as MouseEvent,
} as unknown as React.MouseEvent<HTMLElement>);
});
expect(result.current.anchor).not.toBeUndefined();
act(() => {
vi.advanceTimersByTime(500);
});
act(() => {
result.current.triggerProps.onTouchEnd();
});
expect(result.current.anchor).not.toBeUndefined();
expect(result.current.anchor!.x).toBe(120);
});
it('cancels a pending custom long press when its contextmenu path consumes the event', () => {
const onLongPress = vi.fn<() => void>();
const { result } = renderHook(() => useMenuAnchor({ onLongPress }));
const element = createMockElement();
act(() => {
result.current.triggerProps.onTouchStart({
currentTarget: element,
touches: [{ clientX: 50, clientY: 100 } as Touch],
changedTouches: [{ clientX: 50, clientY: 100 } as Touch],
preventDefault: vi.fn<() => void>(),
nativeEvent: new TouchEvent('touchstart'),
} as unknown as React.TouchEvent<HTMLElement>);
});
let longPressFired: boolean | undefined;
act(() => {
longPressFired = result.current.consumeLongPressFired();
});
expect(longPressFired).toBe(false);
act(() => {
vi.advanceTimersByTime(500);
});
expect(onLongPress).not.toHaveBeenCalled();
});
});
describe('isPressing', () => {
+14 -2
View File
@@ -18,8 +18,10 @@ export type MenuAnchor<T extends HTMLElement> = {
/** Drives the press-feedback highlight while a long press is in progress. */
isPressing: boolean;
close: () => void;
/** Anchors the menu to an element's box. */
/** Toggles the menu on an element's box. Click semantics: press again to close. */
openAt: (element: HTMLElement) => void;
/** Anchors the menu to an element's box without ever closing it. */
open: (element: HTMLElement) => void;
/** Click, right-click and long-press wiring for the trigger element. */
triggerProps: TriggerProps<T>;
/** True once if a long press just fired, for callers that own their contextmenu handler. */
@@ -49,15 +51,23 @@ export function useMenuAnchor<T extends HTMLElement = HTMLElement>(
setAnchor((current) => (current ? undefined : cords));
}, []);
const open = useCallback((element: HTMLElement) => {
setAnchor(element.getBoundingClientRect());
}, []);
const longPress = useMobileLongPress(() => {
if (onLongPress) {
onLongPress();
return;
}
if (triggerRef.current) openAt(triggerRef.current);
// The platform fires its own contextmenu at roughly this delay, and whichever
// lands first opens the menu. Opening, not toggling: a toggle would shut the
// menu that contextmenu just opened.
if (triggerRef.current) open(triggerRef.current);
});
const consumeLongPressFired = useCallback(() => {
longPress.onTouchCancel();
if (!longPress.firedRef.current) return false;
longPress.firedRef.current = false;
return true;
@@ -79,6 +89,7 @@ export function useMenuAnchor<T extends HTMLElement = HTMLElement>(
const onContextMenu: MouseEventHandler<T> = useCallback(
(evt) => {
evt.preventDefault();
longPress.onTouchCancel();
// The long-press timer already opened it; a synthetic contextmenu would toggle it shut.
if (longPress.firedRef.current) {
longPress.firedRef.current = false;
@@ -105,6 +116,7 @@ export function useMenuAnchor<T extends HTMLElement = HTMLElement>(
consumeLongPressFired,
close,
openAt,
open,
triggerProps: {
onClick,
onContextMenu,
+3 -1
View File
@@ -770,7 +770,9 @@ export function SpaceTabs({ scrollRef }: Readonly<SpaceTabsProps>) {
(evt) => {
evt.preventDefault();
setFolderMenuTarget(folder);
folderMenu.openAt(evt.currentTarget as HTMLElement);
// Opening, not toggling: right-clicking a second folder while the first
// menu is open must move the menu, not close it.
folderMenu.open(evt.currentTarget as HTMLElement);
},
[folderMenu]
);