Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 10 additions & 1 deletion src/DropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ function DropdownMenu(props: DropdownMenuProps) {
onFocus,
onBlur,
onScroll,
textareaRef,
} = React.useContext(MentionsContext);

const { prefixCls, options, opened } = props;
Expand All @@ -34,6 +35,14 @@ function DropdownMenu(props: DropdownMenuProps) {
return;
}

// 只有当焦点恰好位于当前文本区域时,才进行滚动操作。
if (
textareaRef?.current &&
document.activeElement !== textareaRef.current.nativeElement
) {
return;
}

const activeItem = menuRef.current?.findItem?.({ key: activeOption.key });

if (activeItem) {
Expand All @@ -42,7 +51,7 @@ function DropdownMenu(props: DropdownMenuProps) {
inline: 'nearest',
});
}
}, [activeIndex, activeOption.key, opened]);
}, [activeIndex, activeOption.key, opened, textareaRef]);

return (
<Menu
Expand Down
1 change: 1 addition & 0 deletions src/Mentions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,7 @@ const InternalMentions = forwardRef<MentionsRef, InternalMentionsProps>(
onFocus: onDropdownFocus,
onBlur: onDropdownBlur,
onScroll: onInternalPopupScroll,
textareaRef,
}}
>
<KeywordTrigger
Expand Down
2 changes: 2 additions & 0 deletions src/MentionsContext.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* tslint:disable: no-object-literal-type-assertion */
import * as React from 'react';
import type { OptionProps } from './Option';
import { TextAreaRef } from '@rc-component/textarea';

export interface MentionsContextProps {
notFoundContent: React.ReactNode;
Expand All @@ -10,6 +11,7 @@ export interface MentionsContextProps {
onFocus: React.FocusEventHandler<HTMLElement>;
onBlur: React.FocusEventHandler<HTMLElement>;
onScroll: React.UIEventHandler<HTMLElement>;
textareaRef: React.MutableRefObject<TextAreaRef>;
}

// We will never use default, here only to fix TypeScript warning
Expand Down
80 changes: 61 additions & 19 deletions tests/DropdownMenu.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,53 +1,95 @@
import React from 'react';
import { render, act } from '@testing-library/react';
import Mentions, { UnstableContext } from '../src';
import { render, act, fireEvent } from '@testing-library/react';
import Mentions from '../src';
import { simulateInput } from './util';

describe('DropdownMenu', () => {
// Generate 20 options for testing scrolling behavior
const generateOptions = Array.from({ length: 20 }).map((_, index) => ({
value: `item-${index}`,
label: `item-${index}`,
}));

beforeAll(() => {
global.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
});

beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
});

it('should scroll into view when navigating with keyboard', async () => {
// Setup component with UnstableContext for testing dropdown behavior
it('should scroll into view when navigating with keyboard (Focused)', async () => {
const { container } = render(
<UnstableContext.Provider value={{ open: true }}>
<Mentions defaultValue="@" options={generateOptions} />
</UnstableContext.Provider>,
<Mentions defaultValue="" options={generateOptions} />,
);

// Mock scrollIntoView since it's not implemented in JSDOM
const textarea = container.querySelector('textarea');
const scrollIntoViewMock = jest
.spyOn(HTMLElement.prototype, 'scrollIntoView')
.mockImplementation(jest.fn());

// Trigger should not scroll
simulateInput(container, '@');
expect(scrollIntoViewMock).not.toHaveBeenCalled();
await act(async () => {
textarea.focus();

simulateInput(container, '@');

for (let i = 0; i < 10; i++) {
await act(async () => {
jest.advanceTimersByTime(1000);
await Promise.resolve();
});
}
jest.runAllTimers();
});

await act(async () => {
fireEvent.keyDown(textarea, { key: 'ArrowDown', code: 'ArrowDown' });
jest.runAllTimers();
});

// Verify if scrollIntoView was called
expect(scrollIntoViewMock).toHaveBeenCalledWith({
block: 'nearest',
inline: 'nearest',
});

scrollIntoViewMock.mockRestore();
});

it('should NOT scroll into view when input is NOT focused', async () => {
const { container } = render(
<Mentions defaultValue="" options={generateOptions} />,
);

const textarea = container.querySelector('textarea');
const scrollIntoViewMock = jest
.spyOn(HTMLElement.prototype, 'scrollIntoView')
.mockImplementation(jest.fn());

await act(async () => {
textarea.focus();
simulateInput(container, '@');
jest.runAllTimers();
});

scrollIntoViewMock.mockClear();

await act(async () => {
fireEvent.blur(textarea);
jest.runAllTimers();
});

await act(async () => {
const menuItems = document.querySelectorAll('.rc-mentions-menu-item');
if (menuItems.length > 1) {
fireEvent.mouseEnter(menuItems[1]);
jest.runAllTimers();
}
});

expect(scrollIntoViewMock).not.toHaveBeenCalled();

scrollIntoViewMock.mockRestore();
});
});