Skip to content

Commit

Permalink
fix(useTextSelection): keep the selected text range when secondary bu…
Browse files Browse the repository at this point in the history
…tton of mouse is pressed (alibaba#2232)

* fix(bug): useTextSelection bug

* test: add case for the secondary button of mouse

---------

Co-authored-by: liuyib <1656081615@qq.com>
  • Loading branch information
2 people authored and askwuxue committed Jul 29, 2023
1 parent 05b2628 commit e0b2505
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
24 changes: 23 additions & 1 deletion packages/hooks/src/useTextSelection/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ describe('useTextSelection', () => {
});
}

function downMouse(x: number, y: number) {
function downMouse(x: number, y: number, options?: MouseEventInit) {
act(() => {
document.dispatchEvent(
new MouseEvent('mousedown', {
clientX: x,
clientY: y,
screenX: x,
screenY: y,
...options,
}),
);
});
Expand Down Expand Up @@ -92,4 +93,25 @@ describe('useTextSelection', () => {
expect(hook.result.current.text).toBe('on textSelection');
hook.unmount();
});

it('keep/cancel the selected text range', async () => {
initGetSelection({ text: 'aaa' });

const hook = renderHook(() => useTextSelection(() => document));

expect(hook.result.current.text).toBe('');
downMouse(0, 0);
upMouse(100, 100);
expect(hook.result.current.text).toBe('aaa');

// trigger the secondary button of mouse (usually the right button)
downMouse(0, 0, { button: 2 });
expect(hook.result.current.text).toBe('aaa');

// // trigger the main button of mouse (usually the left button)
downMouse(0, 0, { button: 0 });
expect(hook.result.current.text).toBe('');

hook.unmount();
});
});
3 changes: 3 additions & 0 deletions packages/hooks/src/useTextSelection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ function useTextSelection(target?: BasicTarget<Document | Element>): State {

// 任意点击都需要清空之前的 range
const mousedownHandler = (e) => {
// 如果是鼠标右键需要跳过 这样选中的数据就不会被清空
if (e.button === 2) return;

if (!window.getSelection) return;
if (stateRef.current.text) {
setState({ ...initState });
Expand Down

0 comments on commit e0b2505

Please sign in to comment.