LibreChat/client/src/components/Nav/NewChat.tsx
Danny Avila 1d9ea7f83f
👐 fix: Open/Close Sidebar Button Animation UX Regression from #10521 (#10694)
Problem:
--------
Commit 5ed1f2991 introduced a layout shift regression when opening the
sidebar. The UI would visibly "jump" as elements shifted right before
the animation completed. Closing the sidebar worked correctly.

Root Cause Analysis:
--------------------
The accessibility PR added a redundant `{navVisible && ...}` conditional
wrapper around the `<nav>` content inside Nav.tsx's `motion.div`. This
caused a race condition:

1. User clicks "Open Sidebar" button
2. `navVisible` state becomes `true`
3. React renders the `motion.div` AND its children simultaneously
4. The inner `{navVisible && (<nav>...)}` renders content at full width
   (320px/260px) BEFORE framer-motion applies `initial={{ width: 0 }}`
5. Brief flash of full-width content causes visible layout shift
6. Animation then starts from width: 0, but damage is done

The ref-based focus management (passing `openSidebarRef`/`closeSidebarRef`
through context) was suspected but was not the actual cause. However,
`requestAnimationFrame` focus calls during animation start could trigger
forced layout calculations, exacerbating the issue.

Solution:
---------
1. Remove redundant conditional rendering in Nav.tsx
   - The outer `{navVisible && (<motion.div>...)}` already controls
     visibility
   - The `overflow-x-hidden` class on motion.div clips content during
     animation
   - Content should always exist inside motion.div for smooth clipping

2. Replace ref-based focus with ID-based focus management
   - Refs passed through component tree can affect React's reconciliation
   - Using `document.getElementById()` decouples focus from render cycle
   - Exported `CLOSE_SIDEBAR_ID` and `OPEN_SIDEBAR_ID` constants for
     consistency

3. Delay focus until after animation completes
   - Changed from `requestAnimationFrame` to `setTimeout(..., 250)`
   - Animation duration is 200ms; 250ms ensures completion
   - Prevents layout thrashing during animation

4. Clean up prop drilling
   - Removed `openSidebarRef`/`closeSidebarRef` from Root.tsx context
   - Simplified Nav.tsx, Header.tsx, NewChat.tsx prop signatures
   - Updated ContextType to remove ref properties

Files Changed:
--------------
- client/src/routes/Root.tsx
- client/src/components/Nav/Nav.tsx
- client/src/components/Nav/NewChat.tsx
- client/src/components/Chat/Header.tsx
- client/src/components/Chat/Menus/OpenSidebar.tsx
- client/src/common/types.ts

Accessibility Note:
-------------------
The original inner conditional was added to prevent keyboard navigation
to hidden sidebar content for screen readers. This is still handled by:
- AnimatePresence unmounting the motion.div after exit animation
- The motion.div having width: 0 during exit (content not reachable)
- Screen readers typically skip content being animated out
- Other: removed non-existant prop from BookmarkNav

Testing:
--------
- Verified smooth animation when opening sidebar (no layout shift)
- Verified smooth animation when closing sidebar (unchanged)
- Verified focus transfers correctly between open/close buttons
- Verified keyboard navigation works as expected
2025-12-04 14:34:46 -05:00

103 lines
3.5 KiB
TypeScript

import React, { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { QueryKeys } from 'librechat-data-provider';
import { useQueryClient } from '@tanstack/react-query';
import { TooltipAnchor, NewChatIcon, MobileSidebar, Sidebar, Button } from '@librechat/client';
import { CLOSE_SIDEBAR_ID, OPEN_SIDEBAR_ID } from '~/components/Chat/Menus/OpenSidebar';
import { useLocalize, useNewConvo } from '~/hooks';
import { clearMessagesCache } from '~/utils';
import store from '~/store';
export default function NewChat({
index = 0,
toggleNav,
subHeaders,
isSmallScreen,
headerButtons,
}: {
index?: number;
toggleNav: () => void;
isSmallScreen?: boolean;
subHeaders?: React.ReactNode;
headerButtons?: React.ReactNode;
}) {
const queryClient = useQueryClient();
/** Note: this component needs an explicit index passed if using more than one */
const { newConversation: newConvo } = useNewConvo(index);
const navigate = useNavigate();
const localize = useLocalize();
const { conversation } = store.useCreateConversationAtom(index);
const handleToggleNav = useCallback(() => {
toggleNav();
// Delay focus until after the sidebar animation completes (200ms)
setTimeout(() => {
document.getElementById(OPEN_SIDEBAR_ID)?.focus();
}, 250);
}, [toggleNav]);
const clickHandler: React.MouseEventHandler<HTMLButtonElement> = useCallback(
(e) => {
if (e.button === 0 && (e.ctrlKey || e.metaKey)) {
window.open('/c/new', '_blank');
return;
}
clearMessagesCache(queryClient, conversation?.conversationId);
queryClient.invalidateQueries([QueryKeys.messages]);
newConvo();
navigate('/c/new', { state: { focusChat: true } });
if (isSmallScreen) {
toggleNav();
}
},
[queryClient, conversation, newConvo, navigate, toggleNav, isSmallScreen],
);
return (
<>
<div className="flex items-center justify-between py-[2px] md:py-2">
<TooltipAnchor
description={localize('com_nav_close_sidebar')}
render={
<Button
id={CLOSE_SIDEBAR_ID}
size="icon"
variant="outline"
data-testid="close-sidebar-button"
aria-label={localize('com_nav_close_sidebar')}
aria-expanded={true}
className="rounded-full border-none bg-transparent p-2 hover:bg-surface-hover md:rounded-xl"
onClick={handleToggleNav}
>
<Sidebar aria-hidden="true" className="max-md:hidden" />
<MobileSidebar
aria-hidden="true"
className="m-1 inline-flex size-10 items-center justify-center md:hidden"
/>
</Button>
}
/>
<div className="flex gap-0.5">
{headerButtons}
<TooltipAnchor
description={localize('com_ui_new_chat')}
render={
<Button
size="icon"
variant="outline"
data-testid="nav-new-chat-button"
aria-label={localize('com_ui_new_chat')}
className="rounded-full border-none bg-transparent p-2 hover:bg-surface-hover md:rounded-xl"
onClick={clickHandler}
>
<NewChatIcon className="icon-lg text-text-primary" />
</Button>
}
/>
</div>
</div>
{subHeaders != null ? subHeaders : null}
</>
);
}