-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathuseMiddleClickOpenInNewTab.ts
More file actions
72 lines (58 loc) · 1.94 KB
/
useMiddleClickOpenInNewTab.ts
File metadata and controls
72 lines (58 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { useAppSelector } from 'app/store/storeHooks';
import { openImageInNewTab } from 'common/util/openImageInNewTab';
import { selectSystemShouldUseMiddleClickToOpenInNewTab } from 'features/system/store/systemSlice';
import type { RefObject } from 'react';
import { useEffect } from 'react';
type Options = {
requireDirectTarget?: boolean;
};
const shouldHandleMiddleClick = <T extends HTMLElement>(
event: MouseEvent,
element: T,
requireDirectTarget: boolean
) => {
if (event.button !== 1) {
return false;
}
if (requireDirectTarget && event.target !== element) {
return false;
}
return true;
};
export const useMiddleClickOpenInNewTab = <T extends HTMLElement = HTMLElement>(
ref: RefObject<T>,
imageUrl: string,
{ requireDirectTarget = false }: Options = {}
) => {
const shouldUseMiddleClickToOpenInNewTab = useAppSelector(selectSystemShouldUseMiddleClickToOpenInNewTab);
useEffect(() => {
const element = ref.current;
if (!element || !shouldUseMiddleClickToOpenInNewTab) {
return;
}
// If auxclick is unsupported, leave the browser's default middle-click behavior intact.
if (!('onauxclick' in element)) {
return;
}
const onMouseDown = (event: MouseEvent) => {
if (!shouldHandleMiddleClick(event, element, requireDirectTarget)) {
return;
}
event.preventDefault();
};
const onAuxClick = (event: MouseEvent) => {
if (!shouldHandleMiddleClick(event, element, requireDirectTarget)) {
return;
}
event.preventDefault();
event.stopPropagation();
openImageInNewTab(imageUrl);
};
element.addEventListener('mousedown', onMouseDown);
element.addEventListener('auxclick', onAuxClick);
return () => {
element.removeEventListener('mousedown', onMouseDown);
element.removeEventListener('auxclick', onAuxClick);
};
}, [imageUrl, ref, requireDirectTarget, shouldUseMiddleClickToOpenInNewTab]);
};