-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdetect-user-interest.ts
More file actions
191 lines (168 loc) · 5.56 KB
/
Copy pathdetect-user-interest.ts
File metadata and controls
191 lines (168 loc) · 5.56 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import { assert } from "../../assert";
import { log as _log } from "../../logging";
import type { UserLinkInteractionEvent } from "../../messaging";
import { Stop, Unbind } from "../../types";
import { browser } from "../../webextension";
const interestInUserEvent = "vaultonomy:interest-in-user";
type InterestInUser = {
interest: "interested" | "disinterested";
dwellTime: number;
username: string;
startTime: number;
};
const userUrlPattern =
/^https:\/\/(?:www|new|old)\.reddit\.com\/u(?:ser)?\/([\w-]{1,20})\/?$/;
const log = _log.getLogger("reddit/ui");
const hoverLog = _log.getLogger(
"reddit/ui/detectInterestInUserFromUserLinkInteraction",
);
/**
* Detect when the user hovers over a link to another Reddit user so that we can
* have the Vaultonomy UI automatically show details of the user in the search
* area.
*/
export default function main(): Unbind {
log.debug("starting");
const toStop: Stop[] = [];
const shutdown = () => {
for (const stop of toStop) stop();
log.debug("stopped");
};
toStop.push(detectInterestInUserFromUserLinkInteraction());
toStop.push(reportInterestInUser({ shutdown }));
return shutdown;
}
function isInterestInUser(obj: unknown): obj is InterestInUser {
return (
typeof obj === "object" &&
!!(obj as Partial<InterestInUser>).username &&
!!(obj as Partial<InterestInUser>).startTime
);
}
function reportInterestInUser({ shutdown }: { shutdown: Stop }): Unbind {
const onInterestInUser = (e: Event) => {
const detail = (e as CustomEvent<unknown>).detail;
assert(isInterestInUser(detail));
try {
browser.runtime.sendMessage({
type: "userLinkInteraction",
interest: detail.interest,
username: detail.username,
startTime: detail.startTime,
dwellTime: detail.dwellTime,
} satisfies UserLinkInteractionEvent);
log.debug(
"Reported interest in user ",
detail.username,
"for",
detail.dwellTime,
"ms",
);
} catch (error) {
if (String(error).includes("Extension context invalidated")) {
log.debug("Stopping due to extension context invalidation");
shutdown();
return;
}
throw error;
}
};
window.addEventListener(interestInUserEvent, onInterestInUser);
return () =>
window.removeEventListener(interestInUserEvent, onInterestInUser);
}
type UserLink = {
startTime: number;
el: HTMLAnchorElement;
username: string;
stop?: (reason: "blur" | "shutdown") => void;
stopped: boolean;
};
function detectInterestInUserFromUserLinkInteraction({
updateInterval = 100,
updateCount = 5,
}: {
updateInterval?: number;
updateCount?: number;
} = {}): Unbind {
let currentUserLink: UserLink | undefined;
function onMouseOver(e: Event): void {
if (!(e.target instanceof HTMLElement)) return;
const containingAnchor = e.target.closest("a[href]");
if (!(containingAnchor instanceof HTMLAnchorElement)) return;
// Entered a new element within an anchor — ignore
if (!currentUserLink?.stopped && containingAnchor === currentUserLink?.el)
return;
const userUrl = userUrlPattern.exec(containingAnchor.href);
if (!userUrl) return;
const username = userUrl[1];
if (currentUserLink) currentUserLink.stop && currentUserLink.stop("blur");
const state: UserLink = (currentUserLink = {
startTime: Date.now(),
el: containingAnchor,
username,
stopped: false,
});
hoverLog.debug("mouse entered link to", username);
let timer: NodeJS.Timeout | undefined = undefined;
let currentUpdateCount = 0;
const notifyInterested = () => {
const dwellTime = Date.now() - state.startTime;
hoverLog.debug(
"mouse remained within link to",
username,
"for",
dwellTime,
"ms",
);
window.dispatchEvent(
new CustomEvent<InterestInUser>(interestInUserEvent, {
detail: {
interest: "interested",
username,
startTime: state.startTime,
dwellTime: Date.now() - state.startTime,
},
}),
);
currentUpdateCount++;
if (currentUpdateCount >= updateCount) clearInterval(timer);
};
// The mouse must remain within the element for a minimum duration.
// Confirm interest after this duration.
timer = setInterval(notifyInterested, updateInterval);
// Cancel without indicating interest if the mouse leaves before the min duration.
// TODO: should we debounce leaves?
const onLeaveAnchor = () => {
state.stop!("blur");
hoverLog.debug(
"mouse left link to",
username,
`after ${Date.now() - state.startTime}ms, ${currentUpdateCount} ${updateInterval}ms interest intervals`,
);
};
containingAnchor.addEventListener("mouseleave", onLeaveAnchor);
state.stop = (reason: "blur" | "shutdown") => {
state.stopped = true;
clearInterval(timer);
containingAnchor.removeEventListener("mouseleave", onLeaveAnchor);
if (currentUpdateCount > 0 && reason !== "shutdown") {
window.dispatchEvent(
new CustomEvent<InterestInUser>(interestInUserEvent, {
detail: {
interest: "disinterested",
username,
startTime: state.startTime,
dwellTime: Date.now() - state.startTime,
},
}),
);
}
};
}
document.addEventListener("mouseover", onMouseOver);
return () => {
document.removeEventListener("mouseover", onMouseOver);
if (currentUserLink?.stop) currentUserLink.stop("shutdown");
};
}