Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪶 perf: Mount a Sidebar Row's Menu Actions Only Once Its Menu Is Used (#16948)

Marco Berettaf74aa905e13b
diff --git a/client/src/components/Conversations/Convo.tsx b/client/src/components/Conversations/Convo.tsx
index b0de2640bc..e1c9ccdf8d 100644
--- a/client/src/components/Conversations/Convo.tsx
+++ b/client/src/components/Conversations/Convo.tsx
@@ -208,12 +208,11 @@ function Conversation({
* restarted its hover fill from transparent every time the pointer crossed
* the row's edge, which reads as a flicker.
*
- * The cost is what the row's own lifetime is: the chats list unmounts a row
- * as it scrolls out, while the Pinned section mounts every pinned row at
- * once, so there a pointer crossing the list leaves one `ConvoOptions` per
- * row it touched, standing until the section unmounts. That is bounded by
- * the pin count the user chose, and a control that unmounts instead is what
- * this comment's first paragraph describes. */
+ * What stays is the trigger and its menu store. The menu's mutations, route
+ * and chat-context subscriptions mount inside `ConvoOptions` only once the
+ * menu is used, so a pointer sweeping the Pinned section, which mounts every
+ * pinned row at once, leaves a trigger per row it touched rather than a
+ * menu. */
const handleMouseEnter = useCallback(() => {
setHasInteracted(true);
}, []);
diff --git a/client/src/components/Conversations/ConvoActions.tsx b/client/src/components/Conversations/ConvoActions.tsx
index 9909cb0a21..5ff18cb9ad 100644
--- a/client/src/components/Conversations/ConvoActions.tsx
+++ b/client/src/components/Conversations/ConvoActions.tsx
@@ -29,12 +29,12 @@ export type ConvoActionsProps = {
* Owns the row's overflow control: which control is rendered, when it is
* visible, and where focus lives across the swap between them.
*
- * Two controls can represent this menu — `ConvoOptions`, which carries six
- * mutations and its own menu store, and a cheap placeholder that stands in
- * until the menu is wanted. Mounting the real one for every overscanned row is
- * wasteful, but the two must agree about identity, visibility, focus and
- * lifecycle, and splitting those decisions across the row is what made them
- * disagree. They are settled together here:
+ * Two controls can represent this menu: `ConvoOptions`, whose trigger and menu
+ * store mount here while its mutations wait until the menu is used, and a cheap
+ * placeholder that stands in until the menu is wanted. Mounting the real one
+ * for every overscanned row is wasteful, but the two must agree about
+ * identity, visibility, focus and lifecycle, and splitting those decisions
+ * across the row is what made them disagree. They are settled together here:
*
* - **Which.** A pointer device reveals the menu on hover, so hovering is
* enough to mount the real one. Touch has no hover, so the placeholder is
diff --git a/client/src/components/Conversations/ConvoOptions/Controller.tsx b/client/src/components/Conversations/ConvoOptions/Controller.tsx
new file mode 100644
index 0000000000..ee2d60bcda
--- /dev/null
+++ b/client/src/components/Conversations/ConvoOptions/Controller.tsx
@@ -0,0 +1,219 @@
+import { useRef, useCallback, useLayoutEffect } from 'react';
+import { QueryKeys } from 'librechat-data-provider';
+import { useToastContext } from '@librechat/client';
+import { useQueryClient } from '@tanstack/react-query';
+import { useParams, useNavigate } from 'react-router-dom';
+import type { MouseEvent, MutableRefObject } from 'react';
+import type { TMessage } from 'librechat-data-provider';
+import {
+ useDeleteConversationMutation,
+ useArchiveConvoMutation,
+ usePinConversationMutation,
+ useMarkConversationUnreadMutation,
+} from '~/data-provider';
+import { useChatContext, useLiveAnnouncer } from '~/Providers';
+import { useLocalize, useNewConvo } from '~/hooks';
+import { NotificationSeverity } from '~/common';
+
+export type ConvoMenuHandlers = {
+ pin: () => void;
+ markUnread: () => void;
+ archive: (e?: MouseEvent) => void;
+ instantDelete: (e: MouseEvent) => void;
+};
+
+export type ConvoMenuLoading = {
+ pin: boolean;
+ archive: boolean;
+ delete: boolean;
+};
+
+/**
+ * The part of a row's overflow menu that costs something: four mutations, the route, the
+ * chat context and the new-conversation machinery. The menu's trigger stays mounted on every
+ * row the pointer reaches, so it cannot carry these; they mount here only once the menu is
+ * used and publish their handlers through `handlersRef` for the trigger's items to call.
+ */
+function ConvoMenuController({
+ conversationId,
+ isPinned,
+ isArchived,
+ retainView,
+ setIsPopoverActive,
+ handlersRef,
+ onLoadingChange,
+}: {
+ conversationId: string | null;
+ isPinned: boolean;
+ isArchived: boolean;
+ retainView: () => void;
+ setIsPopoverActive: (open: boolean) => void;
+ handlersRef: MutableRefObject<ConvoMenuHandlers | null>;
+ onLoadingChange: (loading: ConvoMenuLoading) => void;
+}) {
+ const localize = useLocalize();
+ const queryClient = useQueryClient();
+ const { setConversation } = useChatContext();
+ const { showToast } = useToastContext();
+ /* Archiving or restoring removes the row from the list that held it, unmounting this
+ menu: the announcement has to come from a live region that outlives the row. */
+ const { announcePolite } = useLiveAnnouncer();
+
+ const navigate = useNavigate();
+ const { conversationId: currentConvoId } = useParams();
+ /* A mutation callback outlives the click that made it: the route it should compare
+ against is whichever chat is open when the request resolves, not the one that was
+ open when the menu item was pressed. */
+ const openConvoIdRef = useRef(currentConvoId);
+ openConvoIdRef.current = currentConvoId;
+ const { newConversation } = useNewConvo();
+
+ const archiveConvoMutation = useArchiveConvoMutation();
+ const pinConvoMutation = usePinConversationMutation();
+ const markUnreadMutation = useMarkConversationUnreadMutation();
+
+ const deleteMutation = useDeleteConversationMutation({
+ onSuccess: () => {
+ if (currentConvoId === conversationId || currentConvoId === 'new') {
+ newConversation();
+ navigate('/c/new', { replace: true });
+ }
+ retainView();
+ showToast({
+ message: localize('com_ui_convo_delete_success'),
+ severity: NotificationSeverity.SUCCESS,
+ showIcon: true,
+ });
+ },
+ onError: () => {
+ showToast({
+ message: localize('com_ui_convo_delete_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ });
+
+ const instantDelete = useCallback(
+ (e: MouseEvent) => {
+ e.stopPropagation();
+ const convoId = conversationId ?? '';
+ if (!convoId) {
+ return;
+ }
+ const messages = queryClient.getQueryData<TMessage[]>([QueryKeys.messages, convoId]);
+ const thread_id = messages?.[messages.length - 1]?.thread_id;
+ const endpoint = messages?.[messages.length - 1]?.endpoint;
+ deleteMutation.mutate({ conversationId: convoId, thread_id, endpoint, source: 'button' });
+ },
+ [conversationId, deleteMutation, queryClient],
+ );
+
+ const archive = useCallback(
+ (e?: MouseEvent) => {
+ e?.stopPropagation();
+ const convoId = conversationId ?? '';
+ if (!convoId) {
+ return;
+ }
+
+ archiveConvoMutation.mutate(
+ { conversationId: convoId, isArchived: !isArchived },
+ {
+ onSuccess: () => {
+ /* The request outlives the row: by the time it resolves the user may have opened
+ another chat, so the open conversation is identified at commit time rather than
+ from the one this callback closed over. */
+ setConversation((prev) =>
+ prev?.conversationId === convoId ? { ...prev, isArchived: !isArchived } : prev,
+ );
+ announcePolite({
+ message: localize(isArchived ? 'com_ui_convo_unarchived' : 'com_ui_convo_archived'),
+ isStatus: true,
+ });
+ const openConvoId = openConvoIdRef.current;
+ if (!isArchived && (openConvoId === convoId || openConvoId === 'new')) {
+ newConversation();
+ navigate('/c/new', { replace: true });
+ }
+ retainView();
+ setIsPopoverActive(false);
+ },
+ onError: () => {
+ showToast({
+ message: localize(isArchived ? 'com_ui_unarchive_error' : 'com_ui_archive_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ },
+ );
+ },
+ [
+ conversationId,
+ isArchived,
+ setConversation,
+ archiveConvoMutation,
+ navigate,
+ newConversation,
+ retainView,
+ setIsPopoverActive,
+ announcePolite,
+ showToast,
+ localize,
+ ],
+ );
+
+ const pin = useCallback(() => {
+ const convoId = conversationId ?? '';
+ if (!convoId) {
+ return;
+ }
+ pinConvoMutation.mutate(
+ { conversationId: convoId, pinned: !isPinned },
+ {
+ onSuccess: () => setIsPopoverActive(false),
+ onError: () => {
+ showToast({
+ message: localize(isPinned ? 'com_ui_unpin_error' : 'com_ui_pin_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ },
+ );
+ }, [conversationId, isPinned, pinConvoMutation, setIsPopoverActive, showToast, localize]);
+
+ const markUnread = useCallback(() => {
+ const convoId = conversationId ?? '';
+ if (!convoId) {
+ return;
+ }
+ markUnreadMutation.mutate(
+ { conversationId: convoId },
+ {
+ onSuccess: () => setIsPopoverActive(false),
+ onError: () => {
+ showToast({
+ message: localize('com_ui_mark_unread_error'),
+ severity: NotificationSeverity.ERROR,
+ showIcon: true,
+ });
+ },
+ },
+ );
+ }, [conversationId, markUnreadMutation, setIsPopoverActive, showToast, localize]);
+
+ handlersRef.current = { pin, markUnread, archive, instantDelete };
+
+ const pinLoading = pinConvoMutation.isLoading;
+ const archiveLoading = archiveConvoMutation.isLoading;
+ const deleteLoading = deleteMutation.isLoading;
+ useLayoutEffect(() => {
+ onLoadingChange({ pin: pinLoading, archive: archiveLoading, delete: deleteLoading });
+ }, [onLoadingChange, pinLoading, archiveLoading, deleteLoading]);
+
+ return null;
+}
+
+export default ConvoMenuController;
diff --git a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
index 2e47df9bf7..310f0da226 100644
--- a/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
+++ b/client/src/components/Conversations/ConvoOptions/ConvoOptions.tsx
@@ -1,24 +1,17 @@
-import { useState, useId, useRef, memo, useCallback, useMemo } from 'react';
+import { useState, useId, useRef, memo, useMemo, useCallback } from 'react';
import * as Ariakit from '@ariakit/react';
-import { QueryKeys } from 'librechat-data-provider';
-import { useQueryClient } from '@tanstack/react-query';
-import { useParams, useNavigate } from 'react-router-dom';
-import { DropdownPopup, Spinner, useToastContext } from '@librechat/client';
+import { DropdownPopup, Spinner } from '@librechat/client';
import { Ellipsis, Archive, ArchiveRestore, Mail, Pen, Pin, Trash } from 'lucide-react';
-import type { TMessage } from 'librechat-data-provider';
import type { MouseEvent } from 'react';
-import {
- useDeleteConversationMutation,
- useArchiveConvoMutation,
- usePinConversationMutation,
- useMarkConversationUnreadMutation,
-} from '~/data-provider';
-import { useChatContext, useLiveAnnouncer } from '~/Providers';
+import type { ConvoMenuHandlers, ConvoMenuLoading } from './Controller';
import useDrawerViewport from '~/hooks/Nav/useDrawerViewport';
-import { useLocalize, useNewConvo } from '~/hooks';
-import { NotificationSeverity } from '~/common';
import { cn, rowActionClasses } from '~/utils';
+import ConvoMenuController from './Controller';
import DeleteButton from './DeleteButton';
+import { useLocalize } from '~/hooks';
+
+const IDLE: ConvoMenuLoading = { pin: false, archive: false, delete: false };
+
/** The overflow menu and the shift-held quick action show the same archive control in two
* sizes, and must never disagree about which direction it moves the conversation. */
function renderArchiveIcon(isLoading: boolean, isArchived: boolean, className: string) {
@@ -64,171 +57,48 @@ function ConvoOptions({
contextMenuPosition?: { x: number; y: number };
}) {
const localize = useLocalize();
- const queryClient = useQueryClient();
const isSmallScreen = useDrawerViewport();
- const { setConversation } = useChatContext();
- const { showToast } = useToastContext();
- /* Archiving or restoring removes the row from the list that held it, unmounting this
- menu: the announcement has to come from a live region that outlives the row. */
- const { announcePolite } = useLiveAnnouncer();
-
- const navigate = useNavigate();
- const { conversationId: currentConvoId } = useParams();
- /* A mutation callback outlives the click that made it: the route it should compare
- against is whichever chat is open when the request resolves, not the one that was
- open when the menu item was pressed. */
- const openConvoIdRef = useRef(currentConvoId);
- openConvoIdRef.current = currentConvoId;
- const { newConversation } = useNewConvo();
const menuId = useId();
const menuButtonRef = useRef<HTMLButtonElement>(null);
const deleteButtonRef = useRef<HTMLButtonElement>(null);
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
- const archiveConvoMutation = useArchiveConvoMutation();
- const pinConvoMutation = usePinConversationMutation();
- const markUnreadMutation = useMarkConversationUnreadMutation();
-
- const deleteMutation = useDeleteConversationMutation({
- onSuccess: () => {
- if (currentConvoId === conversationId || currentConvoId === 'new') {
- newConversation();
- navigate('/c/new', { replace: true });
- }
- retainView();
- showToast({
- message: localize('com_ui_convo_delete_success'),
- severity: NotificationSeverity.SUCCESS,
- showIcon: true,
- });
- },
- onError: () => {
- showToast({
- message: localize('com_ui_convo_delete_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- });
-
- const isArchiveLoading = archiveConvoMutation.isLoading;
- const isPinLoading = pinConvoMutation.isLoading;
- const isDeleteLoading = deleteMutation.isLoading;
+ /* Every row the pointer reaches mounts this trigger and keeps it, so the trigger stays the
+ same element across the row's hover. What the menu does is kept off it until the menu is
+ first used: opened, shift-held for the quick actions, or asked to delete. From then on it
+ stays, because a request it started has to land in the handlers that made it. */
+ const showQuickActions = isShiftHeld && isActiveConvo && !isPopoverActive && !showDeleteDialog;
+ const [armed, setArmed] = useState(false);
+ if (!armed && (isPopoverActive || showDeleteDialog || showQuickActions)) {
+ setArmed(true);
+ }
+ const handlersRef = useRef<ConvoMenuHandlers | null>(null);
+ const [loading, setLoading] = useState<ConvoMenuLoading>(IDLE);
- const deleteHandler = useCallback(() => {
- setShowDeleteDialog(true);
- }, []);
+ const isArchiveLoading = loading.archive;
+ const isPinLoading = loading.pin;
+ const isDeleteLoading = loading.delete;
+ const deleteHandler = useCallback(() => setShowDeleteDialog(true), []);
const handleInstantDelete = useCallback(
- (e: MouseEvent) => {
- e.stopPropagation();
- const convoId = conversationId ?? '';
- if (!convoId) {
- return;
- }
- const messages = queryClient.getQueryData<TMessage[]>([QueryKeys.messages, convoId]);
- const thread_id = messages?.[messages.length - 1]?.thread_id;
- const endpoint = messages?.[messages.length - 1]?.endpoint;
- deleteMutation.mutate({ conversationId: convoId, thread_id, endpoint, source: 'button' });
- },
- [conversationId, deleteMutation, queryClient],
+ (e: MouseEvent) => handlersRef.current?.instantDelete(e),
+ [],
);
-
- const handleArchiveClick = useCallback(
- async (e?: MouseEvent) => {
- e?.stopPropagation();
- const convoId = conversationId ?? '';
- if (!convoId) {
- return;
- }
-
- archiveConvoMutation.mutate(
- { conversationId: convoId, isArchived: !isArchived },
- {
- onSuccess: () => {
- /* The request outlives the row: by the time it resolves the user may have opened
- another chat, so the open conversation is identified at commit time rather than
- from the one this callback closed over. */
- setConversation((prev) =>
- prev?.conversationId === convoId ? { ...prev, isArchived: !isArchived } : prev,
- );
- announcePolite({
- message: localize(isArchived ? 'com_ui_convo_unarchived' : 'com_ui_convo_archived'),
- isStatus: true,
- });
- const openConvoId = openConvoIdRef.current;
- if (!isArchived && (openConvoId === convoId || openConvoId === 'new')) {
- newConversation();
- navigate('/c/new', { replace: true });
- }
- retainView();
- setIsPopoverActive(false);
- },
- onError: () => {
- showToast({
- message: localize(isArchived ? 'com_ui_unarchive_error' : 'com_ui_archive_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- },
- );
- },
- [
- conversationId,
- isArchived,
- setConversation,
- archiveConvoMutation,
- navigate,
- newConversation,
- retainView,
- setIsPopoverActive,
- announcePolite,
- showToast,
- localize,
- ],
- );
-
- const handlePinClick = useCallback(() => {
- const convoId = conversationId ?? '';
- if (!convoId) {
- return;
- }
- pinConvoMutation.mutate(
- { conversationId: convoId, pinned: !isPinned },
- {
- onSuccess: () => setIsPopoverActive(false),
- onError: () => {
- showToast({
- message: localize(isPinned ? 'com_ui_unpin_error' : 'com_ui_pin_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- },
- );
- }, [conversationId, isPinned, pinConvoMutation, setIsPopoverActive, showToast, localize]);
-
- const handleMarkUnreadClick = useCallback(() => {
- const convoId = conversationId ?? '';
- if (!convoId) {
- return;
- }
- markUnreadMutation.mutate(
- { conversationId: convoId },
- {
- onSuccess: () => setIsPopoverActive(false),
- onError: () => {
- showToast({
- message: localize('com_ui_mark_unread_error'),
- severity: NotificationSeverity.ERROR,
- showIcon: true,
- });
- },
- },
- );
- }, [conversationId, markUnreadMutation, setIsPopoverActive, showToast, localize]);
+ const handleArchiveClick = useCallback((e?: MouseEvent) => handlersRef.current?.archive(e), []);
+ const handlePinClick = useCallback(() => handlersRef.current?.pin(), []);
+ const handleMarkUnreadClick = useCallback(() => handlersRef.current?.markUnread(), []);
+ const controller = armed ? (
+ <ConvoMenuController
+ conversationId={conversationId}
+ isPinned={isPinned}
+ isArchived={isArchived}
+ retainView={retainView}
+ setIsPopoverActive={setIsPopoverActive}
+ handlersRef={handlersRef}
+ onLoadingChange={setLoading}
+ />
+ ) : null;
const dropdownItems = useMemo(
() => [
@@ -295,35 +165,41 @@ function ConvoOptions({
visible: isActiveConvo === true || isPopoverActive || isSmallScreen || isGenerating,
});
- if (isShiftHeld && isActiveConvo && !isPopoverActive && !showDeleteDialog) {
+ if (showQuickActions) {
+ /* The controller sits first in a fragment in both branches, so letting go of shift keeps
+ it mounted and a request it started still reaches its callbacks. */
return (
- <div className="flex items-center gap-0.5">
- <button
- aria-label={localize(isArchived ? 'com_ui_unarchive' : 'com_ui_archive')}
- className={buttonClassName}
- onClick={handleArchiveClick}
- disabled={isArchiveLoading}
- >
- {renderArchiveIcon(isArchiveLoading, isArchived, 'icon-md text-text-secondary')}
- </button>
- <button
- aria-label={localize('com_ui_delete')}
- className={buttonClassName}
- onClick={handleInstantDelete}
- disabled={isDeleteLoading}
- >
- {isDeleteLoading ? (
- <Spinner className="size-4" />
- ) : (
- <Trash className="icon-md text-text-secondary" aria-hidden={true} />
- )}
- </button>
- </div>
+ <>
+ {controller}
+ <div className="flex items-center gap-0.5">
+ <button
+ aria-label={localize(isArchived ? 'com_ui_unarchive' : 'com_ui_archive')}
+ className={buttonClassName}
+ onClick={handleArchiveClick}
+ disabled={isArchiveLoading}
+ >
+ {renderArchiveIcon(isArchiveLoading, isArchived, 'icon-md text-text-secondary')}
+ </button>
+ <button
+ aria-label={localize('com_ui_delete')}
+ className={buttonClassName}
+ onClick={handleInstantDelete}
+ disabled={isDeleteLoading}
+ >
+ {isDeleteLoading ? (
+ <Spinner className="size-4" />
+ ) : (
+ <Trash className="icon-md text-text-secondary" aria-hidden={true} />
+ )}
+ </button>
+ </div>
+ </>
);
}
return (
<>
+ {controller}
<DropdownPopup
/**
* Must portal: the row sits inside the nav's `overflow-hidden` and a
diff --git a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
index ee292e0fee..b03c5b3449 100644
--- a/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
+++ b/client/src/components/Conversations/ConvoOptions/__tests__/ConvoOptions.archive.test.tsx
@@ -12,6 +12,7 @@ const mockRetainView = jest.fn();
const mockSetIsPopoverActive = jest.fn();
const mockAnnouncePolite = jest.fn();
const mockSetConversation = jest.fn();
+const mockMutationHook = jest.fn();
jest.mock('@ariakit/react', () => ({
MenuButton: jest
@@ -65,11 +66,23 @@ jest.mock('@librechat/client', () => ({
jest.mock('~/data-provider', () => ({
useDuplicateConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
useAssignConversationToProjectMutation: () => ({ mutate: jest.fn(), isLoading: false }),
- useDeleteConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+ useDeleteConversationMutation: () => {
+ mockMutationHook('delete');
+ return { mutate: jest.fn(), isLoading: false };
+ },
useGetStartupConfig: () => ({ data: { sharedLinksEnabled: false } }),
- useArchiveConvoMutation: () => ({ mutate: mockArchiveMutate, isLoading: false }),
- usePinConversationMutation: () => ({ mutate: jest.fn(), isLoading: false }),
- useMarkConversationUnreadMutation: () => ({ mutate: jest.fn(), isLoading: false }),
+ useArchiveConvoMutation: () => {
+ mockMutationHook('archive');
+ return { mutate: mockArchiveMutate, isLoading: false };
+ },
+ usePinConversationMutation: () => {
+ mockMutationHook('pin');
+ return { mutate: jest.fn(), isLoading: false };
+ },
+ useMarkConversationUnreadMutation: () => {
+ mockMutationHook('markUnread');
+ return { mutate: jest.fn(), isLoading: false };
+ },
}));
jest.mock('~/hooks', () => ({
@@ -117,7 +130,7 @@ const renderOptions = (isArchived: boolean, isActiveConvo = false) => {
isArchived={isArchived}
retainView={mockRetainView}
renameHandler={jest.fn()}
- isPopoverActive={false}
+ isPopoverActive={true}
setIsPopoverActive={mockSetIsPopoverActive}
isActiveConvo={active}
/>
@@ -214,3 +227,67 @@ describe('ConvoOptions archive action', () => {
expect(mockNavigate).not.toHaveBeenCalled();
});
});
+
+describe('ConvoOptions mount cost', () => {
+ const ROWS = 30;
+ const renderRows = (openIndex: number | null) => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const tree = (open: number | null) => (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={['/c/conversation-0']}>
+ <Routes>
+ <Route
+ path="/c/:conversationId"
+ element={
+ <>
+ {Array.from({ length: ROWS }, (_, index) => (
+ <ConvoOptions
+ key={index}
+ conversationId={`conversation-${index}`}
+ title={`Chat ${index}`}
+ retainView={mockRetainView}
+ renameHandler={jest.fn()}
+ isPopoverActive={index === open}
+ setIsPopoverActive={mockSetIsPopoverActive}
+ isActiveConvo={false}
+ />
+ ))}
+ </>
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ const view = render(tree(openIndex));
+ return { open: (index: number | null) => view.rerender(tree(index)) };
+ };
+
+ beforeEach(() => {
+ mockMutationHook.mockReset();
+ });
+
+ /** A Pinned section mounts every row at once, and every row the pointer crossed keeps its
+ * trigger: those triggers must not each carry the menu's mutations and route subscriptions. */
+ it('runs no menu mutations for triggers whose menu was never used', () => {
+ renderRows(null);
+
+ expect(screen.getAllByRole('button', { name: 'com_nav_convo_menu_options' })).toHaveLength(
+ ROWS,
+ );
+ expect(mockMutationHook).not.toHaveBeenCalled();
+ });
+
+ it('mounts the menu actions for the one row whose menu opens, and keeps them after it closes', () => {
+ const rows = renderRows(null);
+
+ act(() => rows.open(4));
+ const hooksWhileOpen = new Set(mockMutationHook.mock.calls.map(([name]) => name));
+ expect(hooksWhileOpen).toEqual(new Set(['delete', 'archive', 'pin', 'markUnread']));
+
+ mockMutationHook.mockReset();
+ act(() => rows.open(null));
+ /* Only the row that was opened renders again, and it keeps its actions mounted. */
+ expect(mockMutationHook).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/e2e/specs/mock/scenarios/pinned-row-menus.spec.ts b/e2e/specs/mock/scenarios/pinned-row-menus.spec.ts
new file mode 100644
index 0000000000..e5b937e202
--- /dev/null
+++ b/e2e/specs/mock/scenarios/pinned-row-menus.spec.ts
@@ -0,0 +1,120 @@
+import { expect, test } from '@playwright/test';
+import type { Locator, Page } from '@playwright/test';
+import type { SeededPin } from './pinned.helpers';
+import {
+ PINNED_REGION,
+ isConversationPinned,
+ removePins,
+ resetPinnedState,
+ seedPinnedConversations,
+} from './pinned.helpers';
+import { NEW_CHAT_PATH } from '../helpers';
+import { openSidebar } from './sidebar';
+
+/**
+ * Every pinned row the pointer crosses keeps its overflow trigger, while the menu's actions
+ * mount only once that menu is used. These check the menu still opens and acts from each
+ * input: a mouse that swept the section first, the keyboard alone, and a touch tap.
+ */
+const MENU_LABEL = 'Conversation Menu Options';
+
+const pinnedRow = (page: Page, title: string): Locator =>
+ page
+ .getByRole('region', { name: PINNED_REGION })
+ .getByTestId('convo-item')
+ .filter({ hasText: title })
+ .filter({ visible: true })
+ .first();
+
+async function seedAndOpen(page: Page, label: string, count: number): Promise<SeededPin[]> {
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ await resetPinnedState(page);
+ const stamp = Date.now();
+ const pins = await seedPinnedConversations(
+ Array.from({ length: count }, (_, index) => `${label} ${stamp} ${index + 1}`),
+ );
+ await page.reload();
+ await openSidebar(page);
+ await expect(pinnedRow(page, pins[0].title)).toBeVisible({ timeout: 15000 });
+ return pins;
+}
+
+async function expectUnpinned(page: Page, pin: SeededPin) {
+ await expect.poll(() => isConversationPinned(pin.conversationId)).toBe(false);
+ await expect(pinnedRow(page, pin.title)).toHaveCount(0);
+}
+
+test.describe('pinned row menus on a pointer device', () => {
+ test.use({ viewport: { width: 1280, height: 900 }, isMobile: false, hasTouch: false });
+
+ test('a pinned row menu opens and acts by mouse after a sweep and by keyboard alone @scenario:pinned-row-menu-mouse-and-keyboard', async ({
+ page,
+ }) => {
+ let pins: SeededPin[] = [];
+ try {
+ pins = await seedAndOpen(page, 'Menu input', 6);
+
+ for (const pin of pins) {
+ await pinnedRow(page, pin.title).hover();
+ }
+ await page.mouse.move(900, 450);
+
+ const mouseRow = pinnedRow(page, pins[1].title);
+ await mouseRow.hover();
+ const mouseTrigger = mouseRow.getByRole('button', { name: MENU_LABEL });
+ await expect(mouseTrigger).toBeVisible();
+ await mouseTrigger.click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect(menu.getByRole('menuitem', { name: 'Unpin' })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(menu).toBeHidden();
+ await expect(mouseTrigger).toBeFocused();
+
+ await page.mouse.move(900, 450);
+ const keyboardRow = pinnedRow(page, pins[3].title);
+ const keyboardTrigger = keyboardRow.getByRole('button', { name: MENU_LABEL });
+ await keyboardRow.getByRole('button', { name: new RegExp(`^${pins[3].title}`) }).focus();
+ for (let step = 0; step < 6; step++) {
+ if (await keyboardTrigger.evaluate((node) => node === document.activeElement)) {
+ break;
+ }
+ await page.keyboard.press('Tab');
+ }
+ await expect(keyboardTrigger).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(menu).toBeVisible();
+ const unpin = menu.getByRole('menuitem', { name: 'Unpin' });
+ await expect(unpin).toBeVisible();
+ await expect(unpin).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expectUnpinned(page, pins[3]);
+ } finally {
+ await removePins(pins);
+ }
+ });
+});
+
+test.describe('pinned row menus on touch', () => {
+ test.use({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
+
+ test('a pinned row menu opens and acts from a tap @scenario:pinned-row-menu-touch', async ({
+ page,
+ }) => {
+ let pins: SeededPin[] = [];
+ try {
+ pins = await seedAndOpen(page, 'Menu touch', 3);
+
+ const row = pinnedRow(page, pins[1].title);
+ const trigger = row.getByRole('button', { name: MENU_LABEL });
+ await expect(trigger).toBeVisible();
+ await trigger.tap();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await menu.getByRole('menuitem', { name: 'Unpin' }).tap();
+ await expectUnpinned(page, pins[1]);
+ } finally {
+ await removePins(pins);
+ }
+ });
+});