-
-
Notifications
You must be signed in to change notification settings - Fork 421
/
captureClicks.ts
90 lines (73 loc) · 2.18 KB
/
captureClicks.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import xs, {Stream, MemoryStream} from 'xstream';
import {
HistoryInput,
HistoryDriver,
GoBackHistoryInput,
GoForwardHistoryInput,
GoHistoryInput,
PushHistoryInput,
ReplaceHistoryInput,
} from './types';
const CLICK_EVENT = typeof document !== 'undefined' && document.ontouchstart ?
'touchstart' :
'click';
function which(ev: any) {
if (typeof window === 'undefined') {
return false;
}
let e = ev || window.event;
return e.which === null ? e.button : e.which;
}
function sameOrigin(href: string) {
if (typeof window === 'undefined') {
return false;
}
return href && href.indexOf(window.location.origin) === 0;
}
function makeClickListener(push: (p: string) => void) {
return function clickListener(event: MouseEvent) {
if (which(event) !== 1) {
return;
}
if (event.metaKey || event.ctrlKey || event.shiftKey) {
return;
}
if (event.defaultPrevented) {
return;
}
let element: any = event.target;
while (element && element.nodeName !== 'A') {
element = element.parentNode;
}
if (!element || element.nodeName !== 'A') { return; }
if (element.hasAttribute('download') ||
element.getAttribute('rel') === 'external') { return; }
if (element.target) { return; }
const link = element.getAttribute('href');
if (link && link.indexOf('mailto:') > -1 || link.charAt(0) === '#') {
return;
}
if (!sameOrigin(element.href)) {
return;
}
event.preventDefault();
const {pathname, search, hash = ''} = element;
push(pathname + search + hash);
};
}
function captureAnchorClicks(push: (p: string) => void) {
const listener = makeClickListener(push);
if (typeof window !== 'undefined') {
document.addEventListener(CLICK_EVENT, listener, false);
}
}
export function captureClicks(historyDriver: HistoryDriver): HistoryDriver {
return function historyDriverWithClickCapture(sink$: Stream<HistoryInput | string>) {
const internalSink$ = xs.create<HistoryInput | string>();
captureAnchorClicks((pathname: string) => {
internalSink$._n({type: 'push', pathname});
});
sink$._add(internalSink$);
return historyDriver(internalSink$);
};
}