-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
966 lines (850 loc) · 29.9 KB
/
Copy pathcontent.js
File metadata and controls
966 lines (850 loc) · 29.9 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
// Content script — injects typing overlay into pages
// ---------- State ----------
let state = {
enabled: false,
active: false,
completed: false,
targetText: "",
currentIndex: 0,
startTime: null,
correctKeystrokes: 0,
totalKeystrokes: 0,
errors: 0,
errorPositions: new Set(),
wpmHistory: [],
timerId: null,
};
// ---------- Overlay Elements ----------
let overlayPanel = null;
let overlayBackdrop = null;
let floatingBtn = null;
let caretUpdateTimer = null;
let lastScrollTarget = null;
let lastCaretLineTop = null;
let lastMeasuredIndex = 0;
let showSelectionButton = true;
let overlayStylesPromise = null;
let overlayCssTextPromise = null;
let themeStyleEl = null;
// ---------- Theme Definitions ----------
const themes = {
dark: {
bg: "#323437",
text: "#d1d0c5",
sub: "#646669",
main: "#e2b714",
caret: "#e2b714",
error: "#ca4754",
},
latte: {
bg: "#f6e6d8",
text: "#454345",
sub: "#826d64",
main: "#7f5539",
caret: "#7f5539",
error: "#e59e80",
},
matcha: {
bg: "#ebf9f0",
text: "#b1d3e0",
sub: "#82cdaa",
main: "#1c2020",
caret: "#1c2020",
error: "#c38080",
},
bingus: {
bg: "#221b4f",
text: "#4e2e7c",
sub: "#6800ff",
main: "#00ffff",
caret: "#00ffff",
error: "#ff5577",
},
carbon: {
bg: "#191919",
text: "#9b9b9b",
sub: "#525252",
main: "#c19549",
caret: "#c19549",
error: "#d04040",
},
dracula: {
bg: "#282a36",
text: "#f8f8f2",
sub: "#6272a4",
main: "#bd93f9",
caret: "#bd93f9",
error: "#ff5555",
},
revo: {
bg: "#214082",
text: "#f6e6d8",
sub: "#826d64",
main: "#d2a8ff",
caret: "#d2a8ff",
error: "#ff8080",
},
honeybee: {
bg: "#f5e050",
text: "#310808",
sub: "#6b441d",
main: "#f7b068",
caret: "#f7b068",
error: "#d14242",
},
};
function darken(hex, amount) {
hex = hex.replace("#", "");
let r = parseInt(hex.substring(0, 2), 16);
let g = parseInt(hex.substring(2, 4), 16);
let b = parseInt(hex.substring(4, 6), 16);
r = Math.max(0, Math.min(255, r - amount));
g = Math.max(0, Math.min(255, g - amount));
b = Math.max(0, Math.min(255, b - amount));
return "#" + [r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("");
}
function lighten(hex, amount) {
hex = hex.replace("#", "");
let r = parseInt(hex.substring(0, 2), 16);
let g = parseInt(hex.substring(2, 4), 16);
let b = parseInt(hex.substring(4, 6), 16);
r = Math.max(0, Math.min(255, r + amount));
g = Math.max(0, Math.min(255, g + amount));
b = Math.max(0, Math.min(255, b + amount));
return "#" + [r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("");
}
function adjustBrightness(hex, amount) {
hex = hex.replace("#", "");
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
const lum = (r * 299 + g * 587 + b * 114) / 1000;
return lum > 128 ? darken(hex, amount) : lighten(hex, amount);
}
function applyThemeVars(themeName) {
const t = themes[themeName];
if (!t) return;
if (!themeStyleEl) {
themeStyleEl = document.createElement("style");
themeStyleEl.id = "typepulse-theme-variables";
(document.head || document.documentElement).appendChild(themeStyleEl);
}
const surface = adjustBrightness(t.bg, 8);
themeStyleEl.textContent = `
#typing-overlay-panel, .overlay-results-modern {
--bg-color: ${t.bg};
--text-color: ${t.text};
--sub-color: ${t.sub};
--main-color: ${t.main};
--caret-color: ${t.caret};
--error-color: ${t.error};
--surface-color: ${surface};
}
/* Apply to floating button directly since it uses !important */
#typepulse-floating-btn {
background: ${t.bg} !important;
color: ${t.main} !important;
border-color: ${t.main} !important;
}
`;
}
// Load saved theme on init
chrome.storage.local.get(["showSelectionButton", "selectedTheme"], (data) => {
showSelectionButton = data.showSelectionButton !== false;
if (!showSelectionButton) hideFloatingButton();
// Apply saved theme immediately
const savedTheme = data.selectedTheme || "dark";
applyThemeVars(savedTheme);
});
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName !== "local") return;
if (changes.showSelectionButton) {
showSelectionButton = changes.showSelectionButton.newValue !== false;
if (!showSelectionButton) hideFloatingButton();
}
if (changes.selectedTheme) {
applyThemeVars(changes.selectedTheme.newValue);
}
});
function ensureOverlayStyles() {
if (overlayStylesPromise) return overlayStylesPromise;
overlayStylesPromise = (async () => {
const existing = document.getElementById("typepulse-overlay-styles");
if (existing) return;
if (!overlayCssTextPromise) {
overlayCssTextPromise = fetch(chrome.runtime.getURL("overlay.css")).then(
(response) => {
if (!response.ok) throw new Error("Failed to fetch overlay styles.");
return response.text();
},
);
}
const cssText = await overlayCssTextPromise;
const style = document.createElement("style");
style.id = "typepulse-overlay-styles";
style.textContent = cssText;
(document.head || document.documentElement).appendChild(style);
})();
return overlayStylesPromise;
}
function createFloatingButton() {
if (floatingBtn) return;
floatingBtn = document.createElement("div");
floatingBtn.id = "typepulse-floating-btn";
floatingBtn.title = "Start Typing with TypePulse";
floatingBtn.innerHTML = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M4 7V4h16v3M9 20h6M12 4v16"/>
</svg>
`;
floatingBtn.addEventListener("mousedown", (e) => {
e.preventDefault();
e.stopPropagation();
});
floatingBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
hideFloatingButton();
createOverlayPanel();
});
document.body.appendChild(floatingBtn);
}
function showFloatingButton(x, y) {
if (!floatingBtn) createFloatingButton();
floatingBtn.style.display = "flex";
floatingBtn.style.left = `${x}px`;
floatingBtn.style.top = `${y}px`;
}
function hideFloatingButton() {
if (floatingBtn) {
floatingBtn.style.display = "none";
}
}
function handleMouseUp(e) {
// Wait a tiny bit for selection to be updated
setTimeout(() => {
if (!showSelectionButton) {
hideFloatingButton();
return;
}
const selection = window.getSelection();
const text = selection.toString().trim();
if (text && text.length > 0) {
if (overlayPanel) return; // Don't show if overlay is already open
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
// Position the button above the selection, centered
const x = rect.left + rect.width / 2 - 22.5 + window.scrollX;
const y = rect.top - 50 + window.scrollY;
ensureOverlayStyles()
.then(() => showFloatingButton(x, y))
.catch(() => hideFloatingButton());
} else {
// If clicking outside the button and no text is selected, hide it
if (
floatingBtn &&
e.target !== floatingBtn &&
!floatingBtn.contains(e.target)
) {
hideFloatingButton();
}
}
}, 10);
}
document.addEventListener("mouseup", handleMouseUp);
window.addEventListener("resize", hideFloatingButton);
document.addEventListener("mousedown", (e) => {
if (
floatingBtn &&
e.target !== floatingBtn &&
!floatingBtn.contains(e.target)
) {
// Optional: could hide on mousedown too, but mouseup handles it
}
});
async function createOverlayPanel(selectionOverride = "") {
showLoadingOverlay();
hideFloatingButton();
// Hide any existing panels
removePanels();
// Get the text the user has highlighted on the page
let selection = selectionOverride || window.getSelection().toString().trim();
if (!selection) {
hideLoadingOverlay();
showToast(
"Please highlight text on the page first, then click the extension icon.",
);
return;
}
try {
await ensureOverlayStyles();
} catch (err) {
hideLoadingOverlay();
showToast("TypePulse could not load its styles on this page.");
return;
}
// Clean up the text: normalize whitespace, remove extra newlines
state.targetText = selection.split(/\s+/).join(" ").replace(/\s+/g, " ");
// Add active class for body blur
document.body.classList.add("typing-overlay-active");
// --- Backdrop ---
overlayBackdrop = document.createElement("div");
overlayBackdrop.id = "typing-overlay-backdrop";
document.body.appendChild(overlayBackdrop);
// --- Main overlay panel ---
overlayPanel = document.createElement("div");
overlayPanel.id = "typing-overlay-panel";
// Block propagation to prevent the page from reacting to clicks
overlayPanel.addEventListener("mousedown", (e) => e.stopPropagation());
overlayPanel.addEventListener("keydown", (e) => e.stopPropagation());
overlayPanel.addEventListener("keyup", (e) => e.stopPropagation());
overlayPanel.addEventListener("keypress", (e) => e.stopPropagation());
overlayPanel.innerHTML = `
<div class="overlay-header-modern">
<div class="overlay-logo">
<svg viewBox="0 0 24 24" width="28" height="28" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3M9 20h6M12 4v16"/></svg>
TypePulse
</div>
<div class="overlay-stats-top" id="overlay-stats-top">
<div class="stat-item"><span class="stat-val" id="stats-time">0</span>s</div>
<div class="stat-item"><span class="stat-val" id="stats-wpm">0</span> wpm</div>
<div class="stat-item"><span class="stat-val" id="stats-accuracy">100</span>% acc</div>
</div>
<div class="overlay-close-modern" id="overlay-close-btn" title="Close">
<svg viewBox="0 0 24 24" width="28" height="28" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</div>
</div>
<div class="overlay-input-wrapper-modern" id="overlay-input-wrapper">
<div class="overlay-text-display-modern" id="overlay-text-display"></div>
<div id="overlay-caret"></div>
</div>
<input class="overlay-hidden-input" id="overlay-textarea" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
<div class="overlay-controls-modern">
<button id="overlay-reset-btn" class="overlay-btn-modern" title="Restart Text">
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>
Restart Text
</button>
</div>
`;
// Append to body
document.body.appendChild(overlayPanel);
// Render the target text into the display
renderTextDisplay();
// --- Bind events on the hidden input ---
const textarea = document.getElementById("overlay-textarea");
textarea.focus();
textarea.addEventListener("input", handleInput);
// Prevent tabbing out
textarea.addEventListener("keydown", (e) => {
if (e.key === "Tab") {
e.preventDefault();
resetSession();
}
});
// Keep focus on the hidden input even if user clicks elsewhere in the overlay
overlayPanel.addEventListener("click", () => {
textarea.focus();
});
overlayBackdrop.addEventListener("click", () => {
finishSession();
});
// Close / reset buttons
document
.getElementById("overlay-close-btn")
.addEventListener("click", finishSession);
document
.getElementById("overlay-reset-btn")
.addEventListener("click", resetSession);
// Capture ALL keyboard events so the underlying page doesn't receive them
window.addEventListener("keydown", captureWindowKeys, true);
// Resize handler to adjust caret position
window.addEventListener("resize", updateCaretPosition);
hideLoadingOverlay();
}
function showLoadingOverlay() {
let loader = document.getElementById("typepulse-loader");
if (loader) return;
loader = document.createElement("div");
loader.id = "typepulse-loader";
loader.innerHTML = `
<div class="tp-loader-spinner"></div>
<div class="tp-loader-text">Loading your test...</div>
`;
document.body.appendChild(loader);
}
function hideLoadingOverlay() {
const loader = document.getElementById("typepulse-loader");
if (loader) {
loader.style.opacity = "0";
setTimeout(() => {
if (loader.parentNode) loader.remove();
}, 300);
}
}
function captureWindowKeys(e) {
if (!overlayPanel) return; // double check
// Do not affect the developer tools or reload
if (
e.key === "F12" ||
(e.metaKey && e.key === "r") ||
(e.ctrlKey && e.key === "r")
)
return;
// If user presses Escape, let it close the modal
if (e.key === "Escape" && e.type === "keydown") {
finishSession();
e.preventDefault();
e.stopPropagation();
return;
}
// To absolutely prevent underlying page from doing things with shortcuts,
// we check if focus is NOT in our textarea, and put it there.
const textarea = document.getElementById("overlay-textarea");
if (document.activeElement !== textarea) {
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
textarea.focus();
}
}
}
function renderTextDisplay() {
const display = document.getElementById("overlay-text-display");
if (!display) return;
let html = "";
let currentSegment = "";
// Keep spaces attached to the preceding word so new lines never start with a space.
for (let i = 0; i < state.targetText.length; i++) {
const char = state.targetText[i];
currentSegment += renderCharSpan(i, char);
if (char === " ") {
if (currentSegment) {
html += `<span class="word">${currentSegment}</span>`;
currentSegment = "";
}
}
}
if (currentSegment) {
html += `<span class="word">${currentSegment}</span>`;
}
// Add a placeholder span at the end for the caret when text is finished
html += `<span id="char-end" style="display:inline-block; width:1px; height:1em;"></span>`;
display.innerHTML = html;
scheduleCaretUpdate();
}
function updateTextDisplayState() {
for (let i = 0; i < state.targetText.length; i++) {
const charEl = document.getElementById(`char-${i}`);
if (!charEl) continue;
const isSpace = state.targetText[i] === " ";
let cls = isSpace ? "char space" : "char";
if (i < state.currentIndex) {
cls += state.errorPositions.has(i) ? " error" : " done";
}
charEl.className = cls;
}
scheduleCaretUpdate();
}
function scheduleCaretUpdate() {
// Wait until layout settles before measuring character positions.
if (caretUpdateTimer) clearTimeout(caretUpdateTimer);
caretUpdateTimer = setTimeout(() => {
caretUpdateTimer = null;
updateCaretPosition();
}, 10);
}
function updateCaretPosition() {
const caret = document.getElementById("overlay-caret");
const display = document.getElementById("overlay-text-display");
if (!caret || !display) return;
const charEl =
document.getElementById(`char-${state.currentIndex}`) ||
document.getElementById("char-end");
if (charEl) {
caret.style.left = charEl.offsetLeft + "px";
// Center the caret vertically relative to the character
const charHeight = charEl.offsetHeight || 32;
caret.style.top =
charEl.offsetTop + (charHeight - caret.offsetHeight) / 2 + "px";
}
if (state.active) {
caret.classList.add("typing");
} else {
caret.classList.remove("typing");
}
// Keep the active line in a stable viewport zone instead of threshold-based bouncing.
if (charEl) {
const wrapper = document.getElementById("overlay-input-wrapper");
if (wrapper) {
syncScrollPosition(wrapper, charEl);
}
}
}
function renderCharSpan(index, ch) {
const isSpace = ch === " ";
let cls = isSpace ? "char space" : "char";
if (index < state.currentIndex) {
cls += state.errorPositions.has(index) ? " error" : " done";
}
const content = isSpace ? " " : escapeHtml(ch);
return `<span class="${cls}" id="char-${index}">${content}</span>`;
}
function syncScrollPosition(wrapper, charEl) {
const currentScrollTop = wrapper.scrollTop;
const currentLineTop = charEl.offsetTop;
const maxScrollTop = Math.max(0, wrapper.scrollHeight - wrapper.clientHeight);
const movingBackward = state.currentIndex < lastMeasuredIndex;
let nextScrollTop = null;
// typing.com-style behavior: when the caret advances onto a new rendered line,
// smoothly scroll so that new line becomes the first visible line.
if (
lastCaretLineTop !== null &&
currentLineTop > lastCaretLineTop &&
currentLineTop > currentScrollTop
) {
nextScrollTop = currentLineTop;
} else if (movingBackward && currentLineTop < currentScrollTop) {
nextScrollTop = currentLineTop;
}
lastCaretLineTop = currentLineTop;
lastMeasuredIndex = state.currentIndex;
if (nextScrollTop === null) return;
nextScrollTop = Math.max(0, Math.min(maxScrollTop, nextScrollTop));
if (
lastScrollTarget !== null &&
Math.abs(lastScrollTarget - nextScrollTop) < 1
)
return;
if (Math.abs(currentScrollTop - nextScrollTop) < 1) {
lastScrollTarget = nextScrollTop;
return;
}
lastScrollTarget = nextScrollTop;
wrapper.scrollTo({ top: nextScrollTop, behavior: "smooth" });
}
function escapeHtml(ch) {
const map = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
return map[ch] || ch;
}
// ---------- Typing Logic ----------
function handleInput(e) {
if (state.completed) return;
if (!state.active) {
state.active = true;
state.startTime = Date.now();
startTimer();
const statsTop = document.getElementById("overlay-stats-top");
if (statsTop) statsTop.classList.add("typing-started");
}
const textarea = e.target;
let typed = textarea.value;
// Prevent input larger than target length
if (typed.length > state.targetText.length) {
typed = typed.substring(0, state.targetText.length);
textarea.value = typed;
}
// Reset: clear errors so far, re-check
state.errorPositions.clear();
state.errors = 0;
state.correctKeystrokes = 0;
state.totalKeystrokes = 0;
for (let i = 0; i < typed.length; i++) {
state.totalKeystrokes++;
if (typed[i] === state.targetText[i]) {
state.correctKeystrokes++;
} else {
state.errors++;
state.errorPositions.add(i);
}
}
state.currentIndex = typed.length;
// Update stats
updateStats();
updateTextDisplayState();
// Check completion: finished whenever typed length matches target
if (typed.length >= state.targetText.length) {
sessionComplete();
}
}
// ---------- Stats ----------
function startTimer() {
if (state.timerId) clearInterval(state.timerId);
state.timerId = setInterval(() => {
if (!state.active) return;
const elapsed = (Date.now() - state.startTime) / 1000;
const timeEl = document.getElementById("stats-time");
if (timeEl) timeEl.textContent = Math.floor(elapsed);
// Live WPM update
const wpm =
state.currentIndex > 0
? Math.round(state.currentIndex / 5 / (elapsed / 60))
: 0;
const wpmEl = document.getElementById("stats-wpm");
if (wpmEl) wpmEl.textContent = wpm;
}, 1000);
}
function updateStats() {
const total = state.totalKeystrokes;
const accuracy =
total > 0 ? Math.round((state.correctKeystrokes / total) * 100) : 100;
const accEl = document.getElementById("stats-accuracy");
if (accEl) accEl.textContent = accuracy;
}
function calculateSessionStats() {
const elapsedMinutes = (Date.now() - state.startTime) / 1000 / 60;
const elapsedSeconds = (Date.now() - state.startTime) / 1000;
// Monkeytype WPM = (chars / 5) / minutes
const wpm =
elapsedMinutes > 0
? Math.round(state.targetText.length / 5 / elapsedMinutes)
: 0;
// Raw WPM = (total keystrokes / 5) / minutes
const rawWpm =
elapsedMinutes > 0
? Math.round(state.totalKeystrokes / 5 / elapsedMinutes)
: 0;
const total = state.totalKeystrokes;
const accuracy =
total > 0 ? Math.round((state.correctKeystrokes / total) * 100) : 100;
return {
wpm,
rawWpm,
accuracy,
errors: state.errors,
characters: state.targetText.length,
totalKeystrokes: total,
time: Math.round(elapsedSeconds),
date: new Date().toISOString(),
text: state.targetText,
url: window.location.href,
sourceTitle: document.title,
};
}
function sessionComplete() {
if (state.completed) return;
state.completed = true;
clearInterval(state.timerId);
state.active = false;
state.timerId = null;
const stats = calculateSessionStats();
// Hide the typing interface
const headerStats = document.getElementById("overlay-stats-top");
if (headerStats) headerStats.classList.add("hidden");
const inputArea = document.getElementById("overlay-input-wrapper");
if (inputArea) inputArea.classList.add("hidden");
const textarea = document.getElementById("overlay-textarea");
if (textarea) textarea.disabled = true;
const controls = document.querySelector(".overlay-controls-modern");
if (controls) controls.classList.add("hidden");
const existingResults = overlayPanel
? overlayPanel.querySelector(".overlay-results-modern")
: null;
if (existingResults) existingResults.remove();
// Create results view
const resultsDiv = document.createElement("div");
resultsDiv.className = "overlay-results-modern";
resultsDiv.innerHTML = `
<div class="results-hero">
<span class="results-kicker">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
Session Complete
</span>
<h2 class="results-title">Typing summary</h2>
</div>
<div class="results-main">
<div class="results-primary">
<div class="result-big-item result-highlight">
<span class="result-big-label">
<svg viewBox="0 0 24 24" width="15" height="15" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M12 13V7"/><path d="M15.4 9.6 12 13l-3.4-3.4"/><path d="M20 17a8 8 0 1 1-16 0"/></svg>
wpm
</span>
<span class="result-big-val">${stats.wpm}</span>
</div>
<div class="result-big-item">
<span class="result-big-label">
<svg viewBox="0 0 24 24" width="15" height="15" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 4 7v5c0 5 3.4 8.4 8 9 4.6-.6 8-4 8-9V7l-8-4Z"/><path d="m9 12 2 2 4-4"/></svg>
acc
</span>
<span class="result-big-val">${stats.accuracy}%</span>
</div>
</div>
<div class="results-grid">
<div class="result-small-item">
<span class="result-small-label">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2 3 14h7l-1 8 10-12h-7l1-8Z"/></svg>
raw
</span>
<span class="result-small-val">${stats.rawWpm}</span>
</div>
<div class="result-small-item">
<span class="result-small-label">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/></svg>
characters
</span>
<span class="result-small-val">${stats.characters}</span>
</div>
<div class="result-small-item">
<span class="result-small-label">
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 7v6l4 2"/></svg>
time
</span>
<span class="result-small-val">${stats.time}s</span>
</div>
</div>
</div>
<div class="results-footer">
<button id="results-restart-btn" class="footer-btn footer-btn-primary" title="Next Test">
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>
<span>Next Test</span>
</button>
<button id="results-close-btn" class="footer-btn" title="Close">
<svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
<span>Close</span>
</button>
</div>
<div class="results-footer-subtle">
<span class="footer-subtle-msg">Like TypePulse?</span>
<a href="https://buymeacoffee.com/WaelFa" target="_blank" rel="noopener" class="footer-subtle-link" title="Support the developer">
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M2 12.5C2 12.5 6 6 12 6c6 0 10 6.5 10 6.5S18 19 12 19c-6 0-10-6.5-10-6.5z" opacity="0.2"/><path d="M18 8.5a5.5 5.5 0 0 0-11 0v1a4 4 0 0 0-3 3.87A4.5 4.5 0 0 0 8.5 18h7a4.5 4.5 0 0 0 4.5-4.63A4 4 0 0 0 18 9.5v-1zM9 8.5a3.5 3.5 0 0 1 7 0v1h-7v-1z"/></svg>
Buy me a coffee
</a>
<span class="footer-subtle-sep">·</span>
<a href="https://chromewebstore.google.com/detail/typepulse/hicbcjkddckijmjlfmgokhjgimifokcn" target="_blank" rel="noopener" class="footer-subtle-link" title="Leave a review">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
Rate & suggest features
</a>
</div>
`;
overlayPanel.appendChild(resultsDiv);
// Bind result buttons
document
.getElementById("results-restart-btn")
.addEventListener("click", () => {
resultsDiv.remove();
headerStats.classList.remove("hidden");
inputArea.classList.remove("hidden");
controls.classList.remove("hidden");
resetSession();
});
document
.getElementById("results-close-btn")
.addEventListener("click", finishSession);
// Save stats
try {
chrome.runtime.sendMessage({ action: "save_stats", stats });
} catch (err) {}
}
function finishSession() {
clearInterval(state.timerId);
removePanels();
resetState();
}
function resetSession() {
clearInterval(state.timerId);
resetState();
resetUI();
const textarea = document.getElementById("overlay-textarea");
if (textarea) textarea.focus();
}
function resetState() {
state.active = false;
state.completed = false;
state.currentIndex = 0;
state.startTime = null;
state.correctKeystrokes = 0;
state.totalKeystrokes = 0;
state.errors = 0;
state.errorPositions.clear();
state.wpmHistory = [];
}
function resetUI() {
const textarea = document.getElementById("overlay-textarea");
if (textarea) {
textarea.value = "";
textarea.disabled = false;
}
const wpmEl = document.getElementById("stats-wpm");
if (wpmEl) wpmEl.textContent = "0";
const accEl = document.getElementById("stats-accuracy");
if (accEl) accEl.textContent = "100";
const timeEl = document.getElementById("stats-time");
if (timeEl) timeEl.textContent = "0";
const statsTop = document.getElementById("overlay-stats-top");
if (statsTop) statsTop.classList.remove("typing-started");
const wrapper = document.getElementById("overlay-input-wrapper");
if (wrapper) wrapper.scrollTop = 0;
lastScrollTarget = null;
lastCaretLineTop = null;
lastMeasuredIndex = 0;
renderTextDisplay();
}
function removePanels() {
if (caretUpdateTimer) {
clearTimeout(caretUpdateTimer);
caretUpdateTimer = null;
}
lastScrollTarget = null;
lastCaretLineTop = null;
lastMeasuredIndex = 0;
if (overlayPanel) {
overlayPanel.remove();
overlayPanel = null;
}
if (overlayBackdrop) {
overlayBackdrop.remove();
overlayBackdrop = null;
}
hideFloatingButton();
document.body.classList.remove("typing-overlay-active");
window.removeEventListener("keydown", captureWindowKeys, true);
window.removeEventListener("resize", updateCaretPosition);
}
// ---------- Toast Notification ----------
function showToast(message) {
let existing = document.getElementById("typing-toast");
if (existing) existing.remove();
const toast = document.createElement("div");
toast.id = "typing-toast";
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
if (toast.parentNode) toast.remove();
}, 3500);
}
// ---------- Message from popup ----------
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "open_overlay") {
createOverlayPanel(message.selectedText || "")
.then(() => sendResponse({ ok: true }))
.catch(() => sendResponse({ ok: false }));
return true;
}
if (message.action === "selection_button_setting_changed") {
showSelectionButton = message.enabled !== false;
if (!showSelectionButton) hideFloatingButton();
sendResponse({ ok: true });
}
if (message.action === "retype_from_history") {
const retypeText = message.text || "";
if (retypeText) {
removePanels();
resetState();
createOverlayPanel(retypeText)
.then(() => sendResponse({ ok: true }))
.catch(() => sendResponse({ ok: false }));
} else {
sendResponse({ ok: false, error: "No text provided" });
}
return true;
}
if (message.action === "apply_theme") {
applyThemeVars(message.theme);
sendResponse({ ok: true });
return true;
}
return true;
});