-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.js
More file actions
1114 lines (979 loc) · 45.7 KB
/
Copy pathchat.js
File metadata and controls
1114 lines (979 loc) · 45.7 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 chatIsClean = true; // Are there any unsaved changes?
const chat = document.getElementById('chat');
const chatInput = document.getElementById('chat-input');
const chatContainer = document.getElementById('chat-container');
const sendChatBtn = document.getElementById('send-chat');
const micChatBtn = document.getElementById('mic-chat');
const MAX_TITLE_LENGTH = 100;
const RECENT_FILES = 1;
// Cache of the last Chat.md content we rendered from. renderMessages skips
// work when the file's content hasn't changed.
let lastChatText = null;
function updateChatActionButton() {
if (!sendChatBtn || !micChatBtn) return;
// Don't swap while a recording is in progress - keep the mic visible so
// the user can press it again to stop.
if (micChatBtn.classList.contains('recording')) return;
const hasText = chatInput.value.trim().length > 0;
sendChatBtn.style.display = hasText ? 'flex' : 'none';
micChatBtn.style.display = hasText ? 'none' : 'flex';
}
chatInput.addEventListener('input', () => {
autoResize();
updateChatActionButton();
});
// Initial resize to set proper height
autoResize();
chat.addEventListener('mouseover', function (e) {
const message = e.target.closest('.message');
if (!message) return;
const shown = chat.querySelector('.message.actions-shown');
if (shown && shown !== message) {
shown.classList.remove('actions-shown');
}
});
async function sendToChat() {
let text = chatInput.value.trim();
if (!text) return;
// jj/жж: journal only. jd/жд: journal and keep in chat.
const lower = text.toLowerCase();
const toJournalOnly = lower.endsWith(' jj') || lower.endsWith(' жж');
const toJournalAndChat = lower.endsWith(' jd') || lower.endsWith(' жд');
if (toJournalOnly || toJournalAndChat) {
text = text.slice(0, -3).trim();
await addToJournal(text);
}
if (toJournalOnly) {
chatInput.value = '';
chatIsClean = false;
// Reload from disk so the journal file/dir created by addToJournal
// shows up, then blink its row in the sidebar.
files = await loadLocalFiles(await getRootDirHandle());
renderSidebar('', [`/journal/${todayJournalFilename()}`]);
return;
}
const now = new Date();
const timestamp = now.toLocaleTimeString('en-US', {
hour12: false,
hour: '2-digit',
minute: '2-digit'
});
const formattedContent = `\n- [ ] \`${timestamp}\` ${text}\n`;
await writeAtEnd(CHAT_PATH, formattedContent);
markSyncDirty();
chatInput.value = '';
chatIsClean = false;
updateChatActionButton();
await renderMessages();
const allMessages = chat.querySelectorAll('.message');
if (allMessages.length > 0) {
allMessages[allMessages.length - 1].classList.add('actions-shown');
}
scrollToBottom();
if (toJournalAndChat) {
// Reload from disk so the journal file/dir shows up, then blink its row.
files = await loadLocalFiles(await getRootDirHandle());
renderSidebar('', [`/journal/${todayJournalFilename()}`]);
}
}
// Voice recording. First click starts capture, second click stops, saves to
// media/, and appends a chat message with the audio markdown so the inline
// audio player (fold-image.js) picks it up just like a pasted file.
let chatMediaRecorder = null;
let chatMediaStream = null;
let chatMediaChunks = [];
async function toggleMicRecording() {
const micBtn = document.getElementById('mic-chat');
if (chatMediaRecorder && chatMediaRecorder.state === 'recording') {
chatMediaRecorder.stop();
return;
}
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia({audio: true});
} catch (err) {
logError('Microphone access denied:', err);
alert('Microphone access denied or unavailable: ' + err.message);
return;
}
chatMediaStream = stream;
chatMediaChunks = [];
// Pick a webm-compatible mime if the browser supports it; fall back to
// whatever MediaRecorder picks (Safari hands us mp4 here).
let mimeType = 'audio/webm';
if (!MediaRecorder.isTypeSupported(mimeType)) mimeType = '';
chatMediaRecorder = new MediaRecorder(stream, mimeType ? {mimeType} : undefined);
chatMediaRecorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) chatMediaChunks.push(e.data);
};
chatMediaRecorder.onstop = async () => {
micBtn.classList.remove('recording');
updateChatActionButton();
// Release the mic so the OS indicator clears.
if (chatMediaStream) {
chatMediaStream.getTracks().forEach(t => t.stop());
chatMediaStream = null;
}
if (chatMediaChunks.length === 0) {
chatMediaRecorder = null;
return;
}
const recordedType = chatMediaRecorder.mimeType || 'audio/webm';
const blob = new Blob(chatMediaChunks, {type: recordedType});
chatMediaRecorder = null;
const ext = getImageExtension(recordedType.split(';')[0]);
const now = new Date();
const dd = String(now.getDate()).padStart(2, '0');
const mm = String(now.getMonth() + 1).padStart(2, '0');
const yyyy = now.getFullYear();
const hh = String(now.getHours()).padStart(2, '0');
const mi = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
const fileName = `${dd}.${mm}.${yyyy} ${hh}h${mi}m${ss}s.${ext}`;
try {
const fileHandle = await writeMediaFile(fileName, blob);
if (!fileHandle) {
logError('Failed to save voice message.');
alert('Failed to save voice message.');
return;
}
if (!files['media/']) files['media/'] = {};
files['media/'][fileName] = {
isFile: true,
handle: fileHandle,
lastModified: Date.now(),
imageUrl: URL.createObjectURL(blob),
};
const now = new Date();
const timestamp = now.toLocaleTimeString('en-US', {
hour12: false, hour: '2-digit', minute: '2-digit',
});
const formattedContent = `\n- [ ] \`${timestamp}\` })\n`;
await writeAtEnd(CHAT_PATH, formattedContent);
markSyncDirty();
chatIsClean = false;
await renderMessages();
scrollToBottom();
} catch (err) {
logError('Error saving voice message:', err);
alert('Error saving voice message: ' + err.message);
}
};
chatMediaRecorder.start();
micBtn.classList.add('recording');
}
async function openChat() {
closeChatModal();
chatContainer.style.display = 'flex';
if (currentEditor.path !== CHAT_PATH) {
const state = {path: editor.path};
history.pushState(state, '');
}
currentEditor.path = CHAT_PATH;
const codemirror = document.querySelector('.CodeMirror-wrap');
codemirror.style.display = 'none';
chat.style.display = 'flex';
chatInput.style.display = 'block';
updateChatActionButton();
hideEditor2();
const searchModal = document.getElementById('search');
if (searchModal.style.display === 'none') {
chatInput.focus();
}
isChat = true;
await renderMessages();
scrollToBottom();
}
async function openChatModal() {
chatContainer.classList.add('modal');
chatContainer.style.display = 'flex';
chat.style.display = 'block';
chatInput.style.display = 'block';
updateChatActionButton();
chat.style.display = 'flex';
chatInput.style.display = 'block';
updateChatActionButton();
chatInput.focus();
await renderMessages();
scrollToBottom();
}
function closeChatModal() {
chatContainer.classList.remove('modal');
if (!isChat) {
chatContainer.style.display = 'none';
chat.style.display = 'none';
chatInput.style.display = 'none';
if (sendChatBtn) sendChatBtn.style.display = 'none';
if (micChatBtn) micChatBtn.style.display = 'none';
}
}
async function toggleChatModal() {
if (isChat) {
return;
}
let isChatModal = document.getElementById('chat-container').classList.contains('modal');
if (isChatModal) {
closeChatModal();
} else {
openChatModal();
}
}
async function parseMessagesFromChat() {
const file = await ((await getFileHandle(CHAT_PATH, true)).getFile());
let chat = await file.text();
// Normalize line endings
chat = chat.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const lines = chat.split('\n');
const headerRegex = /^#### /;
// Block start: any `- [ ] ` / `- [x] ` checklist line (timestamp optional).
const timestampRegex = /^- \[[ xX]\] /;
const blocks = [];
let currentBlock = '';
for (const line of lines) {
const isHeader = headerRegex.test(line);
const isTimestamp = timestampRegex.test(line);
if (isHeader || isTimestamp) {
// Save previous block if exists
if (currentBlock.length > 0) {
blocks.push(currentBlock.trim());
currentBlock = '';
}
// Start new block
currentBlock = line;
} else {
// Continue current block
if (currentBlock.length > 0) {
currentBlock += '\n' + line;
}
}
}
// Add final block
if (currentBlock.length > 0) {
blocks.push(currentBlock.trim());
}
// Parse blocks into messages
const messages = [];
let currentDate = null;
// TODO write clearer way
let numblocks = 0
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
// Check if block is a date header
if (block.startsWith('####')) {
currentDate = block.replace(/^#+\s*/, '').trim();
numblocks++;
continue;
}
// Strip optional `- [ ]`/`- [x]` marker, then optional `HH:MM`
// timestamp. Lines without either are not chat entries.
let rest = block;
let mark = '';
const markerMatch = rest.match(/^- \[([ xX])\] /);
if (markerMatch) {
mark = markerMatch[1];
rest = rest.slice(markerMatch[0].length);
}
let timestamp = '';
const tsMatch = rest.match(/^`(\d{2}:\d{2})` /);
if (tsMatch) {
timestamp = tsMatch[1];
rest = rest.slice(tsMatch[0].length);
}
if (mark === '' && timestamp === '') {
continue;
}
const text = rest.trim();
if (text) {
messages.push({
index: i - numblocks,
done: mark === 'x' || mark === 'X',
text,
timestamp,
date: currentDate || new Date().toDateString(),
});
}
}
return { messages, text: chat };
}
async function saveMessagesToChat(messages) {
// Group messages by date
const messagesByDate = {};
messages.forEach(msg => {
const date = msg.date || todayHeader().replace('#### ', '');
if (!messagesByDate[date]) {
messagesByDate[date] = [];
}
messagesByDate[date].push(msg);
});
let content = '';
Object.entries(messagesByDate).forEach(([date, msgs]) => {
if (content) content += '\n';
content += `#### ${date}\n`;
msgs.forEach(msg => {
const tsPart = msg.timestamp ? `\`${msg.timestamp}\` ` : '';
content += `- [${msg.done ? 'x' : ' '}] ${tsPart}${msg.text}\n`;
});
});
await write(CHAT_PATH, content);
markSyncDirty();
lastChatText = content;
}
// Toggle the checkbox marker on a single chat line in place.
// Matches any of the three shapes the line might be in on disk:
// `HH:MM` text (legacy)
// - [ ] `HH:MM` text (new, not done)
// - [x] `HH:MM` text (new, done)
// and rewrites it to the requested done/undone marker.
async function toggleChatMessage(timestamp, text, done) {
const handle = await getFileHandle(CHAT_PATH, true);
const file = await handle.getFile();
let content = await file.text();
const escapeRegex = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const marker = done ? 'x' : ' ';
const re = timestamp
? new RegExp(`^(?:- \\[[ xX]\\] )?\`${escapeRegex(timestamp)}\` ${escapeRegex(text)}\\s*$`, 'm')
: new RegExp(`^- \\[[ xX]\\] ${escapeRegex(text)}\\s*$`, 'm');
const replacement = timestamp
? `- [${marker}] \`${timestamp}\` ${text}`
: `- [${marker}] ${text}`;
if (!re.test(content)) {
logError('toggleChatMessage: line not found', {timestamp, text});
return;
}
content = content.replace(re, replacement);
const writable = await handle.createWritable();
await writable.write(content);
await writable.close();
markSyncDirty();
lastChatText = content;
}
function initChat() {
chatInput.addEventListener('keydown', async function (e) {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
await sendToChat();
autoResize();
}
});
}
function scrollToBottom() {
setTimeout(function () {
chat.scrollTop = chat.scrollHeight;
}, 100);
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Swap media markdown () for an emoji + bare filename
// in chat-message display. Original text stays in `data-text` so the
// move/journal/archive actions still operate on the real markdown.
function prettifyMediaTags(text) {
return text.replace(/!\[[^\]]*\]\(([^)]+)\)/g, (_, path) => {
const filename = path.split('/').pop();
const ext = filename.split('.').pop().toLowerCase();
const emoji = /^(mp3|ogg|oga|weba|wav)$/.test(ext) ? '🎵'
: /^(mp4|webm|mov)$/.test(ext) ? '🎬'
: '🖼️';
return `${emoji} ${filename}`;
});
}
function autoResize() {
if (chatInput.value === '') {
chatInput.style.height = '';
return;
}
chatInput.style.height = '';
if (chatInput.scrollHeight > chatInput.clientHeight) {
chatInput.style.height = Math.min(chatInput.scrollHeight, 250) + 'px';
}
}
function getRecentlyModifiedFiles(n) {
if (files === undefined) return [];
const entries = [];
for (const filename in files) {
const content = files[filename];
if (filename && content && !filename.endsWith('/') &&
![
toFilename(CHAT_PATH),
toFilename(CONFIG_PATH),
toFilename(LATER_PATH),
toFilename(WATCH_PATH),
toFilename(READ_PATH),
toFilename(SHOP_PATH),
].includes(filename)) {
entries.push([filename, content]);
}
}
for (let i = 0; i < entries.length - 1; i++) {
for (let j = i + 1; j < entries.length; j++) {
const aTime = new Date(entries[i][1].lastModified || 0);
const bTime = new Date(entries[j][1].lastModified || 0);
if (aTime < bTime) {
// Swap
const temp = entries[i];
entries[i] = entries[j];
entries[j] = temp;
}
}
}
// Take first 3 and extract filenames
const result = [];
const limit = Math.min(n, entries.length);
for (let i = 0; i < limit; i++) {
result.push(entries[i][0]);
}
return result;
}
chatInput.addEventListener('paste', async (e) => {
const items = e.clipboardData.items;
for (const item of items) {
if (item.kind === 'file' && item.type.startsWith('image/')) {
e.preventDefault();
const file = item.getAsFile();
const fileName = generateSafeFilename(file.name);
const saved = await writeMediaFile(fileName, file);
if (saved) {
const imageMarkdown = `})\n`;
const cursorPos = chatInput.selectionStart;
const textBefore = chatInput.value.substring(0, cursorPos);
const textAfter = chatInput.value.substring(chatInput.selectionEnd);
chatInput.value = textBefore + imageMarkdown + textAfter;
const newCursorPos = cursorPos + imageMarkdown.length;
chatInput.setSelectionRange(newCursorPos, newCursorPos);
chatInput.focus();
autoResize();
updateChatActionButton();
}
break;
}
}
});
function todayJournalFilename() {
const now = new Date();
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
const monthIndex = parseInt(now.toLocaleDateString('en-US', {month: 'numeric',})) - 1;
const year = parseInt(now.toLocaleDateString('en-US', {year: 'numeric'}));
const month = (monthIndex + 1).toString().padStart(2, '0');
return `${year}.${month} ${monthNames[monthIndex]}.md`;
}
function todayHeader(timezone) {
const now = new Date();
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
const dayNames = [
'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'
];
const day = parseInt(now.toLocaleDateString('en-US', {day: 'numeric', timeZone: timezone}));
const monthIndex = parseInt(now.toLocaleDateString('en-US', {month: 'numeric', timeZone: timezone})) - 1;
const year = parseInt(now.toLocaleDateString('en-US', {year: 'numeric', timeZone: timezone}));
const dayIndex = new Date(now.toLocaleDateString('en-US', {timeZone: timezone})).getDay();
return `#### ${day} ${monthNames[monthIndex]}, ${dayNames[dayIndex]}`;
}
async function addToJournal(text) {
text = ucfirst(text.trim());
const journalFilename = todayJournalFilename();
const journalPath = `journal/${journalFilename}`;
const journalHeader = todayHeader().replace(/^#### /, '## ');
await addHeaderAndText(journalPath, journalHeader, text);
}
async function moveFromChat(text, callback) {
await callback(text);
const { messages } = await parseMessagesFromChat();
const filteredMessages = messages.filter(msg => msg.text !== text);
await saveMessagesToChat(filteredMessages);
}
function attachEventListeners() {
document.addEventListener('keydown', function (e) {
if (isMetaKey(e) && e.key === 'a') {
const searchModal = document.getElementById('search');
const moveModal = document.getElementById('move');
if ((searchModal && searchModal.style.display !== 'none' && searchModal.style.display !== '') ||
(moveModal && moveModal.style.display !== 'none' && moveModal.style.display !== '')) {
return;
}
if (e.target.id !== 'chat-input') {
e.preventDefault();
const allMessages = chat.querySelectorAll('.message');
allMessages.forEach(message => message.classList.add('selected'));
}
}
});
chat.addEventListener('mousedown', function (e) {
// Mousedown in empty space (the margins around centered messages, or
// the gaps between them): draw a marquee rectangle and select every
// message it touches.
if (!e.target.closest('.message')) {
if (e.button !== 0) return;
e.preventDefault(); // don't start a native text selection
const startX = e.clientX, startY = e.clientY;
const messages = Array.from(chat.querySelectorAll('.message'));
const additive = isMetaKey(e) || e.shiftKey;
const preselected = additive
? messages.filter(m => m.classList.contains('selected'))
: [];
let rectEl = null;
let dragging = false;
const intersects = (a, b) =>
a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
function handleMouseMove(e) {
const dx = e.clientX - startX, dy = e.clientY - startY;
if (!dragging && Math.abs(dx) < 4 && Math.abs(dy) < 4) return;
dragging = true;
document.getSelection().removeAllRanges();
if (!rectEl) {
rectEl = document.createElement('div');
rectEl.className = 'chat-marquee';
document.body.appendChild(rectEl);
chat.classList.add('block-selecting');
}
const left = Math.min(startX, e.clientX);
const top = Math.min(startY, e.clientY);
const width = Math.abs(dx), height = Math.abs(dy);
rectEl.style.left = left + 'px';
rectEl.style.top = top + 'px';
rectEl.style.width = width + 'px';
rectEl.style.height = height + 'px';
const marquee = {left, top, right: left + width, bottom: top + height};
messages.forEach(m => {
const hit = intersects(marquee, m.getBoundingClientRect());
m.classList.toggle('selected', hit || preselected.includes(m));
});
}
function handleMouseUp() {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
if (rectEl) rectEl.remove();
chat.classList.remove('block-selecting');
// Plain click on empty space (no drag): clear the selection.
if (!dragging && !additive) {
document.querySelectorAll('.message.selected').forEach(m => m.classList.remove('selected'));
}
}
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
return;
}
const message = e.target.closest('.message');
if (!message || e.target.closest('.message-actions')) {
return;
}
if (isMetaKey(e)) {
message.classList.toggle('selected');
return;
}
if (e.shiftKey) {
const selectedMessages = document.querySelectorAll('.message.selected');
if (selectedMessages.length > 0) {
const allMessages = Array.from(chat.querySelectorAll('.message'));
const lastSelected = selectedMessages[selectedMessages.length - 1];
const startIndex = allMessages.indexOf(lastSelected);
const endIndex = allMessages.indexOf(message);
const minIndex = Math.min(startIndex, endIndex);
const maxIndex = Math.max(startIndex, endIndex);
for (let i = minIndex; i <= maxIndex; i++) {
allMessages[i].classList.add('selected');
}
return;
}
}
document.querySelectorAll('.message.selected').forEach(m => m.classList.remove('selected'));
message.classList.add('selected');
let startMessage = message;
let allMessages = Array.from(chat.querySelectorAll('.message'));
const downX = e.clientX;
const downY = e.clientY;
const onLink = e.target.closest('a') !== null;
function handleMouseMove(e) {
const currentMessage = e.target.closest('.message');
if (currentMessage && currentMessage !== startMessage) {
document.getSelection().removeAllRanges();
const startIndex = allMessages.indexOf(startMessage);
const endIndex = allMessages.indexOf(currentMessage);
const minIndex = Math.min(startIndex, endIndex);
const maxIndex = Math.max(startIndex, endIndex);
document.querySelectorAll('.message.selected').forEach(m => m.classList.remove('selected'));
for (let i = minIndex; i <= maxIndex; i++) {
allMessages[i].classList.add('selected');
}
}
}
function handleMouseUp(e) {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
// Select message text on click
const dragged = Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4;
if (dragged || onLink) {
return;
}
const content = startMessage.querySelector('.message-content');
if (!content) {
return;
}
const range = document.createRange();
range.selectNodeContents(content);
const selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
});
chat.addEventListener('click', function (e) {
// Only clear selection if clicking outside messages AND not dragging
if (!e.target.closest('.message') && !e.detail > 1) {
document.querySelectorAll('.message.selected').forEach(m => m.classList.remove('selected'));
}
});
chat.addEventListener('keydown', function (e) {
if (e.key === 'Escape') {
const selectedMessages = chat.querySelectorAll('.message.selected');
if (selectedMessages.length > 0) {
selectedMessages.forEach(message => message.classList.remove('selected'));
e.preventDefault();
e.stopPropagation();
}
}
}, true);
// Add event listeners for editing message content
// chatContainer.querySelectorAll('.message-content[contenteditable]').forEach(element => {
// element.addEventListener('blur', function (e) {
// saveEdit(e.target.dataset.noteId, e.target.textContent);
// e.target.classList.remove('editing');
// });
//
// element.addEventListener('focus', function (e) {
// e.target.classList.add('editing');
// });
//
// element.addEventListener('keydown', function (e) {
// if (e.key === 'Enter' && !e.shiftKey) {
// e.preventDefault();
// e.target.blur();
// }
// if (e.key === 'Escape') {
// e.target.textContent = messages.find(n => n.id == e.target.dataset.noteId).text;
// e.target.blur();
// }
// });
// });
chat.querySelectorAll('.complete-btn').forEach(btn => {
btn.addEventListener('mousedown', function (e) { e.stopPropagation(); });
btn.addEventListener('click', async function (e) {
e.stopPropagation();
const el = btn.closest('.message');
el.classList.toggle('completed');
const done = el.classList.contains('completed');
try {
await toggleChatMessage(el.dataset.timestamp, el.dataset.text, done);
} catch (err) {
logError('Failed to toggle chat line:', err);
el.classList.toggle('completed'); // revert
}
});
});
chat.querySelectorAll('.to-file-btn').forEach(btn => {
btn.addEventListener('click', function (e) {
e.stopPropagation();
const searchModalElement = document.getElementById('search');
if (searchModalElement.style.display !== 'none' && searchModalElement.style.display !== '') {
searchModal.close();
} else {
const message = btn.closest('.message');
// Keep this message's action row visible while the picker is
// open - mouse leaves the bubble as soon as the modal grabs
// focus, otherwise the buttons fade out under the user.
message.classList.add('actions-pinned');
searchModal.open('', e.target, message);
}
});
});
chat.querySelectorAll('.to-journal-btn').forEach(btn => {
btn.addEventListener('click', async function (e) {
e.stopPropagation();
const selectedMessages = document.querySelectorAll('.message.selected');
let msgs = [];
let messagesToRemove = [];
if (selectedMessages.length > 0) {
msgs = Array.from(selectedMessages).map(msg => msg.querySelector('.message-content').dataset.text);
messagesToRemove = selectedMessages;
} else {
msgs = [btn.closest('.message').querySelector('.message-content').dataset.text];
messagesToRemove = [btn.closest('.message')];
}
(async () => {
for (const msg of msgs) {
await moveFromChat(msg, addToJournal);
}
await renderMessages();
// The journal file (or even the journal/ dir) may have
// just been created on disk. addToJournal goes through
// write(), which doesn't touch the in-memory `files` map,
// so reload from disk before rendering or the new entry
// won't show up in the sidebar.
files = await loadLocalFiles(await getRootDirHandle());
renderSidebar('', [`/journal/${todayJournalFilename()}`]);
})();
// TODO only remove if previous is successful
messagesToRemove.forEach(message => {
message.classList.add('removing');
setTimeout(() => {
message.remove();
}, 300);
});
chatInput.focus();
});
});
chat.querySelectorAll('.to-checklist-btn').forEach(btn => {
btn.addEventListener('click', async function (e) {
e.stopPropagation();
const selectedMessages = document.querySelectorAll('.message.selected');
let msgs = [];
let messagesToRemove = [];
if (selectedMessages.length > 0) {
msgs = Array.from(selectedMessages).map(msg => msg.querySelector('.message-content').dataset.text);
messagesToRemove = selectedMessages;
} else {
msgs = [btn.closest('.message').dataset.text];
messagesToRemove = [btn.closest('.message')];
}
(async () => {
for (const msg of msgs) {
await moveFromChat(msg, async msg => {
await addChecklistItem(btn.dataset.checklist, msg)
});
}
// The checklist file (Later.md / Read.md / Watch.md /
// Shop.md) may not exist yet - addChecklistItem creates it
// on disk via write() but doesn't touch the in-memory
// `files` map, so reload before rendering.
files = await loadLocalFiles(await getRootDirHandle());
// dataset.checklist is "Later.md"/"Read.md"/etc.; sidebar
// paths are absolute, so prepend / so the includes() match
// fires.
renderSidebar('', [joinPath('/', btn.dataset.checklist)]);
})();
messagesToRemove.forEach(message => {
message.classList.add('removing');
setTimeout(() => {
message.remove();
}, 300);
});
setTimeout(() => {
renderMessages();
}, 500);
chatInput.focus();
});
});
chat.querySelectorAll('.to-archive-btn').forEach(btn => {
btn.addEventListener('click', async function (e) {
e.stopPropagation();
const selectedMessages = document.querySelectorAll('.message.selected');
let msgs = [];
let messagesToRemove = [];
if (selectedMessages.length > 0) {
msgs = Array.from(selectedMessages).map(msg => msg.querySelector('.message-content').dataset.text);
messagesToRemove = selectedMessages;
} else {
msgs = [btn.closest('.message').querySelector('.message-content').dataset.text];
messagesToRemove = [btn.closest('.message')];
}
const destinations = [];
(async () => {
for (const msg of msgs) {
const [header, body] = extractHeaderAndBody(msg, MAX_TITLE_LENGTH);
const path = joinPath('/', btn.dataset.dir, sanitizeFilename(header)) + '.md';
destinations.push(path);
for (const msg of msgs) {
await moveFromChat(msg, async () => {
await write(path, body)
});
}
}
await renderMessages();
// Reload from disk - write() above creates new files (and
// possibly the archive/ dir itself) without touching the
// in-memory `files` map.
files = await loadLocalFiles(await getRootDirHandle());
renderSidebar('', destinations);
})();
messagesToRemove.forEach(message => {
message.classList.add('removing');
setTimeout(() => {
message.remove();
}, 300);
});
chatInput.focus();
});
});
chat.querySelectorAll('.to-recent-btn').forEach(btn => {
btn.addEventListener('click', async function (e) {
e.stopPropagation();
const selectedMessages = document.querySelectorAll('.message.selected');
let msgs = [];
let messagesToRemove = [];
if (selectedMessages.length > 0) {
msgs = Array.from(selectedMessages).map(msg => msg.querySelector('.message-content').dataset.text);
messagesToRemove = selectedMessages;
} else {
msgs = [btn.closest('.message').querySelector('.message-content').dataset.text];
messagesToRemove = [btn.closest('.message')];
}
const path = btn.dataset.filename;
let callback = async text => await addHeaderAndText(path, todayHeader(), text, true, false);
(async () => {
for (const msg of msgs) {
await moveFromChat(msg, callback);
}
await renderMessages();
// The recent-file may not exist yet (addHeaderAndText goes
// through write() and doesn't touch the in-memory `files`
// map), so reload before rendering. dataset.filename is
// just "Foo.md"; the sidebar walker produces "/Foo.md" -
// normalize so modifiedPaths.includes(path) matches.
files = await loadLocalFiles(await getRootDirHandle());
renderSidebar('', [joinPath('/', path)]);
})();
messagesToRemove.forEach(message => {
message.classList.add('removing');
setTimeout(() => {
message.remove();
}, 300);
});
chatInput.focus();
});
});
// Enable editing on double-click
chat.querySelectorAll('.message-content').forEach(content => {
content.addEventListener('dblclick', function (e) {
e.stopPropagation();
this.style.pointerEvents = 'auto';
this.classList.add('editing');
this.focus();
});
});
}
async function renderMessages() {
const { messages, text } = await parseMessagesFromChat();
if (text === lastChatText) {
log('Chat unchanged, skipping render');
return;
}
lastChatText = text;
log(`Loaded ${messages.length} messages from ${CHAT_PATH}`);
if (messages.length === 0) {
chat.innerHTML = `