-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4064 lines (3737 loc) · 191 KB
/
Copy pathscript.js
File metadata and controls
4064 lines (3737 loc) · 191 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
// Version info
const APP_VERSION = "2.3.5";
const APP_BUILD_NUMBER = "140202062026";
const APP_BUILD_DATE = "2026-06-02";
const INITIAL_RENDER_LIMIT = 30;
const RENDER_STEP = 30;
const SEARCH_DEBOUNCE_MS = 200;
const UPDATE_DISMISS_KEY = "dismissedUpdateVersion";
const PENDING_UPDATE_VERSION_KEY = "pendingUpdateVersion";
const BACKUP_SCHEMA_VERSION = "2.3.5";
const BACKUP_REMINDER_INTERVAL = 20;
const RECYCLE_RETENTION_DAYS = 30;
const FIRST_RUN_ONBOARDING_KEY = "hasSeenFirstRunOnboarding";
const LAST_BACKUP_AT_KEY = "lastBackupAt";
const LAST_BACKUP_COUNT_KEY = "lastBackupPostCount";
const LAST_BACKUP_REMINDER_COUNT_KEY = "lastBackupReminderPostCount";
const ENABLE_CELEBRATIONS_KEY = "enableCelebrations";
const SHARE_IMAGE_LIMITS = {
titleChars: 90,
maxHashtags: 3
};
const LANGUAGE_STORE_WEB_URL = "https://thoughtswebstore.netlify.app";
const LANGUAGE_STORE_RAW_BASE_URL = "https://raw.githubusercontent.com/dheeraz101/webstore-thoughts/main";
const LANGUAGE_STORE_MANIFEST_URL = `${LANGUAGE_STORE_RAW_BASE_URL}/languages.json`;
const LANGUAGE_NATIVE_NAMES = {
english: "English",
spanish: "Español",
french: "Français",
hindi: "हिन्दी",
emojis: "Emojis",
nnbabu: "NNBabu",
hinglish: "Hinglish",
tamil: "தமிழ்",
telugu: "తెలుగు",
bengali: "বাংলা",
marathi: "मराठी",
gujarati: "ગુજરાતી",
kannada: "ಕನ್ನಡ",
malayalam: "മലയാളം",
punjabi: "ਪੰਜਾਬੀ",
urdu: "اردو",
arabic: "العربية",
japanese: "日本語",
chinese: "中文",
korean: "한국어",
german: "Deutsch",
italian: "Italiano",
portuguese: "Português",
russian: "Русский"
};
const whatsNew = `
<strong>Thoughts v2.3.5</strong><br>
Share-as-image now keeps hashtags visible and wraps long notes cleanly onto new lines<br>
Settings import and update icons have been refined for a clearer Apple-style look<br>
Check for update now gives calmer visual feedback with a spinning update icon<br>
English and Hinglish release-facing text has been refreshed for this public patch<br><br>
<small>Stored locally in your browser. Export backups before clearing browser data.</small>
`;
const FINAL_RELEASE_CHANGELOG = `
<strong>Thoughts v2.3.5</strong><br>
Final public release patch: sharing reliability, settings polish, localization, and release metadata<br>
Faster notes feed with smarter rendering and Load More<br>
Safe markdown support in notes<br>
Share-as-image now preserves hashtags, wraps long text, and expands the card height when needed<br>
God Mode moved to hidden build-tap unlock (mobile friendly)<br>
Update system upgraded with version checks, install flow, and spinning check feedback<br><br>
<small>Always back up your notes from Settings before clearing browser data.</small>
`;
const CURRENT_RELEASE_CHANGELOG = `
<strong>Thoughts v2.3.5</strong><br>
Patch release for share-image reliability and settings detail<br>
Image sharing now shows hashtag-only notes and long notes without cutting the text<br>
Import and update rows in Settings now use cleaner icons<br>
Check for update now spins the icon while checking and waits before showing the result<br>
English and Hinglish text has been refreshed for the latest visible release copy<br><br>
<small>Stored locally in your browser. Export backups before clearing browser data.</small>
`;
// Lazy audio setup: keeps sound optional and avoids forcing loud defaults.
let audioContext = null;
let gainNode = null;
let criticalSoundsPreloaded = false;
// Define all sound files used in the app
const soundFiles = [
'/sounds/click.ogg',
'/sounds/error.ogg',
'/sounds/success.ogg',
'/sounds/stars.ogg',
'/sounds/tone.ogg',
'/sounds/long-touch.ogg',
'/sounds/single-firework.ogg',
'/sounds/fireworksschoolprid.ogg',
'/sounds/shooting-stars.ogg',
'/sounds/snow.ogg',
'/sounds/fireworks.ogg'
];
// Define critical sounds for initial preload
const criticalSounds = ['/sounds/click.ogg', '/sounds/error.ogg', '/sounds/success.ogg'];
// Store decoded audio buffers
const soundBuffers = new Map();
// Preload sound files into buffers
async function preloadSound(src) {
if (soundBuffers.has(src)) return; // Already preloaded
try {
const ctx = ensureAudioReady();
if (!ctx) return;
const response = await fetch(src);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
soundBuffers.set(src, audioBuffer);
console.log(`Preloaded sound: ${src}`);
} catch (err) {
console.warn(`Failed to preload sound (${src}):`, err);
}
}
function ensureAudioReady() {
if (!(window.AudioContext || window.webkitAudioContext)) return null;
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
gainNode = audioContext.createGain();
gainNode.gain.value = 0.35;
gainNode.connect(audioContext.destination);
}
return audioContext;
}
// Play sound using Web Audio API with full volume
const throttledPlaySound = throttle(async (src) => {
if (!isSoundEnabled) return;
const ctx = ensureAudioReady();
if (!ctx) return;
if (!soundFiles.includes(src)) {
console.warn(`Sound file ${src} not found in soundFiles array`);
return;
}
// Ensure audio context is running
if (ctx.state === "suspended") {
await ctx.resume();
}
if (!criticalSoundsPreloaded) {
criticalSoundsPreloaded = true;
await Promise.all(criticalSounds.map(preloadSound));
}
// Lazy-load sound if not preloaded
if (!soundBuffers.has(src)) {
await preloadSound(src);
}
// If still not loaded (e.g., fetch failed), skip playback
if (!soundBuffers.has(src)) {
console.warn(`Sound (${src}) not available for playback`);
return;
}
// Create and play the sound with full volume
const source = ctx.createBufferSource();
source.buffer = soundBuffers.get(src);
source.connect(gainNode); // Connect to gainNode instead of directly to destination
source.start(0);
}, 100);
// Attach to button clicks
document.querySelectorAll("button").forEach(button => {
button.addEventListener("click", () => {
console.log("Button clicked! Playing sound...");
throttledPlaySound('/sounds/click.ogg');
});
});
// Optional: Function to adjust volume dynamically if needed
function setVolume(level) {
if (!gainNode) return;
gainNode.gain.value = Math.max(0, Math.min(1, level)); // Clamp between 0 and 1
console.log(`Volume set to: ${gainNode.gain.value}`);
}
// Service Worker Registration
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/service-worker.js")
.then(registration => {
console.log("ServiceWorker registered:", registration.scope);
// When a new SW is found, it will install and go to 'waiting' state
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
console.log("New version available (SW waiting)");
checkForUpdates();
}
});
});
})
.catch(err => console.warn("ServiceWorker registration failed:", err));
});
// When the SW takes over, wait for the user to reload from the update popup.
navigator.serviceWorker.addEventListener('controllerchange', () => {
sessionStorage.setItem('sw-controller-updated', '1');
});
}
// Clean Update System
function checkForUpdates(options = {}) {
if (!navigator.onLine) return Promise.resolve({ status: "offline" });
return fetch(`/manifest.json?t=${Date.now()}`, { cache: 'no-store' })
.then(res => res.json())
.then(manifest => {
const storedVersion = localStorage.getItem('appVersion');
const currentVersion = storedVersion || APP_VERSION;
const dismissedVersion = localStorage.getItem(UPDATE_DISMISS_KEY);
const isLocalDevelopmentHost = ["localhost", "127.0.0.1", "0.0.0.0"].includes(window.location.hostname);
if (manifest.version !== currentVersion) {
localStorage.setItem(PENDING_UPDATE_VERSION_KEY, manifest.version);
if (!options.forceNotify && isLocalDevelopmentHost) return { status: "local-dev", version: manifest.version };
if (!options.forceNotify && dismissedVersion === manifest.version) return { status: "dismissed", version: manifest.version };
if (!options.suppressNotify) showUpdateNotification(manifest.version, getCurrentDraftForUpdate, saveDraftForUpdate);
return { status: "available", version: manifest.version };
}
localStorage.setItem('appVersion', APP_VERSION);
localStorage.removeItem(PENDING_UPDATE_VERSION_KEY);
localStorage.removeItem(UPDATE_DISMISS_KEY);
return { status: "current", version: manifest.version };
})
.catch(() => ({ status: "error" }));
}
function showUpdateNotification(newVersion, getDraftFn, saveDraftFn) {
if (document.querySelector('.update-notification')) return;
const isMobile = window.innerWidth <= 768;
const notification = document.createElement('div');
notification.className = 'update-notification';
Object.assign(notification.style, {
position: 'fixed',
bottom: '20px',
left: '50%',
transform: 'translateX(-50%)',
background: 'rgba(20, 23, 26, 0.85)',
backdropFilter: 'blur(16px) saturate(180%)',
WebkitBackdropFilter: 'blur(16px) saturate(180%)',
borderRadius: '20px',
padding: isMobile ? '20px' : '24px',
maxWidth: isMobile ? '90vw' : '340px',
width: '100%',
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.4)',
color: '#ffffff',
textAlign: 'center',
border: '1px solid rgba(255, 255, 255, 0.12)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: '10px',
zIndex: '99999'
});
const title = document.createElement('p');
title.textContent = textFor("newUpdateTitle", "Update Available");
Object.assign(title.style, {
fontSize: '17px',
fontWeight: '700',
margin: '0',
lineHeight: '1.3'
});
const versionText = document.createElement('p');
versionText.textContent = `${textFor("versionLabel", "Version")} ${newVersion}`;
Object.assign(versionText.style, {
fontSize: '14px',
color: '#aaa',
margin: '0'
});
const updateButton = document.createElement('button');
updateButton.textContent = textFor("updateNowButton", "Update Now");
const laterButton = document.createElement('button');
laterButton.textContent = textFor("laterButton", "Later");
Object.assign(updateButton.style, {
background: '#34c759',
color: '#fff',
border: 'none',
padding: '12px 0',
borderRadius: '14px',
fontSize: '16px',
fontWeight: '600',
cursor: 'pointer',
width: '100%',
transition: 'background 0.2s ease'
});
Object.assign(laterButton.style, {
background: 'transparent',
color: '#c4c4c4',
border: '1px solid rgba(255,255,255,0.2)',
padding: '10px 0',
borderRadius: '12px',
fontSize: '14px',
fontWeight: '500',
cursor: 'pointer',
width: '100%'
});
updateButton.onmouseover = () => updateButton.style.background = '#2db84d';
updateButton.onmouseout = () => updateButton.style.background = '#34c759';
updateButton.addEventListener('click', () => {
throttledPlaySound('/sounds/click.ogg');
const currentDraft = (typeof getDraftFn === "function" ? getDraftFn() : "") || "";
if (currentDraft && typeof saveDraftFn === "function") saveDraftFn(currentDraft);
localStorage.removeItem(UPDATE_DISMISS_KEY);
performUpdate(newVersion, getDraftFn, saveDraftFn, notification);
});
laterButton.addEventListener('click', () => {
throttledPlaySound('/sounds/click.ogg');
localStorage.setItem(UPDATE_DISMISS_KEY, newVersion);
localStorage.setItem(PENDING_UPDATE_VERSION_KEY, newVersion);
notification.remove();
});
notification.appendChild(title);
notification.appendChild(versionText);
notification.appendChild(updateButton);
notification.appendChild(laterButton);
document.body.appendChild(notification);
}
async function performUpdate(newVersion, getDraftFn, saveDraftFn, notificationEl) {
console.log(`Updating to version ${newVersion}...`);
try {
const currentDraft = (typeof getDraftFn === "function" ? getDraftFn() : "") || "";
if (currentDraft && typeof saveDraftFn === "function") saveDraftFn(currentDraft);
const progressEl = showUpdateProgressPopup(newVersion, notificationEl);
const startedAt = Date.now();
const reg = await navigator.serviceWorker.ready;
await reg.update();
if (reg.waiting) {
reg.waiting.postMessage({ type: 'SKIP_WAITING' });
} else {
const started = Date.now();
while (!reg.waiting && Date.now() - started < 4000) {
await new Promise(resolve => setTimeout(resolve, 250));
await reg.update();
}
if (reg.waiting) reg.waiting.postMessage({ type: 'SKIP_WAITING' });
}
const keys = await caches.keys();
await Promise.all(
keys
.filter(k => k !== `thoughts-v${newVersion}` && k.startsWith('thoughts-v'))
.map(k => caches.delete(k))
);
const elapsed = Date.now() - startedAt;
if (elapsed < 2000) await new Promise(resolve => setTimeout(resolve, 2000 - elapsed));
localStorage.setItem('appVersion', newVersion);
localStorage.removeItem(UPDATE_DISMISS_KEY);
localStorage.removeItem(PENDING_UPDATE_VERSION_KEY);
showUpdateReloadState(progressEl, newVersion);
} catch (e) {
console.warn('Update failed:', e);
createNotification(textFor("updateFailedTrySettings", "Update failed. Try again from Settings."), { background: "#ef4444" });
}
}
function showUpdateProgressPopup(newVersion, notificationEl) {
if (notificationEl?.classList?.contains("settings-overlay")) {
closeModalOverlay(notificationEl);
} else if (notificationEl) {
notificationEl.remove();
}
document.querySelectorAll('.update-progress-popup').forEach(el => el.remove());
const popup = document.createElement('div');
popup.className = 'update-progress-popup';
popup.innerHTML = `
<div class="update-progress-card">
<div class="update-progress-track" aria-hidden="true"><span></span></div>
<h2>${textFor("updateInstallingTitle", "Installing update")}</h2>
<p>${textFor("updateInstallingMessage", "Preparing version {version}. Your current draft is kept safe.", { version: newVersion })}</p>
</div>
`;
document.body.appendChild(popup);
return popup;
}
function showUpdateReloadState(popup, newVersion) {
const target = popup || showUpdateProgressPopup(newVersion);
target.innerHTML = `
<div class="update-progress-card">
<h2>${textFor("updateReadyTitle", "Update ready")}</h2>
<p>${textFor("updateReadyMessage", "Version {version} is installed. Reload to finish switching over.", { version: newVersion })}</p>
<button type="button" data-update-reload>${textFor("reloadButton", "Reload")}</button>
</div>
`;
target.querySelector("[data-update-reload]").addEventListener("click", () => window.location.reload());
}
// Check for updates on load + every 30 minutes
checkForUpdates();
setInterval(checkForUpdates, 30 * 60 * 1000);
// Check when coming back online
window.addEventListener('online', () => setTimeout(checkForUpdates, 2000));
let languageData = {};
let selectedLanguage = localStorage.getItem("language") || "english";
let isGodMode = localStorage.getItem("isGodMode") === "true";
let texts = {};
let editIndex = null;
let updateEditState;
let originalLanguageData = {};
let hasRenderedPostSkeleton = false;
const DEFAULT_CHAR_LIMIT = 500;
const GOD_MODE_TAP_TARGET = 7;
let currentCharLimit;
let hasSeenVolumeNotification = localStorage.getItem("hasSeenVolumeNotification") === "true";
let isZoomEnabled = localStorage.getItem("isZoomEnabled") === "true" || false;
let isSoundEnabled = localStorage.getItem("isSoundEnabled") === "true";
let getCurrentDraftForUpdate = () => {
const input = document.getElementById("public-input");
return input ? input.value.trim() : "";
};
let saveDraftForUpdate = (draft) => {
localStorage.setItem("draftNote", draft || "");
};
function textFor(key, fallback, replacements = {}) {
let value = texts?.[key] || languageData?.english?.[key] || fallback || "";
Object.entries(replacements).forEach(([name, replacement]) => {
value = value.replaceAll(`{${name}}`, replacement);
});
return value;
}
function subtleHaptic() {
if (!isSoundEnabled || !navigator.vibrate) return;
navigator.vibrate(8);
}
// Simple hash function (djb2 variant)
function simpleHash(str) {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash * 33) ^ str.charCodeAt(i);
}
return hash >>> 0;
}
// Precomputed hash of the secret code
const SECRET_CODE_HASH = 3912020992;
// Utility: Throttle function (optimized)
function throttle(func, limit) {
let inThrottle;
let lastArgs;
return function (...args) {
lastArgs = args;
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
if (lastArgs !== args) func.apply(this, lastArgs); // Catch final call
}, limit);
}
};
}
// Utility: Debounce function (for rendering)
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// Escape user-written text before putting it inside innerHTML
function escapeHTML(str = "") {
return String(str).replace(/[&<>"']/g, char => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
}[char]));
}
// Function to detect if the user is on a PC
function isPC() {
const userAgent = navigator.userAgent.toLowerCase();
// Common PC identifiers: Windows, Mac, Linux (excluding mobile versions)
const pcPatterns = /(windows nt|macintosh|linux (?!.*android))/i;
const mobilePatterns = /(android|iphone|ipad|mobile|tablet)/i;
// If it matches a PC pattern and does NOT match a mobile pattern, it's a PC
return pcPatterns.test(userAgent) && !mobilePatterns.test(userAgent);
}
// Notification creation function (consolidated)
function createNotification(message, options = {}) {
const { background = "rgba(20, 23, 26, 0.85)", color = "#ffffff", duration = 1500, top = "20px", zIndex = "4200" } = options;
const notificationDiv = document.createElement("div");
notificationDiv.textContent = message;
Object.assign(notificationDiv.style, {
position: "fixed",
top,
left: "50%",
transform: "translateX(-50%)",
background,
color,
padding: "14px 28px",
borderRadius: "16px",
boxShadow: "0 6px 16px rgba(0, 0, 0, 0.3)",
zIndex,
fontSize: "18px",
fontWeight: "600",
textAlign: "center",
width: "min(92vw, 760px)",
maxWidth: "760px",
opacity: "0",
transition: "opacity 0.3s ease-in-out",
...(window.innerWidth <= 768 && { fontSize: "16px", padding: "12px 20px", width: "calc(100vw - 28px)" })
});
if (background === "rgba(20, 23, 26, 0.85)") {
Object.assign(notificationDiv.style, {
backdropFilter: "blur(8px)",
border: "1px solid rgba(255, 255, 255, 0.15)",
fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
});
}
document.body.appendChild(notificationDiv);
setTimeout(() => notificationDiv.style.opacity = "1", 10);
setTimeout(() => {
notificationDiv.style.opacity = "0";
setTimeout(() => notificationDiv.remove(), 300);
}, duration);
}
// Specific notification types
function showGodModeNotification() {
throttledPlaySound('/sounds/stars.ogg');
createNotification(textFor("godModeUnlocked", "God Mode Unlocked"), { background: "rgba(255, 215, 0, 0.9)", color: "#000", duration: 1500 });
}
function showSuccess(message) {
throttledPlaySound('/sounds/success.ogg');
createNotification(message, { duration: 4500 });
}
function getBuildInfoLabel() {
return `Build ${APP_BUILD_NUMBER} - ${APP_BUILD_DATE}`;
}
function getStoredPosts() {
return normalizePosts(JSON.parse(localStorage.getItem("posts") || "[]"));
}
function persistPosts(posts) {
const normalizedPosts = normalizePosts(posts);
const postsString = JSON.stringify(normalizedPosts);
localStorage.setItem("posts", postsString);
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then(reg => reg.active?.postMessage({ type: "SAVE_POSTS", posts: postsString }))
.catch(err => console.warn("SW posts save failed:", err));
}
return normalizedPosts;
}
function formatRelativeBackupAge(timestamp) {
if (!timestamp) return "No backup yet";
const diffMs = Date.now() - Date.parse(timestamp);
if (!Number.isFinite(diffMs) || diffMs < 0) return "Backup date unknown";
const minutes = Math.floor(diffMs / 60000);
if (minutes < 1) return "Backed up just now";
if (minutes < 60) return `Backed up ${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `Backed up ${hours}h ago`;
const days = Math.floor(hours / 24);
return `Backed up ${days}d ago`;
}
function lockPageScrollForModal(overlay, panel) {
const scrollY = window.scrollY || document.documentElement.scrollTop || 0;
document.body.dataset.previousOverflow = document.body.style.overflow || "";
document.body.dataset.previousPosition = document.body.style.position || "";
document.body.dataset.previousTop = document.body.style.top || "";
document.body.dataset.previousWidth = document.body.style.width || "";
document.body.dataset.modalScrollY = String(scrollY);
document.body.style.overflow = "hidden";
document.body.style.position = "fixed";
document.body.style.top = `-${scrollY}px`;
document.body.style.width = "100%";
overlay.addEventListener("wheel", event => {
if (!panel) return;
event.preventDefault();
panel.scrollTop += event.deltaY * 2.2;
}, { passive: false });
let lastTouchY = 0;
overlay.addEventListener("touchstart", event => {
lastTouchY = event.touches[0]?.clientY || 0;
}, { passive: true });
overlay.addEventListener("touchmove", event => {
if (!panel) return;
const currentY = event.touches[0]?.clientY || lastTouchY;
event.preventDefault();
panel.scrollTop += (lastTouchY - currentY) * 1.7;
lastTouchY = currentY;
}, { passive: false });
}
function closeModalOverlay(overlay) {
overlay.remove();
const scrollY = Number.parseInt(document.body.dataset.modalScrollY || "0", 10);
document.body.style.overflow = document.body.dataset.previousOverflow || "";
document.body.style.position = document.body.dataset.previousPosition || "";
document.body.style.top = document.body.dataset.previousTop || "";
document.body.style.width = document.body.dataset.previousWidth || "";
delete document.body.dataset.previousOverflow;
delete document.body.dataset.previousPosition;
delete document.body.dataset.previousTop;
delete document.body.dataset.previousWidth;
delete document.body.dataset.modalScrollY;
window.scrollTo(0, Number.isFinite(scrollY) ? scrollY : 0);
}
function showLanguageChangeNotification(language, showWelcome = false) {
const langName = languageData[language].name || language;
let message;
if (showWelcome) {
message = (texts.welcomeMessage || "Welcome! Language set to \"{name}\".").replace("{name}", langName);
} else {
message = (texts.applyingLanguageMessage || "Language switched to \"{name}\".").replace("{name}", langName);
}
createNotification(message, { duration: 1500 });
}
function toRoman(num) {
if (num === 0) return "";
const romanValues = [
{ value: 1000, numeral: "M" },
{ value: 900, numeral: "CM" },
{ value: 500, numeral: "D" },
{ value: 400, numeral: "CD" },
{ value: 100, numeral: "C" },
{ value: 90, numeral: "XC" },
{ value: 50, numeral: "L" },
{ value: 40, numeral: "XL" },
{ value: 10, numeral: "X" },
{ value: 9, numeral: "IX" },
{ value: 5, numeral: "V" },
{ value: 4, numeral: "IV" },
{ value: 1, numeral: "I" }
];
let result = "";
for (const { value, numeral } of romanValues) {
while (num >= value) {
result += numeral;
num -= value;
}
}
return result;
}
function updateHeaderTitle() {
const headerTitle = document.querySelector("header h1");
if (headerTitle) {
let posts = normalizePosts(JSON.parse(localStorage.getItem("posts") || "[]"));
localStorage.setItem("posts", JSON.stringify(posts));
const postCount = posts.length;
headerTitle.textContent = `${texts.appName} ${toRoman(postCount)}`;
}
}
function normalizePosts(posts) {
return posts.map(post => {
const parsedDate = new Date(post.timestamp);
return {
text: String(post.text || ""),
timestamp: isNaN(parsedDate.getTime())
? new Date().toISOString()
: parsedDate.toISOString(),
pinned: Boolean(post.pinned)
};
});
}
// Async fetch for languages
async function fetchLanguages() {
try {
// Load from localStorage first (instant)
const storedLanguages = JSON.parse(localStorage.getItem("customLanguages") || "{}");
const storedOriginal = JSON.parse(localStorage.getItem("originalLanguageData") || "{}");
// Fetch from server as a fallback or initial setup
const response = await fetch("/languages.json");
originalLanguageData = await response.json();
localStorage.setItem("originalLanguageData", JSON.stringify(originalLanguageData)); // Save instantly
// Merge with custom languages
languageData = { ...originalLanguageData, ...storedLanguages };
// Check cache for newer custom languages
const cachedLanguages = await caches.match("/languages");
if (cachedLanguages) {
const cachedData = JSON.parse(await cachedLanguages.text());
if (cachedData.timestamp > (localStorage.getItem("languageTimestamp") || 0)) {
Object.assign(languageData, cachedData.data);
localStorage.setItem("customLanguages", JSON.stringify(cachedData.data));
localStorage.setItem("languageTimestamp", cachedData.timestamp);
}
}
// Ensure selected language exists, fallback to english
if (!languageData[selectedLanguage]) {
selectedLanguage = "english";
localStorage.setItem("language", "english");
}
texts = { ...(languageData["english"] || {}), ...(languageData[selectedLanguage] || {}) };
const baseCharLimit = Number(texts.charLimit) || DEFAULT_CHAR_LIMIT;
currentCharLimit = isGodMode ? baseCharLimit * 2 : baseCharLimit;
texts.charCount = `{count}/${currentCharLimit}`;
const splashTitle = document.getElementById("splash-title");
splashTitle.textContent = texts.appName;
splashTitle.classList.add("scale-110");
setTimeout(() => splashTitle.classList.remove("scale-110"), 300);
} catch (err) {
console.error("Failed to load languages:", err);
languageData = JSON.parse(localStorage.getItem("customLanguages") || "{}") || { english: { appName: "Thoughts", addButton: "Add", charLimit: DEFAULT_CHAR_LIMIT } };
selectedLanguage = "english";
localStorage.setItem("language", "english");
texts = { ...(languageData["english"] || {}), ...(languageData[selectedLanguage] || {}) };
const baseCharLimit = Number(texts.charLimit) || DEFAULT_CHAR_LIMIT;
currentCharLimit = isGodMode ? baseCharLimit * 2 : baseCharLimit;
}
// Backup to service worker cache asynchronously
saveLanguagesToCache();
}
function saveLanguagesToCache() {
const languagePayload = {
data: Object.keys(languageData)
.filter(key => !originalLanguageData[key]) // Only custom languages
.reduce((obj, key) => {
obj[key] = languageData[key];
return obj;
}, {}),
timestamp: Date.now()
};
localStorage.setItem("customLanguages", JSON.stringify(languagePayload.data));
localStorage.setItem("languageTimestamp", languagePayload.timestamp);
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then(reg => {
reg.active?.postMessage({
type: "SAVE_LANGUAGES",
languages: JSON.stringify(languagePayload)
});
}).catch(err => console.warn("Failed to save languages to cache:", err));
}
}
function getLocalizedDateString() {
const today = new Date();
const dayIndex = today.getDay();
const date = today.getDate();
const monthIndex = today.getMonth();
const year = today.getFullYear();
const currentTexts = languageData[selectedLanguage] || languageData["english"];
let dayName, monthName;
if (currentTexts.days && currentTexts.months) {
dayName = currentTexts.days[dayIndex];
monthName = currentTexts.months[monthIndex];
} else {
// Fallback to browser's locale formatting
const locale = selectedLanguage === "english" ? "en-US" : selectedLanguage;
dayName = today.toLocaleDateString(locale, { weekday: "long" });
monthName = today.toLocaleDateString(locale, { month: "long" });
}
return `${dayName}, ${monthName} ${date}, ${year}`;
}
// Add this new function to apply zoom state silently
function applyZoomStateSilently() {
const metaViewport = document.querySelector('meta[name="viewport"]');
if (!metaViewport) {
const newMeta = document.createElement("meta");
newMeta.name = "viewport";
newMeta.content = isZoomEnabled
? "width=device-width, initial-scale=1.0"
: "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
document.head.appendChild(newMeta);
} else {
metaViewport.content = isZoomEnabled
? "width=device-width, initial-scale=1.0"
: "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no";
}
const zoomToggleBtn = document.getElementById("zoom-toggle");
if (zoomToggleBtn) {
zoomToggleBtn.textContent = isZoomEnabled
? (texts.zoomEnabledText || "Zoom: On")
: (texts.zoomDisabledText || "Zoom: Off");
}
}
// Update toggleZoom to only handle user interaction
function saveAppSettings(lang, zoomEnabled) {
if (lang) localStorage.setItem("language", lang);
if (zoomEnabled !== undefined) localStorage.setItem("isZoomEnabled", zoomEnabled.toString());
}
// Update toggleZoom to only handle user interaction
function toggleZoom() {
isZoomEnabled = !isZoomEnabled;
saveAppSettings(null, isZoomEnabled); // Save immediately
// Add a small delay to ensure data is persisted
setTimeout(() => {
applyZoomStateSilently(); // Apply the state
createNotification(
isZoomEnabled
? (texts.zoomEnabledNotification || "Zoom Enabled")
: (texts.zoomDisabledNotification || "Zoom Disabled"),
{ duration: 1500 }
);
}, 50); // Small delay
}
// Modify the initial zoom application in DOMContentLoaded
document.addEventListener("DOMContentLoaded", () => {
applyZoomStateSilently(); // Apply initial state silently
});
// Main app initialization
document.addEventListener("DOMContentLoaded", async () => {
await fetchLanguages();
const customLanguages = JSON.parse(localStorage.getItem("customLanguages") || "{}");
Object.assign(languageData, customLanguages);
// DOM elements
const elements = {
postButton: document.getElementById("post-button"),
postContainer: document.getElementById("post-container"),
inputWrapper: document.getElementById("public-input"),
charCount: document.getElementById("char-count"),
deleteAllButton: document.getElementById("delete-all"),
deleteConfirmation: document.getElementById("delete-confirmation"),
confirmDelete: document.getElementById("confirm-delete"),
cancelDelete: document.getElementById("cancel-delete"),
searchInput: document.getElementById("search-input"),
scrollToTopButton: document.getElementById("scroll-to-top"),
clearSearch: document.querySelector(".clear-search"),
cancelEditButton: document.getElementById("cancel-edit"),
hashtagList: document.getElementById("hashtag-list"),
footer: document.getElementById("footer")
};
// Validate critical elements
if (!elements.inputWrapper || !elements.postContainer || !elements.footer) {
console.error("Critical DOM elements missing");
createNotification(textFor("appInitFailed", "App initialization failed"), { background: "#ef4444", duration: 5000 });
return;
}
let actionContext = null;
let activeHashtag = null;
let visiblePostCount = INITIAL_RENDER_LIMIT;
let lastRenderFilter = "";
let lastRenderHashtag = null;
let noteSearchIndex = [];
let lastSavedDraft = localStorage.getItem("draftNote") || "";
let isSavingOnClose = false;
let deferredInstallPrompt = null;
await loadInitialData();
applyZoomStateSilently();
// Ensure God Mode state is applied correctly on init
isGodMode = localStorage.getItem("isGodMode") === "true";
{
const baseCharLimit = Number(texts.charLimit) || DEFAULT_CHAR_LIMIT;
currentCharLimit = isGodMode ? baseCharLimit * 2 : baseCharLimit;
texts.charCount = `{count}/${currentCharLimit}`;
applyLanguage(selectedLanguage);
renderPosts();
}
//
// TIER 1 + TIER 3: Power Features
//
// Smart relative date ("2h ago", "yesterday")
function timeAgo(timestamp) {
const now = new Date();
const then = new Date(timestamp);
const seconds = Math.floor((now - then) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
if (seconds < 172800) return 'yesterday';
if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;
if (seconds < 2592000) return `${Math.floor(seconds / 604800)}w ago`;
// Fallback to formatted date
return then.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
function formatPostDate(timestamp) {
const parsed = new Date(timestamp);
if (isNaN(parsed.getTime())) return "";
return parsed.toLocaleString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
});
}
// Reading time estimate
function getReadingTime(text) {
const words = text.trim().split(/\s+/).length;
const minutes = Math.ceil(words / 200); // 200 wpm average
return minutes < 1
? textFor("readingTimeUnderMinute", "< 1 min read")
: textFor("readingTimeMinutes", "{count} min read", { count: String(minutes) });
}
// Word count
function getWordCount(text) {
return text.trim().split(/\s+/).filter(w => w.length > 0).length;
}
// Writing streak feature removed
// Generate shareable image from post
function generatePostImage(post, index) {
const { title, content } = extractTitleAndContent(post.text);
const cleanTitle = title ? title.replace(/^@/, '').slice(0, SHARE_IMAGE_LIMITS.titleChars) : null;
const cleanContent = (content || post.text || "").trim();
const words = getWordCount(post.text);
const readTime = getReadingTime(post.text);
const relativeDate = timeAgo(post.timestamp);
const compactNote = cleanContent.length <= 110 && words <= 16;
const shortNote = cleanContent.length <= 190 && words <= 28;
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const scale = 2; // retina
const w = 600;
const maxTextWidth = w - 60;
const titleFontSize = compactNote ? 36 : shortNote ? 30 : 22;
const titleLineHeight = compactNote ? 42 : shortNote ? 36 : 28;
const contentFontSize = compactNote ? 30 : shortNote ? 25 : 16;
const contentLineHeight = compactNote ? 40 : shortNote ? 34 : 24;
ctx.font = `bold ${titleFontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
const titleLines = cleanTitle ? wrapText(ctx, cleanTitle, maxTextWidth) : [];
ctx.font = `${contentFontSize}px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`;
const contentLines = wrapText(ctx, cleanContent, maxTextWidth);
const hashtags = (post.text.match(/#\w+/g) || []).slice(0, SHARE_IMAGE_LIMITS.maxHashtags);
ctx.font = '12px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
const hashtagLines = hashtags.length ? wrapText(ctx, hashtags.join(' '), maxTextWidth) : [];
const topPadding = 40;
const titleBlockHeight = titleLines.length ? titleLines.length * titleLineHeight + (compactNote ? 16 : shortNote ? 12 : 8) : 0;
const contentBlockHeight = Math.max(contentLineHeight, contentLines.length * contentLineHeight);
const metaBlockHeight = 86 + (hashtagLines.length ? hashtagLines.length * 18 + 6 : 0);
const h = Math.max(cleanTitle ? 380 : 320, topPadding + titleBlockHeight + contentBlockHeight + metaBlockHeight);
canvas.width = w * scale;
canvas.height = h * scale;
ctx.scale(scale, scale);