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
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,44 @@ describe("ChatsSidebar section switcher", () => {
});
});

describe("ChatsSidebar search dialog", () => {
const SidebarWithSearchState: React.FC = () => {
const [open, setOpen] = useState(false);
return (
<ChatsSidebar
{...defaultProps}
isSearchDialogOpen={open}
onSearchDialogOpenChange={setOpen}
/>
);
};

it("returns focus to the search button when dismissed", async () => {
const user = userEvent.setup();
render(
<Wrapper>
<SidebarWithSearchState />
</Wrapper>,
);

const [searchButton] = screen.getAllByRole("button", {
name: "Search chats",
});
searchButton.focus();
await user.keyboard("{Enter}");
await waitFor(() => {
expect(
screen.getByRole("combobox", { name: "Search chats" }),
).toHaveFocus();
});

await user.keyboard("{Escape}");
await waitFor(() => {
expect(searchButton).toHaveFocus();
});
});
});

describe("ChatsSidebar sections", () => {
it("renders another user's shared chats in Shared with you regardless of pin order", () => {
render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ export const ChatSearchDialog: React.FC<ChatSearchDialogProps> = ({
}) => {
const contentRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
// Radix only restores focus to a Dialog.Trigger, which this dialog lacks.
const returnFocusRef = useRef<{
element: HTMLElement;
pathname: string;
} | null>(null);

return (
<Dialog open={open} onOpenChange={onOpenChange}>
Expand All @@ -121,12 +126,29 @@ export const ChatSearchDialog: React.FC<ChatSearchDialogProps> = ({
// off-screen. Focus the dialog container instead to keep the
// element in the accessibility tree.
onOpenAutoFocus={(event) => {
const previous = document.activeElement;
returnFocusRef.current =
previous instanceof HTMLElement && previous !== document.body
? { element: previous, pathname: window.location.pathname }
: null;
if (focusInputOnOpen) {
return;
}
event.preventDefault();
contentRef.current?.focus({ preventScroll: true });
}}
onCloseAutoFocus={(event) => {
const returnFocus = returnFocusRef.current;
returnFocusRef.current = null;
if (
!returnFocus?.element.isConnected ||
returnFocus.pathname !== window.location.pathname
) {
return;
}
event.preventDefault();
returnFocus.element.focus({ preventScroll: true });
}}
>
<ChatSearchDialogContent
open={open}
Expand Down
Loading