-
-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathcontentScript.ts
More file actions
331 lines (293 loc) · 11.6 KB
/
contentScript.ts
File metadata and controls
331 lines (293 loc) · 11.6 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Web vital metrics calculated by 'web-vitals' npm package to be displayed
// in Web Metrics tab of Reactime app.
import { onTTFB, onLCP, onFID, onFCP, onCLS, onINP } from 'web-vitals';
const MAX_RECONNECT_ATTEMPTS = 5;
const INITIAL_RECONNECT_DELAY = 1000;
const MAX_RECONNECT_DELAY = 16000;
let currentPort = null;
let isAttemptingReconnect = false;
function establishConnection(attemptNumber = 1) {
console.log(`Establishing connection, attempt ${attemptNumber}`);
try {
currentPort = chrome.runtime.connect({ name: 'keepAlivePort' });
console.log('Port created, setting up listeners');
currentPort.onMessage.addListener((msg) => {
console.log('Port received message:', msg);
});
currentPort.onDisconnect.addListener(() => {
const error = chrome.runtime.lastError;
console.log('Port disconnect triggered', error);
// Clear current port
currentPort = null;
// Prevent multiple simultaneous reconnection attempts
if (isAttemptingReconnect) {
console.log('Already attempting to reconnect, skipping');
return;
}
isAttemptingReconnect = true;
// Calculate delay with exponential backoff
const delay = Math.min(
INITIAL_RECONNECT_DELAY * Math.pow(2, attemptNumber - 1),
MAX_RECONNECT_DELAY,
);
if (attemptNumber <= MAX_RECONNECT_ATTEMPTS) {
console.log(
`Will attempt reconnection ${attemptNumber}/${MAX_RECONNECT_ATTEMPTS} in ${delay}ms`,
);
window.postMessage(
{
action: 'portDisconnect',
payload: {
attemptNumber,
maxAttempts: MAX_RECONNECT_ATTEMPTS,
nextRetryDelay: delay,
},
},
'*',
);
setTimeout(() => {
isAttemptingReconnect = false;
establishConnection(attemptNumber + 1);
}, delay);
} else {
console.log('Max reconnection attempts reached');
isAttemptingReconnect = false;
window.postMessage(
{
action: 'portDisconnect',
payload: {
autoReconnectFailed: true,
message: 'Automatic reconnection failed. Please use the reconnect button.',
},
},
'*',
);
}
});
// Send initial test message
currentPort.postMessage({ type: 'connectionTest' });
console.log('Test message sent');
} catch (error) {
console.error('Error establishing connection:', error);
isAttemptingReconnect = false;
// If immediate connection fails, try again
if (attemptNumber <= MAX_RECONNECT_ATTEMPTS) {
const delay = INITIAL_RECONNECT_DELAY;
console.log(`Connection failed immediately, retrying in ${delay}ms`);
setTimeout(() => establishConnection(attemptNumber + 1), delay);
}
}
}
// Initial connection
console.log('Starting initial connection');
establishConnection();
// Reactime application starts off with this file, and will send
// first message to background.js for initial tabs object set up.
// A "tabs object" holds the information of the current tab,
// such as snapshots, performance metrics, title of app, and so on.
let firstMessage = true;
// Listens for window messages (from the injected script on the DOM)
let isRecording = true;
// INCOMING MESSAGE FROM BACKEND (index.ts) TO CONTENT SCRIPT
window.addEventListener('message', (msg) => {
// Event listener runs constantly based on actions
// recorded on the test application from backend files (linkFiber.ts).
// Background.js has a listener that includes switch cases, depending on
// the name of the action (e.g. 'tabReload').
if (firstMessage) {
// One-time request tells the background script that the tab has reloaded.
chrome.runtime.sendMessage({ action: 'tabReload' });
firstMessage = false;
}
// After tabs object has been created from firstMessage, backend (linkFiber.ts)
// will send snapshots of the test app's link fiber tree.
const { action }: { action: string } = msg.data;
if (action === 'recordSnap') {
if (isRecording) {
// add timestamp to payload for the purposes of duplicate screenshot check in backgroundscript -ellie
msg.data.payload.children[0].componentData.timestamp = Date.now();
chrome.runtime.sendMessage(msg.data);
}
}
if (action === 'devToolsInstalled') {
chrome.runtime.sendMessage(msg.data);
}
if (action === 'aReactApp') {
chrome.runtime.sendMessage(msg.data);
}
});
// User input visualization: show click position when time traveling (see docs/USER_INPUT_VISUALIZATION_IMPLEMENTATION.md)
const REACTIME_POINTER_OVERLAY_ID = 'reactime-pointer-overlay';
const REACTIME_POINTER_STYLES_ID = 'reactime-pointer-styles';
const REACTIME_POINTER_VISIBLE_CLASS = 'reactime-pointer-visible';
/** Cached refs to avoid repeated DOM lookups after first use */
let pointerOverlayRef: HTMLElement | null = null;
let pointerDotRef: HTMLElement | null = null;
let pointerRippleRef: HTMLElement | null = null;
const REACTIME_POINTER_STYLES = `
#${REACTIME_POINTER_OVERLAY_ID} {
position: fixed; inset: 0; pointer-events: none; z-index: 2147483647;
}
#${REACTIME_POINTER_OVERLAY_ID} .reactime-pointer-dot {
position: fixed; width: 22px; height: 22px; border-radius: 50%;
background: #0d9488; border: 3px solid #fff;
box-shadow: 0 0 0 1px rgba(0,0,0,0.2), 0 0 20px 4px rgba(13,148,136,0.5);
transform: translate(-50%, -50%);
}
#${REACTIME_POINTER_OVERLAY_ID} .reactime-pointer-ripple {
position: fixed; width: 22px; height: 22px; border-radius: 50%;
border: 3px solid #14b8a6; transform: translate(-50%, -50%); opacity: 0;
}
#${REACTIME_POINTER_OVERLAY_ID}.${REACTIME_POINTER_VISIBLE_CLASS} .reactime-pointer-dot {
animation: reactime-dot-pulse 2s ease-in-out; animation-iteration-count: infinite;
}
#${REACTIME_POINTER_OVERLAY_ID}.${REACTIME_POINTER_VISIBLE_CLASS} .reactime-pointer-ripple {
animation: reactime-ripple 1.2s ease-out; animation-iteration-count: infinite;
}
@keyframes reactime-dot-pulse {
0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: 1; box-shadow: 0 0 0 1px rgba(0,0,0,0.2), 0 0 20px 4px rgba(13,148,136,0.5); }
10% { transform: translate(-50%, -50%) scale(1); opacity: 1; box-shadow: 0 0 0 1px rgba(0,0,0,0.2), 0 0 20px 4px rgba(13,148,136,0.5); }
50% { transform: translate(-50%, -50%) scale(1.2); opacity: 1; box-shadow: 0 0 0 1px rgba(0,0,0,0.2), 0 0 28px 8px rgba(13,148,136,0.7); }
}
@keyframes reactime-ripple {
0% { transform: translate(-50%, -50%) scale(0.6); opacity: 0.7; }
100% { transform: translate(-50%, -50%) scale(3); opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
#${REACTIME_POINTER_OVERLAY_ID}.${REACTIME_POINTER_VISIBLE_CLASS} .reactime-pointer-dot {
animation: reactime-dot-in 0.25s ease-out;
}
#${REACTIME_POINTER_OVERLAY_ID}.${REACTIME_POINTER_VISIBLE_CLASS} .reactime-pointer-ripple {
animation: none; opacity: 0;
}
}
@keyframes reactime-dot-in {
from { transform: translate(-50%, -50%) scale(0); opacity: 0; }
to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}
`;
/**
* Returns the pointer overlay element, creating it (and injecting styles) only on first use.
* Reuses cached refs to avoid repeated DOM lookups.
*/
function getOrCreatePointerOverlay(): HTMLElement {
if (pointerOverlayRef) return pointerOverlayRef;
if (!document.getElementById(REACTIME_POINTER_STYLES_ID)) {
const style = document.createElement('style');
style.id = REACTIME_POINTER_STYLES_ID;
style.textContent = REACTIME_POINTER_STYLES;
(document.head || document.documentElement).appendChild(style);
}
const overlay = document.createElement('div');
overlay.id = REACTIME_POINTER_OVERLAY_ID;
overlay.setAttribute('aria-hidden', 'true');
const ripple = document.createElement('div');
ripple.className = 'reactime-pointer-ripple';
const dot = document.createElement('div');
dot.className = 'reactime-pointer-dot';
overlay.appendChild(ripple);
overlay.appendChild(dot);
overlay.style.display = 'none';
(document.body || document.documentElement).appendChild(overlay);
pointerOverlayRef = overlay;
pointerDotRef = dot;
pointerRippleRef = ripple;
return overlay;
}
/** Payload shape we use for click replay (snapshot may include lastUserEvent from backend). */
interface ClickReplayPayload {
lastUserEvent?: { x: number; y: number } | null;
}
/**
* Shows or hides the click-replay pointer on the page based on snapshot payload.
* Uses cached overlay/dot/ripple refs after first run to avoid repeated DOM queries.
*/
function updateClickReplayPointer(payload: ClickReplayPayload | undefined): void {
const overlay = getOrCreatePointerOverlay();
const dot = pointerDotRef;
const ripple = pointerRippleRef;
if (!dot) return;
const event = payload?.lastUserEvent;
const hasValidEvent =
event != null && typeof event.x === 'number' && typeof event.y === 'number';
if (hasValidEvent) {
const left = `${event.x}px`;
const top = `${event.y}px`;
dot.style.left = left;
dot.style.top = top;
if (ripple) {
ripple.style.left = left;
ripple.style.top = top;
}
overlay.style.display = '';
overlay.classList.remove(REACTIME_POINTER_VISIBLE_CLASS);
requestAnimationFrame(() => {
overlay.classList.add(REACTIME_POINTER_VISIBLE_CLASS);
});
} else {
overlay.classList.remove(REACTIME_POINTER_VISIBLE_CLASS);
overlay.style.display = 'none';
}
}
// FROM BACKGROUND TO CONTENT SCRIPT
// Listening for messages from the UI of the Reactime extension.
chrome.runtime.onMessage.addListener((request) => {
const { action, port }: { action: string; port?: string } = request;
if (action) {
// Message being sent from background.js
// This is toggling the record button on Reactime when clicked
if (action === 'toggleRecord') {
isRecording = !isRecording;
}
// this is only listening for Jump toSnap
if (action === 'jumpToSnap') {
updateClickReplayPointer(request.payload);
chrome.runtime.sendMessage(request);
// After the jumpToSnap action has been sent back to background js,
// it will send the same action to backend files (index.ts) for it execute the jump feature
// '*' == target window origin required for event to be dispatched, '*' = no preference
window.postMessage(request, '*');
}
if (action === 'hideClickReplay') {
updateClickReplayPointer(undefined);
}
if (action === 'portDisconnect' && !currentPort && !isAttemptingReconnect) {
console.log('Received disconnect message, initiating reconnection');
// When we receive a port disconnection message, relay it to the window
window.postMessage(
{
action: 'portDisconnect',
},
'*',
);
// Attempt to re-establish connection
establishConnection();
}
if (action === 'reinitialize') {
window.postMessage(request, '*');
}
return true;
}
});
// Performance metrics being calculated by the 'web-vitals' api and
// sent as an object to background.js.
// To learn more about Chrome web vitals, see https://web.dev/vitals/.
const metrics = {};
const gatherMetrics = ({ name, value }) => {
metrics[name] = value;
chrome.runtime.sendMessage({
type: 'performance:metric',
name,
value,
});
};
// Functions that calculate web metric values.
onTTFB(gatherMetrics);
onLCP(gatherMetrics);
onFID(gatherMetrics);
onFCP(gatherMetrics);
onCLS(gatherMetrics);
onINP(gatherMetrics);
// Send message to background.js for injecting the initial script
// into the app's DOM.
chrome.runtime.sendMessage({ action: 'injectScript' });