-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1029 lines (898 loc) · 41.1 KB
/
Copy pathindex.html
File metadata and controls
1029 lines (898 loc) · 41.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<!-- === CHARACTER ENCODING & MOBILE SETUP === -->
<!-- UTF-8 lets you use accented Italian characters (è, à, ù, etc.) -->
<meta charset="UTF-8">
<!-- This makes the page fit the phone screen properly and prevents
the annoying zoom-in when you tap an input field -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>thought.log</title>
<!-- === PWA (Progressive Web App) SETUP === -->
<!-- The manifest tells the phone/browser "this website can be installed as an app"
It defines the app name, icon, colors, etc. (see manifest.json) -->
<link rel="manifest" href="manifest.json">
<!-- theme-color sets the color of the phone's status bar when the app is open -->
<meta name="theme-color" content="#1a1a17">
<!-- These two lines are for iPhones specifically (Apple does things differently) -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<!-- The little icon you see in the browser tab (a thought bubble emoji) -->
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>💭</text></svg>">
<!-- === FONTS === -->
<!-- Loading two fonts from Google:
- DM Sans: a clean font for body text
- IBM Plex Mono: a monospace font (like a typewriter) for the log format -->
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<!-- === CSS STYLES === -->
<!-- CSS is the language that controls how everything LOOKS (colors, sizes, positions).
Think of HTML as the skeleton and CSS as the skin/clothes. -->
<style>
/* Reset: remove default browser spacing so everything starts from zero */
/* [v2] touch-action:manipulation removes 300ms tap delay on Android */
*{box-sizing:border-box;margin:0;padding:0;touch-action:manipulation}
/* :root defines "variables" — like constants in MATLAB.
Instead of writing #1a1a17 everywhere, we write var(--bg).
If you want to change a color, you change it in ONE place. */
:root{
--bg:#1a1a17; /* dark background (almost black, warm) */
--surface:#23231f; /* slightly lighter, used for cards */
--border:#3a3a32; /* subtle border color */
--ink:#e8e4d9; /* main text color (warm off-white) */
--ink-dim:#9e9a8b; /* dimmed text for secondary info */
--accent:#c9a84c; /* gold accent for dates and buttons */
--tag:#5b8a72; /* green for #hashtags */
--tag-bg:rgba(91,138,114,0.15); /* transparent green background for tag chips */
--danger:#c45c4a; /* red for delete/stop buttons */
--mono:'IBM Plex Mono','Courier New',monospace; /* typewriter font */
--sans:'DM Sans',sans-serif; /* clean body font */
}
/* Base page styling */
html,body{
background:var(--bg);
color:var(--ink);
font-family:var(--sans);
min-height:100vh; /* vh = viewport height, fill the screen */
-webkit-tap-highlight-color:transparent; /* remove the blue flash when tapping on phones */
}
/* Make inputs and buttons inherit the page font instead of using ugly defaults */
input,textarea,button{font-family:inherit}
/* [v2] Both input and textarea placeholders need styling */
input::placeholder,textarea::placeholder{color:var(--ink-dim);opacity:.6}
/* === ANIMATIONS ===
@keyframes defines an animation you can reuse.
Think of it like defining a function in MATLAB that you call later. */
/* fadeIn: element slides up and fades in (used for new thoughts, entries) */
@keyframes fadeIn{
from{opacity:0;transform:translateY(8px)} /* start invisible, 8px below */
to{opacity:1;transform:translateY(0)} /* end visible, normal position */
}
/* pulse: mic button breathes when recording */
@keyframes pulse{
0%,100%{transform:scale(1)} /* normal size at start and end */
50%{transform:scale(1.1)} /* slightly bigger in the middle */
}
/* toastIn: the "Saved" notification slides up from the bottom */
@keyframes toastIn{
from{opacity:0;transform:translate(-50%,16px)}
to{opacity:1;transform:translate(-50%,0)}
}
/* === LAYOUT === */
/* The main wrapper: centered, max 520px wide (good for phones and desktop) */
.wrap{max-width:520px;margin:0 auto;padding:0 16px 80px}
/* Header: logo on the left, tabs on the right */
.header{padding:24px 0 16px;display:flex;align-items:baseline;justify-content:space-between}
.logo{font-family:var(--mono);font-size:18px;font-weight:500;letter-spacing:.05em;color:var(--accent)}
.version { font-size: 10px; color: var(--ink-dim); margin-left: 6px; font-weight: 400; vertical-align: middle; }
/* Tab buttons (capture / log) */
.tabs{display:flex;gap:4px}
.tab{background:transparent;border:1px solid transparent;color:var(--ink-dim);padding:6px 14px;border-radius:6px;cursor:pointer;font-family:var(--mono);font-size:12px;font-weight:500}
.tab.active{background:var(--surface);border-color:var(--border);color:var(--ink)}
/* === CAPTURE CARD === */
/* The top of the card shows the date stamp [YYMMDD HH:MM] */
.card-top{font-family:var(--mono);font-size:15px;color:var(--accent);padding:12px 16px;background:var(--surface);border-radius:10px 10px 0 0;border:1px solid var(--border);border-bottom:none}
/* Each row has: a label (@, -), an input field, and a mic button */
.row{display:flex;align-items:center;gap:8px;padding:10px 16px;background:var(--surface);border-left:1px solid var(--border);border-right:1px solid var(--border)}
.row-label{font-family:var(--mono);color:var(--ink-dim);font-size:15px;flex-shrink:0}
.row-label.active{color:var(--accent)}
.row textarea{
flex:1;background:transparent;border:none;outline:none;
color:var(--ink);font-size:15px;font-family:inherit;
resize:none;overflow:hidden;
line-height:1.5;
min-height:24px;
}
/* Microphone button: round, gold, turns red when recording */
.mic{width:48px;height:48px;border-radius:50%;background:var(--accent);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s;flex-shrink:0}
.mic.on{background:var(--danger);animation:pulse 1.5s ease-in-out infinite}
/* List of thoughts already added to the current entry */
.thoughts-list{background:var(--surface);border-left:1px solid var(--border);border-right:1px solid var(--border);padding:4px 16px 8px}
.thought-item{display:flex;align-items:flex-start;gap:8px;padding:6px 0;animation:fadeIn .2s ease}
.thought-item span{flex:1;font-size:14px;line-height:1.5}
.thought-item .del{background:none;border:none;color:var(--ink-dim);cursor:pointer;font-size:16px;line-height:1;padding:0 2px;flex-shrink:0}
/* Hashtag highlighting: green and bold */
.ht{color:var(--tag);font-weight:500}
/* "+ add thought" button at the bottom of the card */
.add-btn{width:100%;padding:10px;background:var(--surface);border:1px solid var(--border);border-top:1px dashed var(--border);border-radius:0 0 10px 10px;color:var(--ink-dim);cursor:pointer;font-family:var(--mono);font-size:13px;transition:color .15s}
.add-btn:hover{color:var(--accent)}
/* Tag suggestion chips (the little #tag buttons below the card) */
.tags-bar{margin-top:16px;display:flex;flex-wrap:wrap;gap:6px}
.tag-chip{background:var(--tag-bg);border:1px solid rgba(91,138,114,.2);color:var(--tag);border-radius:20px;padding:4px 12px;font-family:var(--mono);font-size:12px;cursor:pointer;transition:all .15s}
.tag-chip:hover{background:var(--tag);color:var(--bg)}
/* Big gold "Save entry" button */
.save-btn{width:100%;margin-top:20px;padding:14px;background:var(--accent);border:none;border-radius:10px;color:var(--bg);font-size:15px;font-weight:600;cursor:pointer;transition:opacity .15s;letter-spacing:.02em}
.save-btn:hover{opacity:.85}
/* "edit" button */
.edit-form{margin-top:10px}
.edit-row{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.edit-row .row-label{font-family:var(--mono);color:var(--ink-dim);font-size:14px;flex-shrink:0}
.edit-input{flex:1;background:var(--bg);border:1px solid var(--border);border-radius:6px;
padding:8px 10px;color:var(--ink);font-size:14px;outline:none;font-family:inherit}
.edit-input:focus{border-color:var(--accent)}
.edit-del{background:none;border:none;color:var(--ink-dim);cursor:pointer;font-size:16px;
flex-shrink:0;padding:0 4px}
.edit-del:hover{color:var(--danger)}
.edit-add{background:none;border:1px dashed var(--border);border-radius:6px;color:var(--ink-dim);
cursor:pointer;font-family:var(--mono);font-size:12px;padding:6px;width:100%;
margin-top:2px;margin-bottom:8px}
.edit-add:hover{color:var(--accent);border-color:var(--accent)}
.edit-actions{display:flex;gap:8px;margin-top:8px}
.edit-save{flex:1;padding:10px;background:var(--accent);border:none;border-radius:8px;
color:var(--bg);font-weight:600;font-size:13px;cursor:pointer}
.edit-save:hover{opacity:.85}
.edit-cancel{flex:1;padding:10px;background:transparent;border:1px solid var(--border);
border-radius:8px;color:var(--ink-dim);font-size:13px;cursor:pointer;font-family:var(--mono)}
.edit-cancel:hover{color:var(--ink);border-color:var(--ink-dim)}
/* === LOG VIEW === */
/* Toolbar with copy and clear buttons */
.toolbar{display:flex;gap:8px;margin-bottom:16px}
.tool-btn{padding:8px 16px;background:var(--surface);border:1px solid var(--border);border-radius:8px;font-family:var(--mono);font-size:12px;cursor:pointer}
.tool-btn.copy{color:var(--accent)}
.tool-btn.clear{color:var(--danger)}
/* Each saved entry card in the log */
.entry{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:14px 16px;margin-bottom:10px;animation:fadeIn .25s ease}
.entry-head{display:flex;justify-content:space-between;align-items:center}
.entry-date{font-family:var(--mono);font-size:13px;color:var(--accent)}
.entry-actions{display:flex;gap:8px}
.entry-act{background:none;border:none;color:var(--ink-dim);cursor:pointer;font-size:14px;font-family:var(--mono)}
.entry-act:hover{color:var(--accent)}
.entry-act.danger:hover{color:var(--danger)}
.entry-ctx{font-family:var(--mono);font-size:13px;color:var(--ink-dim);margin-top:6px}
.entry-t{font-size:14px;margin-top:5px;padding-left:12px;line-height:1.5}
/* The text area that appears when clipboard copy fails (fallback) */
.export-area{width:100%;min-height:160px;margin-bottom:16px;padding:12px;background:var(--surface);border:1px solid var(--border);border-radius:8px;color:var(--ink);font-family:var(--mono);font-size:12px;resize:vertical;outline:none}
/* "nothing here yet" message */
.empty{color:var(--ink-dim);font-family:var(--mono);font-size:13px;text-align:center;margin-top:60px}
/* Toast notification: the little "Saved" / "Copied" message at the bottom */
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:var(--accent);color:var(--bg);padding:8px 20px;border-radius:20px;font-family:var(--mono);font-size:13px;font-weight:500;animation:toastIn .2s ease;z-index:100}
/* Utility class: adding "hidden" to any element hides it */
.hidden{display:none}
</style>
</head>
<!-- ============================================================
HTML BODY — THE STRUCTURE OF THE APP
============================================================
Think of this like the layout of a form in MATLAB's App Designer.
Each <div> is a container, each <button> is clickable,
each <input> is a text field.
"onclick" means: when the user clicks this, run this JavaScript function.
"id" means: this element has a unique name so JavaScript can find it.
"class" means: apply these CSS styles to this element.
============================================================ -->
<body>
<div class="wrap" id="app">
<!-- HEADER: logo + tab buttons -->
<div class="header">
<div class="logo">thought.log<span class="version">v2.1</span></div>
<div class="tabs">
<!-- Language toggle for voice input: tap to switch between EN and IT -->
<button class="tab" id="lang-btn" onclick="toggleLang()" title="Voice language">EN</button>
<!-- data-view is a custom attribute we use in JavaScript to know which tab is which -->
<button class="tab active" data-view="capture" onclick="switchView('capture')">capture</button>
<button class="tab" data-view="log" onclick="switchView('log')">log (0)</button>
</div>
</div>
<!-- ==================== CAPTURE VIEW ==================== -->
<!-- This is where you type/dictate new thoughts -->
<div id="capture-view">
<!-- Auto-generated date/time stamp, e.g. [260408 14:30] -->
<div class="card-top" id="stamp"></div>
<!-- Context row: the @ line (where/when/why) -->
<div class="row">
<span class="row-label">@</span>
<textarea id="ctx-input" rows="1" placeholder="where, when, why..." oninput="autoGrow(this)"></textarea>
<!-- Mic button for context — the SVG inside is just a microphone icon drawing -->
<button class="mic" id="mic-ctx" onclick="toggleMic('context')">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1a1a17" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="17" x2="12" y2="22"/></svg>
</button>
</div>
<!-- List of thoughts already added (starts hidden, shown by JavaScript) -->
<div id="thoughts-list" class="thoughts-list hidden"></div>
<!-- Thought input row: the - line -->
<div class="row">
<span class="row-label active">-</span>
<!-- onkeydown: when you press Enter, it calls addThought() -->
<textarea id="thought-input" rows="1" placeholder="your thought..." onkeydown="handleThoughtKey(event)" oninput="autoGrow(this)"></textarea>
<!-- Mic button for thoughts -->
<button class="mic" id="mic-thought" onclick="toggleMic('thought')">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1a1a17" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="17" x2="12" y2="22"/></svg>
</button>
</div>
<button class="add-btn" onclick="addThought()">+ add thought (or press Enter)</button>
<!-- Tag suggestions: shows your most-used #tags as tappable chips -->
<div id="tags-bar" class="tags-bar hidden"></div>
<button class="save-btn" onclick="saveEntry()">Save entry</button>
</div>
<!-- ==================== LOG VIEW ==================== -->
<!-- This shows all your saved entries -->
<div id="log-view" class="hidden">
<!-- Toolbar: copy and clear buttons -->
<div id="toolbar" class="toolbar hidden">
<button class="tool-btn copy" onclick="copyAll()">⎘ copy as .txt</button>
<button class="tool-btn clear" onclick="clearAll()">✕ clear all</button>
</div>
<!-- Fallback: if clipboard copy fails, the full text appears here
so you can manually select-all and copy -->
<textarea id="export-area" class="export-area hidden" readonly onfocus="this.select()"></textarea>
<!-- Saved entries will be inserted here by JavaScript -->
<div id="entries-container"></div>
</div>
</div>
<!-- Toast notification (hidden by default, shown briefly by flash()) -->
<div id="toast" class="toast hidden"></div>
<!-- ============================================================
JAVASCRIPT — THE LOGIC OF THE APP
============================================================
This is like a MATLAB script: it runs top to bottom when
the page loads, defining variables and functions.
Key concepts if you know MATLAB/Python:
- let/const = variable declaration (like x = 5 in MATLAB)
- function = same as function in MATLAB or def in Python
- document.getElementById('x') = finds an HTML element by its id
- element.classList = controls CSS classes (add/remove "hidden", etc.)
- element.innerHTML = sets the HTML content of an element
- localStorage = a tiny database built into the browser
(like save/load in MATLAB, but automatic and per-website)
- JSON = a text format for storing data (like a struct in MATLAB)
============================================================ -->
<script>
// ===================================================================
// 1. STATE (the data the app keeps track of)
// ===================================================================
// Load saved entries from localStorage.
// localStorage stores data as text, so we use JSON.parse to convert
// the text back into a JavaScript array of objects.
// The '[]' is the default: an empty array if nothing was saved yet.
// [v2] Wrapped in try-catch: corrupted localStorage was crashing the whole app
let entries;
try { entries = JSON.parse(localStorage.getItem('thought-log') || '[]'); }
catch { entries = []; }
// [v2] Drop malformed entries that would crash renderLog
entries = entries.filter(e => e && e.id && Array.isArray(e.thoughts));
// The thoughts being composed for the CURRENT entry (not yet saved).
// This resets every time you hit "Save entry".
let thoughts = [];
// Voice recording state
let listening = false; // true when the mic is active
let listenTarget = null; // which field is being dictated to: 'context' or 'thought'
let recognition = null; // the speech recognition object (created when you tap the mic)
let editingId = null; // which entry is in edit mode (null = none)
let lastProcessedPhrase = ''; // v1.3
let lastSpeechTime = 0; // tracks when speech was last detected
// Voice language: defaults to English, tap the "EN/IT" button to switch
let micLang = localStorage.getItem('thought-log-lang') || 'en-US';
// Check if this browser supports speech recognition.
// Chrome and Edge do, Firefox and Safari may not.
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
// ===================================================================
// 2. HELPER FUNCTIONS (small utilities used by the main functions)
// ===================================================================
/**
* pad(n) — Adds a leading zero to single-digit numbers.
* pad(3) => "03", pad(12) => "12"
* Used for formatting dates and times.
*/
function pad(n) { return String(n).padStart(2, '0'); }
/**
* now() — Returns the current date and time in our format.
* Returns an object like: { date: "260408", time: "14:30" }
*
* getFullYear() gives 2026, we slice to get "26".
* getMonth() is 0-based (January = 0), so we add 1.
*/
function now() {
const d = new Date();
return {
date: String(d.getFullYear()).slice(2) + pad(d.getMonth()+1) + pad(d.getDate()),
time: pad(d.getHours()) + ':' + pad(d.getMinutes())
};
}
/**
* flash(msg) — Shows a brief notification at the bottom of the screen.
* It appears, then disappears after 2 seconds.
* Used for "Saved", "Copied to clipboard", etc.
*/
// [v2] Added _flashTimer to prevent rapid calls leaving stale toasts
let _flashTimer = 0;
function flash(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.remove('hidden');
clearTimeout(_flashTimer);
_flashTimer = setTimeout(() => t.classList.add('hidden'), 2000);
}
/**
* escHtml(s) — Security function: prevents HTML injection.
* If someone types HTML code as a thought (like a bold tag or worse),
* this converts the < and > into harmless text characters.
* Without this, the browser would try to run the code.
*/
function escHtml(s) {
// [v2] Removed .replace(/'/g,''') — apostrophes are safe in our context
// (double-quoted attributes + innerHTML). The old conversion caused ' to
// show as literal text after double-encoding cycles (edit → save → render).
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
}
/**
* highlightTags(text) — Makes #hashtags green in the displayed text.
* First escapes HTML (security), then wraps any #word in a green <span>.
*
* The /(#\w+)/g is a "regular expression" (regex) — a pattern matcher.
* # = literal hash character
* \w+ = one or more "word" characters (letters, numbers, underscore)
* g = find ALL matches, not just the first one
*
* So "try this #idea for #removable" becomes:
* "try this <span class="ht">#idea</span> for <span class="ht">#removable</span>"
*/
function highlightTags(text) {
// [v2] Added \u00C0-\u024F to match accented chars: #ricordàre, #università
return escHtml(text).replace(/(#[\w\u00C0-\u024F]+)/g, '<span class="ht">$1</span>');
}
/**
* entriesToTxt(list) — Converts all entries into your .txt format.
* This is what gets copied to clipboard for pasting into Google Drive.
*
* .reverse() puts entries in chronological order (oldest first),
* because internally we store newest-first for display.
*
* Output looks like:
* [260408 09:00]
* @ walking to the lab
* - first thought #removable
* - second thought
*
* [260408 14:30]
* @ cooking
* - another thought
*/
function entriesToTxt(list) {
return [...list].reverse().map(e => {
// [...list] creates a copy so we don't modify the original array
let b = `[${e.date} ${e.time}]`;
if (e.context) b += '\n@ ' + e.context; // \n = new line
e.thoughts.forEach(t => b += '\n- ' + t); // add each thought
return b;
}).join('\n\n'); // separate entries with a blank line
}
/**
* persist() — Saves the entries array to localStorage.
* Called every time entries change (add, delete, clear).
* localStorage survives closing the browser, restarting the phone, etc.
* Data stays ONLY on this device, in this browser.
*/
function persist() {
localStorage.setItem('thought-log', JSON.stringify(entries));
}
/**
* extractTags() — Scans ALL saved entries and returns the most-used #tags.
* Used to show the tag suggestion chips.
*
* How it works:
* 1. Loop through every thought in every entry
* 2. Find all #hashtags using regex
* 3. Count how many times each tag appears
* 4. Sort by frequency (most used first)
* 5. Return just the tag names
*/
function extractTags() {
const c = {}; // counts object, like a Python dictionary: { '#removable': 5, '#idea': 2 }
entries.forEach(e => e.thoughts.forEach(t => {
const m = t.match(/#[\w\u00C0-\u024F]+/g); // [v2] supports accented chars
if (m) m.forEach(tag => c[tag] = (c[tag]||0) + 1); // increment count (or start at 1)
}));
return Object.entries(c) // convert { '#removable': 5 } to [['#removable', 5]]
.sort((a,b) => b[1]-a[1]) // sort by count, highest first
.map(([t]) => t); // keep only the tag name, drop the count
}
function handleThoughtKey(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
addThought();
}
}
function autoGrow(el) {
el.style.height = 'auto';
// [v2] min 24px so it doesn't collapse below one line
el.style.height = Math.max(el.scrollHeight, 24) + 'px';
}
function cleanTranscript(text) {
let s = text.trim();
if (!s) return s;
// Capitalize first letter
s = s.charAt(0).toUpperCase() + s.slice(1);
// Capitalize after sentence-ending punctuation
s = s.replace(/([.!?]\s+)(\w)/g, (_, p, c) => p + c.toUpperCase());
// Add period if sentence doesn't end with punctuation
if (!/[.!?]$/.test(s)) s += '.';
return s;
}
// ===================================================================
// 3. DATE/TIME STAMP (auto-updates every 30 seconds)
// ===================================================================
/**
* updateStamp() — Updates the [YYMMDD HH:MM] shown at the top of the capture card.
* Called once on page load, then every 30 seconds via setInterval.
*/
function updateStamp() {
const {date, time} = now(); // "destructuring": extracts date and time from the object
document.getElementById('stamp').textContent = `[${date} ${time}]`;
}
updateStamp(); // run once immediately
setInterval(updateStamp, 30000); // then every 30 seconds (30000 milliseconds)
// ===================================================================
// 4. VIEW SWITCHING (capture vs. log)
// ===================================================================
/**
* switchView(v) — Toggles between the "capture" and "log" views.
* - Highlights the active tab
* - Shows/hides the corresponding view
* - If switching to log, re-renders the entries
*/
function switchView(v) {
// Update tab styling: make the clicked tab "active", deactivate the other
document.querySelectorAll('.tab').forEach(t =>
t.classList.toggle('active', t.dataset.view === v)
);
// Show/hide views: classList.toggle('hidden', condition)
// If condition is true, it ADDS 'hidden'. If false, it REMOVES it.
document.getElementById('capture-view').classList.toggle('hidden', v !== 'capture');
document.getElementById('log-view').classList.toggle('hidden', v !== 'log');
// Refresh the log display when switching to it
if (v === 'log') renderLog();
}
// ===================================================================
// 5. CAPTURE FUNCTIONS (composing a new entry)
// ===================================================================
/**
* renderThoughts() — Redraws the list of thoughts in the current entry.
* Called after adding or removing a thought.
*
* This uses "template literals" (backtick strings with ${...}) to build HTML.
* It's like sprintf in MATLAB: `Hello ${name}` becomes "Hello Gregorio".
*/
function renderThoughts() {
const el = document.getElementById('thoughts-list');
// If there are no thoughts yet, hide the container
if (thoughts.length === 0) { el.classList.add('hidden'); el.innerHTML = ''; return; }
// Otherwise, show it and fill it with thought items
el.classList.remove('hidden');
el.innerHTML = thoughts.map((t, i) => `
<div class="thought-item">
<span style="font-family:var(--mono);color:var(--ink-dim);font-size:14px;flex:none">-</span>
<span>${highlightTags(t)}</span>
<button class="del" onclick="removeThought(${i})">×</button>
</div>
`).join('');
// .map() transforms each thought into HTML
// .join('') concatenates them all into one string
}
/**
* renderTagsBar() — Shows/updates the tag suggestion chips below the card.
* Only shows tags you've actually used before.
*/
function renderTagsBar() {
const tags = extractTags();
const el = document.getElementById('tags-bar');
if (tags.length === 0) { el.classList.add('hidden'); return; }
el.classList.remove('hidden');
// Show at most 12 tags, each as a tappable button
el.innerHTML = tags.slice(0, 12).map(tag =>
`<button class="tag-chip" onclick="insertTag('${tag}')">${tag}</button>`
).join('');
}
/**
* addThought() — Takes the text from the thought input, adds it to the
* thoughts array, clears the input, and re-renders the list.
*/
function addThought() {
if (listening && listenTarget === 'thought') stopMic(); // [v2] prevent ghost re-fill
const inp = document.getElementById('thought-input');
const t = inp.value.trim();
if (!t) return;
thoughts.push(t);
inp.value = '';
autoGrow(inp);
inp.focus();
renderThoughts();
}
/**
* removeThought(i) — Removes the thought at position i from the current entry.
* .splice(i, 1) means: at position i, remove 1 element.
*/
function removeThought(i) {
thoughts.splice(i, 1);
renderThoughts();
}
/**
* insertTag(tag) — When you tap a tag chip, it appends that #tag
* to whatever you're currently typing in the thought input.
*/
function insertTag(tag) {
const inp = document.getElementById('thought-input');
inp.value = (inp.value ? inp.value + ' ' : '') + tag + ' ';
inp.focus();
}
/**
* saveEntry() — Saves the current entry (date + context + thoughts)
* to the entries array and to localStorage.
*
* unshift() adds to the BEGINNING of the array (so newest entries appear first).
* After saving, it clears the current composition and refreshes the UI.
*/
function saveEntry() {
if (listening) stopMic(); // [v2] commit voice text before saving
if (thoughts.length === 0) { flash('Add at least one thought'); return; }
const {date, time} = now();
const ctx = document.getElementById('ctx-input').value.trim();
// Create an entry object with all the data
entries.unshift({
id: Date.now(), // unique ID based on current timestamp (milliseconds)
date, // shorthand for date: date
time,
context: ctx,
thoughts: [...thoughts] // [...x] creates a copy of the array
});
persist(); // save to localStorage
// Reset the capture form
thoughts = [];
document.getElementById('ctx-input').value = '';
document.getElementById('thought-input').value = '';
renderThoughts();
renderTagsBar(); // update tag suggestions (new tags might have been added)
updateLogCount(); // update "log (N)" in the tab
flash('Saved');
}
/**
* updateLogCount() — Updates the number shown in the "log (N)" tab button.
*/
function updateLogCount() {
document.querySelector('[data-view="log"]').textContent = `log (${entries.length})`;
}
// ===================================================================
// 6. LOG FUNCTIONS (viewing, exporting, deleting saved entries)
// ===================================================================
/**
* renderLog() — Draws all saved entries as cards in the log view.
* Each card shows the date, context, thoughts, and a delete button.
*/
function renderLog() {
const container = document.getElementById('entries-container');
const toolbar = document.getElementById('toolbar');
toolbar.classList.toggle('hidden', entries.length === 0);
if (entries.length === 0) {
container.innerHTML = '<p class="empty">nothing here yet. go capture something.</p>';
return;
}
container.innerHTML = entries.map(e => {
if (editingId === e.id) return renderEditForm(e);
return `
<div class="entry">
<div class="entry-head">
<span class="entry-date">[${e.date} ${e.time}]</span>
<div class="entry-actions">
<button class="entry-act" onclick="editEntry(${e.id})">edit</button>
<button class="entry-act danger" onclick="deleteEntry(${e.id})">del</button>
</div>
</div>
${e.context ? `<div class="entry-ctx">@ ${escHtml(e.context)}</div>` : ''}
${e.thoughts.map(t => `<div class="entry-t"><span style="color:var(--ink-dim);font-family:var(--mono)">- </span>${highlightTags(t)}</div>`).join('')}
</div>`;
}).join('');
}
function renderEditForm(e) {
return `
<div class="entry" style="border-color:var(--accent)">
<div class="entry-head">
<span class="entry-date">[${e.date} ${e.time}]</span>
<span style="font-family:var(--mono);font-size:12px;color:var(--accent)">editing</span>
</div>
<div class="edit-form">
<div class="edit-row">
<span class="row-label">@</span>
<input class="edit-input" id="edit-ctx" value="${escHtml(e.context || '')}"
placeholder="where, when, why...">
</div>
${e.thoughts.map((t, i) => `
<div class="edit-row">
<span class="row-label">-</span>
<input class="edit-input edit-thought" value="${escHtml(t)}"
onkeydown="if(event.key==='Enter'){event.preventDefault();addEditThought();}">
<button class="edit-del" onclick="removeEditThought(${i})">×</button>
</div>
`).join('')}
<button class="edit-add" onclick="addEditThought()">+ add thought</button>
<div class="edit-actions">
<button class="edit-save" onclick="saveEdit(${e.id})">Save</button>
<button class="edit-cancel" onclick="cancelEdit()">cancel</button>
</div>
</div>
</div>`;
}
function editEntry(id) {
editingId = id;
renderLog();
const ctxInput = document.getElementById('edit-ctx');
if (ctxInput) ctxInput.focus();
}
function cancelEdit() {
editingId = null;
renderLog();
}
function saveEdit(id) {
const entry = entries.find(e => e.id === id);
if (!entry) return;
const ctxInput = document.getElementById('edit-ctx');
entry.context = ctxInput ? ctxInput.value.trim() : '';
const thoughtInputs = document.querySelectorAll('.edit-thought');
const newThoughts = [];
thoughtInputs.forEach(inp => {
const v = inp.value.trim();
if (v) newThoughts.push(v);
});
if (newThoughts.length === 0) { flash('Keep at least one thought'); return; }
entry.thoughts = newThoughts;
persist();
editingId = null;
renderLog();
flash('Updated');
}
function addEditThought() {
const entry = entries.find(e => e.id === editingId);
if (!entry) return;
syncEditFields(entry);
entry.thoughts.push('');
renderLog();
const inputs = document.querySelectorAll('.edit-thought');
if (inputs.length > 0) inputs[inputs.length - 1].focus();
}
function removeEditThought(i) {
const entry = entries.find(e => e.id === editingId);
if (!entry) return;
syncEditFields(entry);
if (entry.thoughts.length <= 1) { flash('Keep at least one thought'); return; }
entry.thoughts.splice(i, 1);
renderLog();
}
function syncEditFields(entry) {
const ctxInput = document.getElementById('edit-ctx');
if (ctxInput) entry.context = ctxInput.value;
const thoughtInputs = document.querySelectorAll('.edit-thought');
const synced = [];
thoughtInputs.forEach(inp => synced.push(inp.value));
if (synced.length > 0) entry.thoughts = synced;
}
/**
* deleteEntry(id) — Removes a single entry by its unique ID.
* .filter() keeps only the entries whose ID does NOT match.
*/
function deleteEntry(id) {
if (editingId === id) editingId = null;
entries = entries.filter(e => e.id !== id);
persist();
updateLogCount();
renderLog();
}
/**
* copyAll() — Copies ALL entries to clipboard in your .txt format.
*
* navigator.clipboard.writeText() is the modern clipboard API.
* It returns a "Promise" — basically, it tries to copy, and:
* .then() runs if it succeeds
* .catch() runs if it fails (e.g., browser blocks clipboard access)
*
* If clipboard fails, we show the text in a <textarea> so you can
* manually select-all and copy.
*/
function copyAll() {
const txt = entriesToTxt(entries);
const area = document.getElementById('export-area');
navigator.clipboard.writeText(txt).then(() => {
flash('Copied to clipboard');
area.classList.add('hidden');
}).catch(() => {
// Fallback: show text in a text area for manual copying
area.value = txt;
area.classList.remove('hidden');
area.focus();
area.select(); // auto-select all text so you just need Ctrl+C
});
}
/**
* clearAll() — Deletes ALL entries after asking for confirmation.
* confirm() shows a browser popup with OK/Cancel.
*/
function clearAll() {
if (!confirm('Clear all entries?')) return; // user clicked Cancel
entries = [];
editingId = null;
persist();
updateLogCount();
document.getElementById('export-area').classList.add('hidden');
renderLog();
flash('All cleared');
}
// ===================================================================
// 7. VOICE INPUT (speech-to-text via the browser's built-in API)
// ===================================================================
// [v2] Voice accumulator — fixes the interim text contamination bug.
// OLD BUG: baseText = inp.value.trim() was capturing leftover interim text
// on each loop restart, causing garbled duplicates.
// FIX: Track finalized speech separately. Input field is write-only.
let voiceBaseText = ''; // text that existed BEFORE mic was turned on
let voiceFinalizedText = ''; // all finalized speech accumulated across loop restarts
function toggleMic(target) {
if (listening && listenTarget === target) { stopMic(); return; }
// [v2] Stop previous mic if switching targets (context → thought)
if (listening) stopMic();
if (!SpeechRecognition) { flash('Not supported'); return; }
// [v2] Capture input value ONCE before any loop starts
const inp = target === 'context'
? document.getElementById('ctx-input')
: document.getElementById('thought-input');
voiceBaseText = inp.value.trimEnd();
voiceFinalizedText = '';
listening = true;
listenTarget = target;
lastSpeechTime = Date.now();
lastProcessedPhrase = '';
updateMicUI();
runDictationLoop(target);
}
function runDictationLoop(target) {
if (!listening || listenTarget !== target) return;
const r = new SpeechRecognition();
r.lang = micLang;
r.interimResults = true;
r.continuous = false; // [v1.3] Forced false — manual restart loop, proven on Android
const inp = target === 'context'
? document.getElementById('ctx-input')
: document.getElementById('thought-input');
// [v1.3] isFirstResult guards against Android ghost buffer: when a new
// session starts, Android often re-transcribes the last audio chunk,
// producing a duplicate of the previous phrase.
let isFirstResult = true;
r.onresult = (ev) => {
let final = '';
let interim = '';
for (let i = 0; i < ev.results.length; i++) {
const t = ev.results[i][0].transcript;
if (ev.results[i].isFinal) {
const cleaned = cleanTranscript(t);
// [v1.3] Block first-result duplicate from Android ghost buffer
if (isFirstResult && cleaned === lastProcessedPhrase) {
// Skip — this is the ghost replay
} else {
final += cleaned + ' ';
lastProcessedPhrase = cleaned;
}
} else {
interim += t;
}
}
isFirstResult = false;
lastSpeechTime = Date.now();
// [v2] Accumulate finalized text instead of reading back from inp.value
const cleanFinal = final.trim();
if (cleanFinal) {
voiceFinalizedText += (voiceFinalizedText ? ' ' : '') + cleanFinal;
}
// [v2] Render: base + all finalized + interim preview
const parts = [voiceBaseText, voiceFinalizedText].filter(Boolean).join(' ');
inp.value = parts + (interim ? (parts ? ' ' : '') + interim : '');
autoGrow(inp);
};
r.onerror = (e) => {
if (e.error !== 'no-speech' && e.error !== 'network') stopMic();
};
r.onend = () => {
if (listening && listenTarget === target) {
if (Date.now() - lastSpeechTime > 30000) {
stopMic();
flash('Mic stopped (silence)');
return;
}
setTimeout(() => runDictationLoop(target), 50);
}
};
recognition = r;
try { r.start(); } catch { stopMic(); }
}
function stopMic() {
// [v2] Commit finalized text, strip leftover interim
if (listening && listenTarget) {
const inp = listenTarget === 'context'
? document.getElementById('ctx-input')
: document.getElementById('thought-input');
const parts = [voiceBaseText, voiceFinalizedText].filter(Boolean).join(' ');
inp.value = parts;
autoGrow(inp);
}
listening = false;
listenTarget = null;
lastProcessedPhrase = '';
voiceBaseText = '';
voiceFinalizedText = '';
if (recognition) {
recognition.onend = null;
recognition.onerror = null;
try { recognition.stop(); } catch(e){}
}
recognition = null;
updateMicUI();
}
function updateMicUI() {
const micCtx = document.getElementById('mic-ctx');
const micThought = document.getElementById('mic-thought');
const stopIcon = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1a1a17" stroke-width="2.5"><rect x="6" y="6" width="12" height="12" rx="2" fill="#1a1a17"/></svg>';
const micIcon = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#1a1a17" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="12" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="17" x2="12" y2="22"/></svg>';
if(micCtx) {
micCtx.innerHTML = (listening && listenTarget === 'context') ? stopIcon : micIcon;
micCtx.classList.toggle('on', listening && listenTarget === 'context');
}
if(micThought) {
micThought.innerHTML = (listening && listenTarget === 'thought') ? stopIcon : micIcon;
micThought.classList.toggle('on', listening && listenTarget === 'thought');
}
}
// ===================================================================
// 8. INITIALIZATION (runs once when the page loads)
// ===================================================================
/**
* toggleLang() — Switches the voice recognition language between English and Italian.
* Saves the preference to localStorage so it persists across sessions.
*/
function toggleLang() {
if (listening) stopMic(); // [v2] changing language mid-dictation = garbage
micLang = (micLang === 'en-US') ? 'it-IT' : 'en-US';
localStorage.setItem('thought-log-lang', micLang);
updateLangUI();
}
/** Updates the language button text to show the current language */
function updateLangUI() {
const btn = document.getElementById('lang-btn');
btn.textContent = micLang === 'en-US' ? 'EN' : 'IT';
}