-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1907 lines (1595 loc) · 60.6 KB
/
Copy pathscript.js
File metadata and controls
1907 lines (1595 loc) · 60.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
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
let sentenceIndex = 0;
const savedLeague = localStorage.getItem("speechdeb_league") || "MMSSL";
const guestMode = localStorage.getItem("speechdeb_guest") === "1";
const textBox = document.getElementById("textBox");
const textBoxEl = document.getElementById("textBox");
let windowSpeechData = [];
let isOwnerGlobal = false;
let speechesAlreadyLoaded = false;
window.categorySets = {
MSDL: [
{ name: "Children’s Literature", original: false },
{ name: "Declamation", original: false },
{ name: "Dramatic Performance", original: false },
{ name: "Duo Interpretation", original: false },
{ name: "Group Discussion", original: false },
{ name: "Informative Speaking", original: false },
{ name: "Multiple Reading", original: false },
{ name: "Original Oratory", original: true },
{ name: "Play Reading", original: false },
{ name: "Poetry Reading", original: false },
{ name: "Program Oral Interpretation", original: true },
{ name: "Prose Reading", original: false },
],
MMSSL: [
{ name: "Children’s Literature", original: false },
{ name: "Declamation", original: false },
{ name: "Demonstration", original: false },
{ name: "Dramatic Performance", original: false },
{ name: "Duo Interpretation", original: false },
{ name: "Free Verse/Poetry", original: false },
{ name: "Original Literature", original: true },
{ name: "Original Oratory", original: true },
{ name: "Prose", original: false },
{ name: "Storytelling", original: false }
]
};
window.descriptions = {};
(window.categorySets[savedLeague] || []).forEach(name => {
window.descriptions[name] = name;
});
function isOriginalCategory(categoryName) {
const league = localStorage.getItem("speechdeb_league") || "MMSSL";
const categories = window.categorySets[league] || [];
const cat = categories.find(c => c.name === categoryName);
return cat ? cat.original : false;
}
const payload = localStorage.getItem("speechdeb_editor_payload");
// === Navigation (fixed: real Supabase session instead of email/userId flags) ===
function goBackToMenu() {
try {
localStorage.removeItem("speechdeb_editor_payload");
} catch (e) {
console.warn("Could not clear editor payload:", e);
}
const isGuest = localStorage.getItem("speechdeb_guest") === "1";
if (isGuest) {
window.location.href = "user.html?guest=1";
return;
}
// Supabase tracks the session itself — no need to check email/userId manually
window.location.href = "user.html";
}
function toggleSettings() {
window.location.href = "./settings.html";
}
// Replaces the two duplicate "user.php?action=get&id=..." lookups that used
// to live inline in initScript() and showMenuView().
async function getProfileAndLoadSpeeches() {
const urlParams = new URLSearchParams(window.location.search);
const profileIdParam = urlParams.get("id");
const { data: sessionData } = await supabaseClient.auth.getSession();
const currentUser = sessionData?.session?.user;
if (profileIdParam) {
const { data: profile, error } = await supabaseClient
.from("profiles")
.select("id")
.eq("id", profileIdParam)
.single();
if (error || !profile) {
window.location.href = "404.html";
return;
}
const isOwner = !!(currentUser && profile.id === currentUser.id);
loadSpeechesFromServer(profile.id, isOwner);
} else if (currentUser) {
loadSpeechesFromServer(currentUser.id, true);
} else if (guestMode) {
loadSpeechesFromServer(null, true);
}
}
window.initScript = function initScript() {
const copyLinkBtn = document.getElementById("copyLinkBtn");
if (copyLinkBtn) {
copyLinkBtn.addEventListener("click", () => {
const id = currentSpeechId || "";
if (!id) {
showMessage("⚠️ Save the speech first to get a link.", "warning");
return;
}
const link = `${window.location.origin}/editor.html?speechId=${id}`;
navigator.clipboard.writeText(link)
.then(() => showMessage("✅ Link copied to clipboard!", "success"))
.catch(() => showMessage("❌ Failed to copy link.", "error"));
});
}
const menuBtn = document.getElementById("menuBtn");
if (menuBtn) {
menuBtn.addEventListener("click", goBackToMenu);
}
// Initialize menu view
const menuView = document.getElementById("menuView");
if (menuView) {
getProfileAndLoadSpeeches();
}
// Restore editor if payload exists
const editorView = document.getElementById("editorView");
if (editorView) {
if (!payload) {
createCategorySection(); // ensure it shows up for new speeches too
}
const waitForDOM = () => {
const ready =
document.getElementById("speechTitle") &&
document.getElementById("textBox") &&
document.getElementById("editorView") &&
document.getElementById("editorTopControls"); // ✅ critical
if (!ready) return setTimeout(waitForDOM, 50);
if (!document.getElementById("categorySection") &&
!document.getElementById("categorySelect")) {
createCategorySection(); // <-- ensure always created
}
if (payload) {
const speech = JSON.parse(payload);
loadSpeechIntoEditorServer(speech);
}
};
waitForDOM();
}
// Apply saved user settings
const leagueSelector = document.getElementById("leagueSelector");
if (leagueSelector) {
if (savedLeague) leagueSelector.value = savedLeague;
}
const format = localStorage.getItem("speechdeb_exportFormat") || "txt";
const formatInput = document.querySelector(`input[name="exportFormat"][value="${format}"]`);
if (formatInput) formatInput.checked = true;
const overwrite = localStorage.getItem("speechdeb_overwriteZip") === "true";
const overwriteCheckbox = document.getElementById("overwriteZipCheckbox");
if (overwriteCheckbox) overwriteCheckbox.checked = overwrite;
// Preferences & navigation buttons
const prefsBtn = document.getElementById("prefs");
if (prefsBtn) prefsBtn.addEventListener("click", toggleSettings);
if (menuBtn) menuBtn.addEventListener("click", goBackToMenu);
updateWordCount();
}
function showMessage(text, type = "info", duration = 5000) {
const box = document.getElementById("globalAlert");
if (!box) return;
if (!text || typeof text !== "string") {
text = "⚠️ An unexpected error occurred.";
}
box.innerHTML = text;
box.style.display = "block";
box.style.opacity = "1";
switch (type) {
case "success":
box.style.backgroundColor = "#e6ffe6";
box.style.color = "#006600";
box.style.borderBottom = "3px solid #00aa00";
break;
case "error":
box.style.backgroundColor = "#ffe6e6";
box.style.color = "#990000";
box.style.borderBottom = "3px solid #cc0000";
break;
case "warning":
box.style.backgroundColor = "#fff5e6";
box.style.color = "#995c00";
box.style.borderBottom = "3px solid #cc9900";
break;
default:
box.style.backgroundColor = "#f0f0f0";
box.style.color = "#333";
box.style.borderBottom = "3px solid #ccc";
}
clearTimeout(messageTimeout);
messageTimeout = setTimeout(() => {
box.style.opacity = "0";
setTimeout(() => {
box.style.display = "none";
}, 500);
}, duration);
}
function applyWarningStyles(box, message) {
box.style.cssText = `
display: block;
background-color: #fff5e5;
border: 2px solid #cc0000;
color: #cc0000;
border-radius: 8px;
padding: 12px 20px;
margin-top: 20px;
font-size: 16px;
font-family: inherit;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
max-width: 90%;
margin-inline: auto;
`;
box.innerHTML = message;
}
function applySavedStyles(box, message) {
box.style.cssText = `
display: block;
background-color: #e6ffe6;
border: 2px solid #00aa00;
color: #004400;
border-radius: 8px;
padding: 12px 20px;
margin-top: 20px;
font-size: 16px;
font-family: inherit;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
max-width: 90%;
margin-inline: auto;
`;
box.innerHTML = message;
}
// NOTE: handleSignup(), handleLogin(), toggleAuthMode(), showPasswordReset(),
// showReset(), showAuthView() were removed here — they referenced #loginForm,
// #signupForm, #authBox, #passwordResetForm etc. which don't exist anywhere
// in editor.html. Auth now lives entirely on login.html/signup.html, wired
// to Supabase directly, so this dead code (which posted to register.php /
// login.php) has been deleted rather than converted.
function formatRelativeTime(timestamp) {
const now = Date.now();
const diff = Math.max(0, now - new Date(timestamp).getTime());
const seconds = Math.floor(diff / 1000);
if (seconds < 60) return `${seconds} second${seconds !== 1 ? "s" : ""} ago`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} minute${minutes !== 1 ? "s" : ""} ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} hour${hours !== 1 ? "s" : ""} ago`;
const days = Math.floor(hours / 24);
if (days < 7) return `${days} day${days !== 1 ? "s" : ""} ago`;
const weeks = Math.floor(days / 7);
if (weeks < 4) return `${weeks} week${weeks !== 1 ? "s" : ""} ago`;
const months = Math.floor(weeks / 4);
if (months < 12) return `${months} month${months !== 1 ? "s" : ""} ago`;
const years = Math.floor(months / 12);
return `${years} year${years !== 1 ? "s" : ""} ago`;
}
// === Timer Setup ===
const BASE_TIME_SEC = 450; // 450 = 7:30 in seconds, 150 = 2:30 in seconds (minimum for testing)
const TIME_MULTIPLIER = 1;
// Globals to define (some are unrelated to timer)
let timerInterval = null;
let startTime = BASE_TIME_SEC;
let currentTime = startTime;
let overtime = false;
let startTimestamp = null;
let memorizeMode = false;
let tourIsRunning = false;
let attempts = 0;
let detachedManually = false;
let overtimeStartTimestamp = null;
let resetAttempts = [];
let cooldownTimeout = null;
const flashTimers = {};
let totalElapsedSeconds = 0;
let messageTimeout;
let categoryLocked = false;
let currentSpeechId = null;
let currentSpeechTitle = null;
let currentSpeechCategory = null;
const uploadInput = document.getElementById("uploadFile");
const timerDisplay = document.getElementById("timerDisplay");
const miniTime = document.getElementById("miniTime");
const miniDot = document.getElementById("miniDot");
const stopSummary = document.getElementById("stopSummary");
const lightHighlightToggle = document.getElementById("lightHighlightToggle");
let doneSentences = [];
const settingsBox = document.getElementById("settingsBox");
const markerFlashes = {
150: "label2",
90: "label1",
60: "label30"
};
let timerRunning = false;
let lastUpdate = 0;
const UPDATE_INTERVAL = 100;
let lastSecond = BASE_TIME_SEC;
function formatTime(seconds, omitTenths = false) {
const min = Math.floor(seconds / 60);
const sec = Math.floor(seconds % 60);
const tenths = Math.floor((seconds * 10) % 10);
return omitTenths ? `${pad(min)}:${pad(sec)}` : `${pad(min)}:${pad(sec)}.${tenths}`;
}
function pad(n) {
return n < 10 ? '0' + n : n;
}
const flashedMarkers = {};
function handleFlashes(nowSec, prevSec, elapsedScaled) {
Object.entries(markerFlashes).forEach(([targetStr, id]) => {
const target = Number(targetStr);
if (currentTime <= target && !flashedMarkers[id]) {
startFlash(id, 5000);
flashedMarkers[id] = true;
}
});
const graceEl = document.getElementById("labelOVT");
if (graceEl && currentTime <= 30 && !flashedMarkers["GRACE"]) {
startFlash("labelOVT", 5000);
flashedMarkers["GRACE"] = true;
}
if (graceEl && currentTime <= 0) {
graceEl.textContent = "⚫ OVT";
}
}
function startFlash(id, duration = 5000) {
const el = document.getElementById(id);
if (!el) return;
const originalText = el.textContent.replace(/^[^\w\d]+/, "").trim();
let startTimestamp = performance.now();
let flashing = true;
let flashFrameId = null;
function flashLoop(now) {
if (!flashing) {
el.textContent = "⚫ " + originalText;
miniDot.textContent = "⚫";
cancelAnimationFrame(flashFrameId);
return;
}
const elapsed = now - startTimestamp;
const phase = Math.floor(elapsed / 500) % 2 === 0;
el.textContent = (phase ? "🔴 " : "⚫ ") + originalText;
miniDot.textContent = phase ? "🔴" : "⚫";
flashFrameId = requestAnimationFrame(flashLoop);
}
flashTimers[id] = { stop: () => { flashing = false; } };
flashFrameId = requestAnimationFrame(flashLoop);
setTimeout(() => {
if (flashTimers[id]) {
flashTimers[id].stop();
delete flashTimers[id];
}
}, duration);
}
function stopAllFlashes() {
for (let id in flashTimers) {
if (flashTimers[id]) {
flashTimers[id].stop();
}
const el = document.getElementById(id);
if (el) {
const cleanText = el.textContent.replace(/^[^\w\d]+/, "").trim();
el.textContent = "⚫ " + cleanText;
}
}
Object.keys(flashTimers).forEach(id => delete flashTimers[id]);
miniDot.textContent = "⚫";
const graceEl = document.getElementById("labelOVT");
if (graceEl) {
graceEl.textContent = "⚫ GRACE";
}
}
// === Dropdown & Category Lock ===
const titleInput = document.getElementById("speechTitle");
const menuView = document.getElementById("menuView");
const editorView = document.getElementById("editorView");
let currentSpeechKey = null;
let currentSpeechMetaKey = null;
// === Save & Autosave Logic (rewritten for Supabase) ===
function formatDateTime(date) {
const pad = (n) => (n < 10 ? '0' + n : n);
const mm = pad(date.getMonth() + 1);
const dd = pad(date.getDate());
const yyyy = date.getFullYear();
const hh = pad(date.getHours());
const min = pad(date.getMinutes());
const sec = pad(date.getSeconds());
return `${mm}/${dd}/${yyyy} at ${hh}:${min}:${sec}`;
}
async function saveSpeech() {
const titleEl = document.getElementById("speechTitle");
const contentEl = document.getElementById("textBox");
const categoryEl = document.getElementById("categorySelect");
const shareEl = document.getElementById("shareStatus");
const warningBox = document.getElementById("unsavedWarning");
if (!titleEl || !contentEl || !categoryEl) {
console.error("❌ Missing title, content, or category element.");
return;
}
const title = titleEl.value.trim();
const contentHTML = contentEl.innerHTML.trim();
const plainText = contentHTML.replace(/<[^>]+>/g, "").trim();
const category = categoryEl.value.trim();
const memorized = memorizeMode ? true : false;
const done = doneSentences || [];
const shareStatus = shareEl?.value || "private";
const id = currentSpeechId || null;
if (!title || title.length < 3) {
showMessage("⚠️ Please enter a valid title (min 3 characters).", "warning");
return;
}
if (!category) {
showMessage("⚠️ Please choose a category.", "warning");
return;
}
if (!plainText) {
showMessage("⚠️ Please add some content before saving.", "warning");
return;
}
if (warningBox) applyWarningStyles(warningBox, "💾 Saving...");
// Guest mode never hits the database — save locally instead
if (guestMode) {
saveGuestSpeechLocally({ id, title, content: contentHTML, category, shareStatus });
updateLastSaved();
return;
}
const { data: sessionData } = await supabaseClient.auth.getSession();
const currentUser = sessionData?.session?.user;
if (!currentUser) {
showMessage("❌ You must be logged in to save.", "error");
return;
}
const dbPayload = {
user_id: currentUser.id,
title,
content: contentHTML,
category,
memorization_mode: memorized,
done_sentences: done,
share_status: shareStatus,
updated_at: new Date().toISOString()
};
let result;
if (id) {
result = await supabaseClient
.from("speeches")
.update(dbPayload)
.eq("id", id)
.eq("user_id", currentUser.id)
.select()
.single();
} else {
result = await supabaseClient
.from("speeches")
.insert({ ...dbPayload, created_at: new Date().toISOString() })
.select()
.single();
}
const { data, error } = result;
if (error) {
console.error("❌ Save failed:", error);
showMessage("❌ Could not save: " + error.message, "error");
return;
}
currentSpeechId = data.id;
updateLastSaved();
const shareInput = document.getElementById("shareStatus");
const shareDropdown = document.getElementById("shareDropdown");
if (shareInput && shareDropdown) {
shareDropdown.value = shareInput.value;
}
}
// Minimal guest-mode save: updates the same localStorage array user.html reads from
function saveGuestSpeechLocally({ id, title, content, category, shareStatus }) {
const GUEST_STORAGE_KEY = "speechdeb_guest_speeches";
let speeches = [];
try {
speeches = JSON.parse(localStorage.getItem(GUEST_STORAGE_KEY) || "[]");
} catch (e) {
speeches = [];
}
const now = new Date().toISOString();
const existingIndex = speeches.findIndex(s => s.id === id);
if (existingIndex >= 0) {
speeches[existingIndex] = { ...speeches[existingIndex], title, content, category, share_status: shareStatus, updated_at: now };
currentSpeechId = id;
} else {
const newId = id || Date.now();
speeches.push({ id: newId, title, content, category, share_status: shareStatus, created_at: now, updated_at: now });
currentSpeechId = newId;
}
localStorage.setItem(GUEST_STORAGE_KEY, JSON.stringify(speeches));
}
let lastSavedMessage = "";
let warningActive = false;
let warningTimeout = null;
const categorySelect = document.getElementById("categorySelect");
function updateLastSaved() {
const now = new Date();
const titleInputEl = document.getElementById("speechTitle");
const categorySelect = document.getElementById("categorySelect");
const box = document.getElementById("unsavedWarning");
const title = titleInputEl ? titleInputEl.value.trim() : "";
const category = categorySelect ? categorySelect.value.trim() : "";
const content = textBoxEl ? textBoxEl.innerText.trim() : "";
const allPresent = title.length > 0 && category.length > 0 && content.length > 0;
if (!box) return;
if (!allPresent) {
warningActive = true;
applyWarningStyles(box, "⚠️ Your speech is not saving! Category, title, and/or content are absent.");
} else {
warningActive = false;
lastSavedMessage = `✅ Last saved at ${formatDateTime(now)}`;
applySavedStyles(box, lastSavedMessage);
}
}
// === Download Handlers ===
function downloadText() {
const text = textBox.innerText;
const blob = new Blob([text], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "speech.txt";
a.click();
URL.revokeObjectURL(url);
}
function generatePDFBufferFromText(text) {
const { jsPDF } = window.jspdf;
const pdf = new jsPDF();
const marginLeft = 10;
const marginTop = 10;
const lineHeight = 10;
const pageHeight = pdf.internal.pageSize.height;
const maxY = pageHeight - marginTop;
let y = marginTop;
const paragraphs = text.split(/\n{2,}/);
paragraphs.forEach((para) => {
const lines = pdf.splitTextToSize(para.trim(), 180);
lines.forEach((line) => {
if (y + lineHeight > maxY) {
pdf.addPage();
y = marginTop;
}
pdf.text(line, marginLeft, y);
y += lineHeight;
});
y += lineHeight * 1.5;
});
return pdf.output("arraybuffer");
}
function downloadPDF() {
const rawText = textBox.innerText || "";
const cleanedText = rawText.replace(/\r?\n/g, "\n");
const title = titleInput.value.trim().replace(/[^\w\s-]/g, "").replace(/\s+/g, "_") || "speech";
const pdfBuffer = generatePDFBufferFromText(cleanedText);
const blob = new Blob([pdfBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${title}.pdf`;
a.click();
URL.revokeObjectURL(url);
}
// === Word Count and Timing Stats ===
function updateWordCount() {
if (!textBox) return;
const text = textBox.textContent || "";
const words = text.trim().split(/\s+/).filter(word => word.length > 0);
const wordCountEl = document.getElementById("wordCount");
if (wordCountEl) {
wordCountEl.textContent = words.length;
}
updateTimingStats(totalElapsedSeconds || 0);
}
function updateTimingStats(totalSeconds) {
const text = textBox.innerText || "";
const words = text.trim().split(/\s+/).filter(word => word.length > 0).length;
const wpm = words > 0 && totalSeconds > 0 ? (words / (totalSeconds / 60)).toFixed(1) : "0.0";
const spw = words > 0 && totalSeconds > 0 ? (totalSeconds / words).toFixed(2) : "–";
const wpmValue = document.getElementById("wpmValue");
const spwValue = document.getElementById("spwValue");
if (wpmValue) wpmValue.textContent = wpm;
if (spwValue) spwValue.textContent = spw;
if (!timerRunning || totalSeconds <= 0) return;
const maxWPM = 300;
const cappedWPM = Math.min(maxWPM, parseFloat(wpm));
const wpmNeedle = document.getElementById("wpmNeedle");
const wpmAngle = 225 - (cappedWPM / maxWPM) * 270;
if (wpmNeedle && !isNaN(wpmAngle)) {
wpmNeedle.style.transform = `rotate(${wpmAngle}deg)`;
}
const maxSPW = 5;
const cappedSPW = spw === "–" ? 0 : Math.min(maxSPW, parseFloat(spw));
const spwNeedle = document.getElementById("spwNeedle");
const spwAngle = 225 - (cappedSPW / maxSPW) * 270;
if (spwNeedle && !isNaN(spwAngle)) {
spwNeedle.style.transform = `rotate(${spwAngle}deg)`;
}
const odometer = document.getElementById("odometer");
if (odometer) {
odometer.innerHTML = words
.toString()
.padStart(4, "0")
.split("")
.map(d => `
<div class="odometer-digit">
<div class="odometer-wheel" style="transform: translateY(-${parseInt(d) * 30}px);">
${[...Array(10).keys()].map(n => `<div>${n}</div>`).join("")}
</div>
</div>
`)
.join("");
}
}
function updateOdometer(value) {
const odometer = document.getElementById("odometer");
if (!odometer) return;
const digits = value.toString().padStart(4, "0").split("");
odometer.innerHTML = digits.map(d => `
<div class="odometer-digit">
<div class="odometer-wheel">
${[...Array(10).keys()].map(n => `<div>${n}</div>`).join("")}
</div>
</div>
`).join("");
const wheels = odometer.querySelectorAll(".odometer-wheel");
digits.forEach((d, i) => {
wheels[i].style.transform = `translateY(-${parseInt(d) * 10}%)`;
});
}
// === Input Event Handlers ===
let saveTimeout;
if (textBox) {
textBox.addEventListener("input", () => {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(saveSpeech, 500);
updateWordCount();
});
textBox.addEventListener("paste", () => {
setTimeout(updateWordCount, 50);
});
textBox.addEventListener("blur", updateWordCount);
}
if (titleInput) {
titleInput.addEventListener("input", () => {
document.title = titleInput.value || "Untitled Speech";
updateLastSaved();
});
titleInput.addEventListener("input", () => {
warningActive = false;
updateLastSaved();
});
}
if (titleInput) {
titleInput.addEventListener("blur", saveSpeech);
}
const liveDropdown = document.getElementById("categorySelect");
if (liveDropdown) {
liveDropdown.addEventListener("blur", saveSpeech);
liveDropdown.addEventListener("change", () => {
saveSpeech();
updateLastSaved();
});
}
// === Load on Startup ===
const onEditorPage = !!document.getElementById("editorView");
const onMenuPage = location.pathname.includes("index.html") || location.pathname.includes("user.html");
if (onEditorPage) {
updateWordCount();
}
// === Memorization Mode ===
memorizeMode = false;
let sentences = [];
let originalEditorHTML = "";
function splitTextIntoSentencePieces(text) {
const pieces = [];
const regex = /([^.!?]*[.!?]["')\]]*\s*|[^.!?]+$)/g;
let match;
while ((match = regex.exec(text)) !== null) {
const part = match[0];
if (part && part.trim().length > 0) {
pieces.push(part);
}
}
return pieces.length ? pieces : [text];
}
let sentenceSpans = [];
function buildMemorizeViewFromOriginalHTML() {
if (!originalEditorHTML) {
originalEditorHTML = textBox.innerHTML || "";
}
const temp = document.createElement("div");
temp.innerHTML = originalEditorHTML;
sentenceSpans = [];
let indexCounter = 0;
function processNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const raw = node.textContent;
if (!raw || !raw.trim()) return;
const parts = splitTextIntoSentencePieces(raw);
if (parts.length === 1) return;
const frag = document.createDocumentFragment();
parts.forEach(part => {
if (!part) return;
const span = document.createElement("span");
span.textContent = part;
span.className = "mem-sentence";
span.dataset.index = indexCounter;
sentenceSpans.push(span);
indexCounter++;
frag.appendChild(span);
});
node.parentNode.replaceChild(frag, node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
Array.from(node.childNodes).forEach(processNode);
}
}
Array.from(temp.childNodes).forEach(processNode);
textBox.innerHTML = temp.innerHTML;
sentences = sentenceSpans.map(span => span.textContent.trim()).filter(Boolean);
}
const memorizeBtn = document.getElementById("memorizeBtn");
const toggleVisibilityBtn = document.getElementById("toggleVisibilityBtn");
const prevBtn = document.getElementById("prevSentenceBtn");
const nextBtn = document.getElementById("nextSentenceBtn");
if (memorizeBtn && titleInput && textBox) {
memorizeBtn.addEventListener("click", () => {
const memNav = document.getElementById("memNav");
const formatControls = document.getElementById("formatControls");
const uploadFile = document.getElementById("uploadFile");
const categorySection = document.getElementById("categorySection");
const statsBox = document.getElementById("statsBox");
if (!memorizeMode) {
originalEditorHTML = textBox.innerHTML || "";
memorizeMode = true;
titleInput.disabled = true;
textBox.contentEditable = false;
buildMemorizeViewFromOriginalHTML();
prepareSentences();
sentenceIndex = 0;
highlightSentence();
updateSentenceCounter();
if (memNav) memNav.style.display = "flex";
if (formatControls) formatControls.style.display = "none";
if (uploadFile) uploadFile.style.display = "none";
if (categorySection) categorySection.style.display = "none";
if (statsBox) statsBox.style.display = "none";
memorizeBtn.textContent = "Unmemorize";
memorizeBtn.classList.add("active");
} else {
memorizeMode = false;
titleInput.disabled = false;
textBox.contentEditable = true;
if (originalEditorHTML) {
textBox.innerHTML = originalEditorHTML;
}
sentenceSpans = [];
sentences = [];
sentenceIndex = 0;
if (memNav) memNav.style.display = "none";
if (formatControls) formatControls.style.display = "flex";
if (uploadFile) uploadFile.style.display = "inline-block";
if (categorySection) categorySection.style.display = "block";
if (statsBox) statsBox.style.display = "block";
memorizeBtn.textContent = "Memorize";
memorizeBtn.classList.remove("active");
updateWordCount();
updateSentenceCounter();
updateDonePercentage();
}
updateLastSaved();
saveSpeech();
});
}
// === Sentence Parsing & Highlighting ===
function prepareSentences() {
if (!memorizeMode) return;
if (!sentenceSpans || sentenceSpans.length === 0) {
buildMemorizeViewFromOriginalHTML();
}
sentences = (sentenceSpans || [])
.map(span => span.textContent.trim())
.filter(Boolean);
if (sentenceIndex >= sentences.length) {
sentenceIndex = 0;
}
}
function highlightSentence() {
if (!memorizeMode) return;
if (!sentenceSpans || sentenceSpans.length === 0) return;
const isHidden = toggleVisibilityBtn?.dataset.hidden === "true";
sentenceSpans.forEach((span, idx) => {
const isCurrent = idx === sentenceIndex;
const isDone = doneSentences.includes(idx);
const shouldHighlight = isCurrent || isDone;
span.style.backgroundColor = shouldHighlight ? "yellow" : "inherit";
span.style.fontWeight = isCurrent ? "bold" : "normal";
span.style.opacity = (isHidden && isCurrent) ? "0" : "1";
span.style.transition = "opacity 0.3s ease";
span.style.borderRadius = "3px";
span.style.padding = shouldHighlight ? "0.05em 0.1em" : "0";
});
syncDoneCheckbox();
updateDonePercentage();
}
function updateSentenceCounter() {
const counterEl = document.getElementById("sentenceCounter");
if (!sentences || sentences.length === 0) {
counterEl.textContent = "";
return;
}
counterEl.textContent = `Sentence ${sentenceIndex + 1} of ${sentences.length}`;
}
// === Navigation Buttons ===
toggleVisibilityBtn?.addEventListener("click", () => {
const isHidden = toggleVisibilityBtn.dataset.hidden === "true";
toggleVisibilityBtn.dataset.hidden = isHidden ? "false" : "true";
toggleVisibilityBtn.textContent = isHidden ? "Hide" : "Show";
toggleVisibilityBtn.style.backgroundColor = isHidden ? "yellow" : "white";
highlightSentence();
});
if (prevBtn) {
prevBtn.addEventListener("click", () => {
prepareSentences();
sentenceIndex = Math.max(0, sentenceIndex - 1);
highlightSentence();
updateSentenceCounter();
updateDonePercentage();
syncDoneCheckbox();
saveSpeech();
});
}
if (nextBtn) {
nextBtn.addEventListener("click", () => {
prepareSentences();
sentenceIndex = Math.min(sentences.length - 1, sentenceIndex + 1);
highlightSentence();
updateSentenceCounter();