Repository navigation
Expand file tree
/
Copy pathrendering.js
More file actions
1339 lines (1113 loc) · 43.7 KB
/
Copy pathrendering.js
File metadata and controls
1339 lines (1113 loc) · 43.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
// Rendering Module for TLNotes - Enhanced Scope Lines Functionality
// Virtual Scrolling Implementation - Unified Notes + Scope Lines
class TimelineVirtualScroller {
constructor(parentContainer, itemHeight = 85, bufferSize = 5) {
this.parentContainer = parentContainer;
this.itemHeight = itemHeight;
this.bufferSize = bufferSize;
this.scrollTop = 0;
this.totalItems = 0;
this.visibleStart = 0;
this.visibleEnd = 0;
this.allNotesData = [];
this.onRenderItems = null;
// Track period notes and their positions for scope lines
this.allPeriodsData = [];
this.onRenderScopeLines = null;
this.init();
}
init() {
console.log("🏗️ Virtual Scroller: Creating unified container");
// Create the main virtual scrolling container
this.scrollContainer = document.createElement('div');
this.scrollContainer.className = 'virtual-timeline-container';
// Create scroll area that holds all virtual elements
this.scrollArea = document.createElement('div');
this.scrollArea.className = 'virtual-scroll-area';
// Create notes section (left side)
this.notesSection = document.createElement('div');
this.notesSection.className = 'virtual-items-section';
this.notesSection.id = 'virtualNotesSection';
// Create scope lines section (right side)
this.scopeSection = document.createElement('div');
this.scopeSection.className = 'virtual-scope-section';
this.scopeSection.id = 'virtualScopeSection';
this.scopeSection.style.left = 'auto'; // Let CSS handle positioning
this.scopeSection.style.right = '0';
// Assemble the structure
this.scrollArea.appendChild(this.notesSection);
this.scrollArea.appendChild(this.scopeSection);
this.scrollContainer.appendChild(this.scrollArea);
// Initially hide - will be shown when enabled
this.scrollContainer.style.display = 'none';
// Add to parent container
this.parentContainer.appendChild(this.scrollContainer);
// Bind scroll handler
this.scrollContainer.addEventListener('scroll', this.handleScroll.bind(this), { passive: true });
console.log("✅ Virtual Scroller: Unified container ready");
}
setData(notes, allPeriods = null) {
console.log(`🚀 Virtual Scroller: Setting ${notes.length} notes and ${allPeriods?.length || 0} periods`);
this.allNotesData = [...notes];
this.totalItems = this.allNotesData.length;
// Set periods if provided, otherwise extract from notes
this.allPeriodsData = allPeriods || notes.filter(note => note.type === 'period');
this.updateTotalHeight();
this.updateVisibleRange();
if (this.onRenderItems) {
this.renderVisibleItems();
}
if (this.onRenderScopeLines) {
this.renderVirtualScopeLines();
}
}
updateTotalHeight() {
const totalHeight = this.totalItems * this.itemHeight;
this.scrollArea.style.height = `${totalHeight}px`;
console.log(`📏 Total virtual height: ${totalHeight}px (${this.totalItems} items)`);
}
handleScroll() {
this.scrollTop = this.scrollContainer.scrollTop;
// Only update if we've scrolled significantly
const newStart = Math.floor(this.scrollTop / this.itemHeight) - this.bufferSize;
if (Math.abs(newStart - this.visibleStart) >= this.bufferSize) {
this.updateVisibleRange();
this.renderVisibleItems();
if (this.onRenderScopeLines) {
this.renderVirtualScopeLines();
}
}
}
updateVisibleRange() {
const containerHeight = this.scrollContainer.clientHeight;
// Calculate visible range with buffer
this.visibleStart = Math.max(0,
Math.floor(this.scrollTop / this.itemHeight) - this.bufferSize
);
this.visibleEnd = Math.min(this.totalItems,
Math.ceil((this.scrollTop + containerHeight) / this.itemHeight) + this.bufferSize
);
console.log(`👁️ Visible range: ${this.visibleStart} to ${this.visibleEnd} (${this.visibleEnd - this.visibleStart} items)`);
}
renderVisibleItems() {
if (!this.onRenderItems) return;
// Get visible items data
const visibleItems = this.allNotesData.slice(this.visibleStart, this.visibleEnd);
// Call external render function with visible items
this.onRenderItems(visibleItems, this.visibleStart, this.itemHeight);
}
renderVirtualScopeLines() {
if (!this.onRenderScopeLines) return;
// Get visible periods data
const visiblePeriods = this.allPeriodsData.slice(this.visibleStart, this.visibleEnd);
// Get current element positions for scope line calculation
const elementPositions = new Map();
for (let i = this.visibleStart; i < this.visibleEnd; i++) {
const note = this.allNotesData[i];
if (note) {
elementPositions.set(note.id, (i - this.visibleStart) * this.itemHeight);
}
}
// Render scope lines with calculated positions
// Pass visiblePeriods, elementPositions, startIndex to match the function signature
this.onRenderScopeLines(visiblePeriods, elementPositions, this.visibleStart);
}
scrollToIndex(index, offset = 0) {
const scrollTop = (index * this.itemHeight) + offset;
this.scrollContainer.scrollTop = scrollTop;
}
scrollToNote(noteId) {
const index = this.allNotesData.findIndex(note => note.id === noteId);
if (index >= 0) {
console.log(`🎯 Scrolling to note ${noteId} at index ${index}`);
this.scrollToIndex(index, -50); // Small offset for better visibility
}
}
show() {
console.log("👁️ Showing virtual scroller");
if (this.scrollContainer) {
this.scrollContainer.style.display = 'flex';
}
if (traditionalTimeline) {
traditionalTimeline.style.display = 'none';
}
}
hide() {
console.log("🙈 Hiding virtual scroller");
if (this.scrollContainer) {
this.scrollContainer.style.display = 'none';
}
if (traditionalTimeline) {
traditionalTimeline.style.display = 'block';
}
}
destroy() {
this.scrollContainer.removeEventListener('scroll', this.handleScroll.bind(this));
if (this.parentContainer.contains(this.scrollContainer)) {
this.parentContainer.removeChild(this.scrollContainer);
}
}
}
// Initialize virtual scroller
let virtualScroller = null;
let traditionalTimeline = null;
let useVirtualScrolling = false;
// Toggle virtual scrolling on/off
function toggleVirtualScrolling() {
useVirtualScrolling = !useVirtualScrolling;
console.log("Virtual scrolling:", useVirtualScrolling ? "ENABLED" : "DISABLED");
renderTimeline();
}
// Initialize virtual scroller when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('DOMContentLoaded', initIcons);
// Get containers
const timelineContainer = document.getElementById("timelineContainer");
traditionalTimeline = document.getElementById("timelineList");
const scopeColumn = document.getElementById("scopeColumn");
// Create virtual scroller instance (disabled by default)
virtualScroller = new TimelineVirtualScroller(timelineContainer, 85, 5);
// Set render callbacks for unified virtual scroller
virtualScroller.onRenderItems = renderVirtualItems;
virtualScroller.onRenderScopeLines = renderVirtualScopeLines;
console.log("🚀 Virtual scrolling system ready - use toggleVirtualScrolling() to enable");
});
// Scope line rendering - THE VITAL FUNCTIONALITY!
function renderScopeLines(allPeriods, elementPositions) {
// Clear container efficiently without innerHTML
while (scopeColumn.firstChild) {
scopeColumn.removeChild(scopeColumn.firstChild);
}
// Clear horizontal lines from timeline container
const timelineContainer = document.getElementById("timelineContainer");
if (timelineContainer) {
const horizontalLines = timelineContainer.querySelectorAll('.scope-line-horizontal');
horizontalLines.forEach(line => {
if (timelineContainer.contains(line)) {
timelineContainer.removeChild(line);
}
});
}
if (allPeriods.length === 0) return;
// Sort periods by start date to handle overlaps properly
const sortedPeriods = allPeriods.sort(
(a, b) => getSortDate(a) - getSortDate(b),
);
sortedPeriods.forEach((period, index) => {
const color = period.color || "#4CAF50";
const startPos = elementPositions.get(period.id);
if (startPos !== undefined) {
const scopeLine = document.createElement("div");
scopeLine.className = "scope-line";
scopeLine.style.backgroundColor = color;
scopeLine.style.top = `${startPos}px`;
scopeLine.style.zIndex = 5 + index; // Layer periods properly
// Calculate height based on period duration and timeline extent
const endDate = getEndDate(period);
let height = 300; // Default height for ongoing periods
if (endDate !== Infinity) {
// Find the last note within this period's timespan
const periodStart = getSortDate(period);
let maxPos = startPos;
elementPositions.forEach((pos, noteId) => {
const note = notes.find((n) => n.id === noteId);
if (note) {
const noteTime = getSortDate(note);
if (
noteTime >= periodStart &&
noteTime <= endDate &&
pos > maxPos
) {
maxPos = pos;
}
}
});
// Include the period note position in max calculation
if (elementPositions.get(period.id) === startPos) {
maxPos = Math.max(maxPos, startPos);
}
height = Math.max(maxPos - startPos + 150, 80);
} else {
// For ongoing periods, extend to bottom of timeline
const maxPos = Math.max(...Array.from(elementPositions.values()));
height = Math.max(maxPos - startPos + 300, 400);
}
scopeLine.style.height = `${height}px`;
// Add start marker
const startMarker = document.createElement("div");
startMarker.className = "scope-marker";
startMarker.style.backgroundColor = color;
startMarker.title = `Period: ${escapeHtml(period.content.substring(0, 30))}...`;
scopeLine.appendChild(startMarker);
// Add end marker if period has ended
if (endDate !== Infinity) {
const endMarker = document.createElement("div");
endMarker.className = "scope-marker";
endMarker.style.backgroundColor = color;
endMarker.style.bottom = "-5px";
endMarker.title = "Period End";
scopeLine.appendChild(endMarker);
scopeLine.classList.add("period-end");
}
scopeLine.classList.add("period-start");
// Add click handler for period info
// Periods: Single click to edit
scopeLine.addEventListener("click", (e) => {
e.stopPropagation();
openModal(period.id);
});
scopeColumn.appendChild(scopeLine);
// Add horizontal extensions to span across the timeline
if (timelineContainer) {
// Start horizontal line
const startHorizontal = document.createElement("div");
startHorizontal.className = "scope-line-horizontal";
startHorizontal.style.position = "absolute";
startHorizontal.style.top = `${startPos}px`;
startHorizontal.style.left = "0";
startHorizontal.style.right = "60px";
startHorizontal.style.height = "2px";
startHorizontal.style.backgroundColor = color;
startHorizontal.style.opacity = "0.5";
startHorizontal.style.borderRadius = "2px";
startHorizontal.style.boxShadow = "0 1px 3px rgba(0, 0, 0, 0.2)";
startHorizontal.style.zIndex = "2";
startHorizontal.title = `Period: ${escapeHtml(period.content.substring(0, 30))}...`;
timelineContainer.appendChild(startHorizontal);
// End horizontal line if period has ended
if (endDate !== Infinity) {
const endHorizontal = document.createElement("div");
endHorizontal.className = "scope-line-horizontal";
endHorizontal.style.position = "absolute";
endHorizontal.style.top = `${startPos + height}px`;
endHorizontal.style.left = "0";
endHorizontal.style.right = "60px";
endHorizontal.style.height = "2px";
endHorizontal.style.backgroundColor = color;
endHorizontal.style.opacity = "0.5";
endHorizontal.style.borderRadius = "2px";
endHorizontal.style.boxShadow = "0 1px 3px rgba(0, 0, 0, 0.2)";
endHorizontal.style.zIndex = "2";
endHorizontal.title = "Period End";
timelineContainer.appendChild(endHorizontal);
}
}
}
});
}
// Virtual scrolling render callback
function renderVirtualItems(visibleNotes, startIndex, itemHeight) {
console.log("🚀 Rendering virtual items:", visibleNotes.length, "from index", startIndex);
// Clear notes section
while (virtualScroller.notesSection.firstChild) {
virtualScroller.notesSection.removeChild(virtualScroller.notesSection.firstChild);
}
let currentPosition = startIndex * itemHeight;
let elementPositions = new Map(); // Global for each virtual render
// Render all visible notes first
visibleNotes.forEach((note, index) => {
const li = createVirtualNoteLi(note);
li.style.position = "absolute";
li.style.top = `${index * itemHeight}px`;
li.style.width = "100%";
li.style.left = "0";
li.style.right = "80px"; // Leave space for scope lines
virtualScroller.notesSection.appendChild(li);
});
console.log("✅ Virtual render complete");
console.log("✅ Virtual render complete");
}
// Create virtual note list item (optimized)
function createVirtualNoteLi(note) {
const li = document.createElement("li");
li.className = "note-item virtual-item";
li.setAttribute("data-note-id", note.id);
li.style.left = "0";
li.style.right = "0";
const contentDiv = document.createElement("div");
contentDiv.className = "content";
const noteContent = document.createElement("div");
noteContent.className = "note-content";
noteContent.textContent = note.content.length > 100
? note.content.substring(0, 100) + "..."
: note.content;
contentDiv.appendChild(noteContent);
// Minimal footer with conditional timestamp based on tags
const footer = document.createElement("div");
footer.className = "footer";
// Only show timestamp for notes without tags (to reduce clutter)
const noteHasTags = note.tags && note.tags.length > 0;
if (!noteHasTags) {
const timestamp = document.createElement("span");
const createdTime = new Date(note.created);
timestamp.textContent = createdTime.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
footer.appendChild(timestamp);
}
contentDiv.appendChild(footer);
li.appendChild(contentDiv);
// Enhanced gesture handling for virtual items
// Desktop: Double click to edit
li.addEventListener("dblclick", (e) => {
e.stopPropagation();
console.log("Virtual item double-clicked:", note.id);
if (typeof window !== 'undefined' && window.openModal) {
window.openModal(note.id);
}
});
// Mobile: Enhanced touch gestures for virtual items
let lastVirtualTapTime = 0;
let virtualTapCount = 0;
let virtualPressTimer;
li.addEventListener("touchstart", (e) => {
if (e.target.classList && e.target.classList.contains("tag")) return;
console.log("Virtual touch start detected on note:", note.id);
if (virtualPressTimer) clearTimeout(virtualPressTimer);
virtualPressTimer = setTimeout(() => {
clearTimeout(virtualPressTimer);
virtualTapCount = 0;
if (typeof window !== 'undefined' && window.openModal) {
console.log("Virtual long press triggered on note:", note.id);
window.openModal(note.id);
}
}, 750);
});
li.addEventListener("touchend", (e) => {
if (e.target.classList && e.target.classList.contains("tag")) return;
console.log("Virtual touch end - checking for double tap");
clearTimeout(virtualPressTimer);
const currentTime = new Date().getTime();
const timeDiff = currentTime - lastVirtualTapTime;
if (timeDiff < 300 && timeDiff > 50) {
virtualTapCount++;
} else {
virtualTapCount = 1;
}
lastVirtualTapTime = currentTime;
if (virtualTapCount === 2) {
console.log("Virtual double tap detected on note:", note.id);
e.preventDefault();
virtualTapCount = 0;
if (typeof window !== 'undefined' && window.openModal) {
window.openModal(note.id);
}
}
});
li.addEventListener("touchmove", () => {
console.log("Virtual touch move - clearing press timer");
clearTimeout(virtualPressTimer);
});
li.addEventListener("contextmenu", (e) => {
e.preventDefault();
});
return li;
}
// Virtual scope lines rendering - INTEGRATED WITH VIRTUAL CANVAS
function renderVirtualScopeLines(visiblePeriods, elementPositions, startIndex) {
console.log("🎯 Virtual scope lines:", visiblePeriods.length, "periods");
// Clear existing scope lines
while (virtualScroller.scopeSection.firstChild) {
virtualScroller.scopeSection.removeChild(virtualScroller.scopeSection.firstChild);
}
if (visiblePeriods.length === 0) {
console.log("📍 No periods to render in virtual mode");
return;
}
// Create unified virtual scope canvas
const scopeCanvas = document.createElement("div");
scopeCanvas.style.position = "relative";
scopeCanvas.style.width = "100%";
scopeCanvas.style.height = "800px"; // Match container height
// Track period notes and their virtual positions
visiblePeriods.forEach((period, index) => {
// Add safety check for period.content
if (!period || !period.content) {
console.warn("⚠️ Skipping invalid period:", period);
return;
}
console.log(`🎨 Virtual rendering period: ${period.content.substring(0, 30)}...`);
const color = period.color || "#4CAF50";
const startPos = elementPositions.get(period.id);
if (startPos !== undefined) {
// Create virtual scope line
const scopeLine = document.createElement("div");
scopeLine.className = "scope-line virtual-scope-line";
scopeLine.style.position = "absolute";
scopeLine.style.left = "4px";
scopeLine.style.width = "3px";
scopeLine.style.backgroundColor = color;
scopeLine.style.top = `${startPos}px`;
scopeLine.style.zIndex = 5 + index;
// Calculate height for virtual scrolling (simplified)
const virtualHeight = Math.min(200, 85 * 3); // Max 3 items height
scopeLine.style.height = `${virtualHeight}px`;
// Add start marker
const startMarker = document.createElement("div");
startMarker.className = "scope-marker virtual-marker";
startMarker.style.position = "absolute";
startMarker.style.width = "10px";
startMarker.style.height = "10px";
startMarker.style.borderRadius = "50%";
startMarker.style.border = "2px solid white";
startMarker.style.backgroundColor = color;
startMarker.style.left = "-3px";
startMarker.style.top = "-5px";
startMarker.style.boxShadow = "0 1px 3px rgba(0, 0, 0, 0.3)";
startMarker.title = `Period: ${period.content.substring(0, 30)}...`;
scopeLine.appendChild(startMarker);
// Add click handler
scopeLine.addEventListener("click", (e) => {
e.stopPropagation();
openModal(period.id);
});
scopeCanvas.appendChild(scopeLine);
}
});
virtualScroller.scopeSection.appendChild(scopeCanvas);
console.log("✅ Virtual scope lines rendered");
}
// Timeline rendering (optimized for performance)
function renderTimeline() {
console.log("🎬 RenderTimeline called, virtual:", useVirtualScrolling);
// Clear containers efficiently without innerHTML
while (timelineList.firstChild) {
timelineList.removeChild(timelineList.firstChild);
}
while (scopeColumn.firstChild) {
scopeColumn.removeChild(scopeColumn.firstChild);
}
// Apply filters
let filtered = [...notes];
// Apply type filters
if (activeTypeFilters && activeTypeFilters.length > 0) {
filtered = filtered.filter((note) => activeTypeFilters.includes(note.type));
}
if (activeTagFilters.length > 0) {
filtered = filtered.filter((note) =>
activeTagFilters.every((tag) => note.tags && note.tags.includes(tag)),
);
}
if (currentSearch) {
const searchLower = currentSearch.toLowerCase();
filtered = filtered.filter(
(note) =>
note.content.toLowerCase().includes(searchLower) ||
(note.tags &&
note.tags.some((tag) => tag.toLowerCase().includes(searchLower))),
);
}
if (filtered.length === 0) {
noEvents.innerHTML =
activeTagFilters.length > 0 || currentSearch
? "No notes match your filters"
: "No Notes Yet<br>Start by adding your first note below";
noEvents.style.display = "block";
timelineContainer.style.display = "none";
return;
}
noEvents.style.display = "none";
timelineContainer.style.display = "flex";
// Use traditional or virtual rendering
if (useVirtualScrolling && virtualScroller) {
console.log("🚀 Using virtual scrolling");
// Virtual scrolling mode
filtered.sort(compareNotes);
// Update virtual scroller with filtered data
virtualScroller.setData(filtered);
// Toggle visibility - ensure virtual container is shown and traditional is hidden
if (traditionalTimeline) traditionalTimeline.style.display = "none";
if (virtualScroller && virtualScroller.scrollContainer) {
virtualScroller.scrollContainer.style.display = "block";
}
// Make sure timelineContainer shows the virtual scroller
if (timelineContainer) {
timelineContainer.style.display = "flex";
}
} else {
console.log("💻 Using traditional rendering");
// Traditional rendering mode
if (virtualScroller && virtualScroller.scrollContainer) {
virtualScroller.scrollContainer.style.display = "none";
}
if (traditionalTimeline) traditionalTimeline.style.display = "block";
// Sort notes
filtered.sort(compareNotes);
let currentYear = null;
let currentMonth = null;
let currentWeek = null;
let currentDay = null;
let elementPositions = new Map();
let currentPosition = 0;
filtered.forEach((note, index) => {
const sortTime = getSortDate(note);
const d = new Date(sortTime);
const y = d.getFullYear();
const m = d.getMonth();
const w = getWeek(sortTime);
const dayStr = d.toLocaleDateString();
// Year headers
if (y !== currentYear) {
const header = document.createElement("div");
header.className = "group-header year-header";
header.innerHTML = `<div class="header-text">${y}</div>`;
timelineList.appendChild(header);
currentPosition += 65;
currentYear = y;
currentMonth = null;
currentWeek = null;
currentDay = null;
}
// Month headers
if (m !== currentMonth) {
const monthName = d.toLocaleDateString("default", { month: "long" });
const header = document.createElement("div");
header.className = "group-header month-header";
header.innerHTML = `<div class="header-text">${monthName} ${y}</div>`;
timelineList.appendChild(header);
currentPosition += 55;
currentMonth = m;
currentWeek = null;
currentDay = null;
}
// Day headers
if (dayStr !== currentDay) {
const d = new Date(sortTime);
const dayName = d.toLocaleDateString("default", { weekday: "long" });
const header = document.createElement("div");
header.className = "group-header day-header";
header.innerHTML = `<div class="header-text">${dayName}, ${dayStr}</div>`;
timelineList.appendChild(header);
currentPosition += 45;
currentDay = dayStr;
}
const li = createNoteLi(note);
timelineList.appendChild(li);
// Store position for scope line rendering
elementPositions.set(note.id, currentPosition);
currentPosition += 85; // Approximate height of note item
});
// Render scope lines after all elements are positioned
// Get all period notes for scope line rendering
const allPeriods = filtered.filter((note) => note.type === "period");
renderScopeLines(allPeriods, elementPositions);
}
renderTagFilters();
// Auto-scroll to last added note (only for traditional mode)
if (lastAddedNoteId && !useVirtualScrolling) {
scrollToNote(lastAddedNoteId);
lastAddedNoteId = null;
}
// Virtual scroll handling - use requestAnimationFrame to ensure DOM is updated
if (useVirtualScrolling && virtualScroller) {
if (lastAddedNoteId) {
// New note: scroll to it
requestAnimationFrame(() => {
virtualScroller.scrollToNote(lastAddedNoteId);
lastAddedNoteId = null;
savedScrollPosition = null; // Clear saved position for new notes
});
} else if (savedScrollPosition !== null) {
// Edit/save/tag operation: restore user's position AFTER DOM is updated
requestAnimationFrame(() => {
console.log("📍 Restoring virtual scroll position:", savedScrollPosition);
virtualScroller.scrollContainer.scrollTop = savedScrollPosition;
savedScrollPosition = null; // Clear after use
});
}
} else {
// Traditional scroll handling - use requestAnimationFrame to ensure DOM is updated
const timelineContainer = document.getElementById("timelineContainer");
if (timelineContainer) {
if (lastAddedNoteId) {
// Auto-scroll to newly added note (don't clear savedScrollPosition here)
requestAnimationFrame(() => {
if (typeof scrollToNote !== 'undefined') {
// Don't auto-scroll if we have a saved position from edit operations
if (savedScrollPosition === null) {
scrollToNote(lastAddedNoteId);
}
}
lastAddedNoteId = null;
});
} else if (savedScrollPosition !== null) {
// Edit/save/tag operation: restore user's position AFTER DOM is updated
// Use multiple requestAnimationFrame layers for ULTRA reliability
requestAnimationFrame(() => {
requestAnimationFrame(() => {
console.log("📍 Restoring traditional scroll position:", savedScrollPosition);
timelineContainer.scrollTop = savedScrollPosition;
// Verify and auto-repair if position was overridden
setTimeout(() => {
if (timelineContainer && Math.abs(timelineContainer.scrollTop - savedScrollPosition) > 10) {
console.warn("⚠️ Scroll position overridden in renderTimeline, re-applying...");
timelineContainer.scrollTop = savedScrollPosition;
// Final verification
setTimeout(() => {
if (Math.abs(timelineContainer.scrollTop - savedScrollPosition) < 10) {
console.log("✅ Final scroll position confirmed:", timelineContainer.scrollTop);
} else {
console.error("❌ Scroll position still inconsistent");
}
}, 100);
}
}, 100);
});
savedScrollPosition = null; // Clear after restoration
});
}
}
}
}
// Create note list item
function createNoteLi(note) {
const li = document.createElement("li");
li.className = "note-item";
li.setAttribute("data-note-id", note.id);
const contentDiv = document.createElement("div");
contentDiv.className = "content";
const noteContent = document.createElement("div");
noteContent.className = "note-content";
// Apply search highlighting if needed
if (currentSearch) {
noteContent.innerHTML = highlightSearch(note.content, currentSearch);
} else {
noteContent.textContent = note.content;
}
contentDiv.appendChild(noteContent);
// Calculate date string for footer
let dateStr = "";
if (note.type === "event" && note.date) {
dateStr = formatPartialDate(note.date);
} else if (note.type === "period" && note.date) {
const beginStr = formatPartialDate(note.date.begin) || "Beginning";
const endStr = formatPartialDate(note.date.end) || "Ongoing";
dateStr = `From ${beginStr} to ${endStr}`;
} else if (note.date && note.type === "note") {
dateStr = formatPartialDate(note.date);
}
// Add footer with consistent right-aligned type label
const footer = document.createElement("div");
footer.className = "footer";
// Left side content
const leftContent = document.createElement("div");
leftContent.className = "footer-left-content";
// Only show timestamp for notes without tags (to reduce clutter)
const noteHasTags = note.tags && note.tags.length > 0;
if (!noteHasTags) {
const timestamp = document.createElement("span");
const createdTime = new Date(note.created);
timestamp.textContent = createdTime.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
leftContent.appendChild(timestamp);
}
// Add date if present
if (dateStr) {
const dateRow = document.createElement("div");
dateRow.className = "footer-date-row";
dateRow.textContent = dateStr;
leftContent.appendChild(dateRow);
}
// Add tags if present
if (note.tags && note.tags.length > 0) {
const tagsRow = document.createElement("div");
tagsRow.className = "footer-tags-row";
note.tags.forEach((tag) => {
const tagSpan = document.createElement("span");
tagSpan.className = "tag";
tagSpan.textContent = tag;
tagSpan.addEventListener("click", (e) => {
e.stopPropagation();
toggleTagFilter(tag);
});
tagsRow.appendChild(tagSpan);
});
leftContent.appendChild(tagsRow);
}
footer.appendChild(leftContent);
// Right side - always the type label
const typeLabel = document.createElement("span");
typeLabel.className = `type-label ${note.type}`;
const typeIcons = {
period: "fas fa-arrows-alt-h",
event: "fas fa-star",
note: "fas fa-sticky-note",
draft: "fas fa-edit",
};
typeLabel.innerHTML = `${getIcon(typeIcons[note.type] || "fas fa-file-text")} ${escapeHtml(note.type.charAt(0).toUpperCase() + note.type.slice(1))}`;
footer.appendChild(typeLabel);
contentDiv.appendChild(footer);
li.appendChild(contentDiv);
// Add menu button
const menuBtn = document.createElement("button");
menuBtn.className = "menu-btn";
menuBtn.innerHTML = getIcon("fas fa-ellipsis-v");
menuBtn.onclick = (e) => {
e.stopPropagation();
openModal(note.id);
};
li.appendChild(menuBtn);
// Add swipe actions for mobile
addSwipeActions(li, note.id);
// Enhanced gesture handling for both desktop and mobile
let clickCount = 0;
let clickTimer;
let touchCount = 0;
let touchTimer;
// Add debugging
console.log("Adding enhanced gesture handlers for note:", note.id);
// Desktop: Double click to edit
li.addEventListener("dblclick", (e) => {
if (e.target.classList.contains("tag")) return;
console.log("Double click detected on note:", note.id);
e.preventDefault();
// Direct call - bypass CSP issues entirely
console.log("Direct openModal call");
try {
// Create a custom event handler that isn't subjected to CSP
const customEvent = new CustomEvent('directOpenModal', {
detail: { noteId: note.id }
});
li.dispatchEvent(customEvent);
} catch (error) {
console.error("Custom event failed, trying window.openModal:", error);
try {
window.openModal(note.id);
} catch (err) {
console.error("window.openModal failed too:", err);
// Last resort: try the csr-safe way by using the menu button differently
const menuBtn = li.querySelector('.menu-btn');
if (menuBtn) {
// Create a new button with a safe onclick handler
const tempBtn = document.createElement('button');
tempBtn.style.display = 'none';
tempBtn.onclick = () => openModal(note.id);
menuBtn.parentNode.appendChild(tempBtn);
setTimeout(() => {
tempBtn.click();
menuBtn.parentNode.removeChild(tempBtn);
}, 0);
}
}
}
});
// Custom event listener for the direct call
li.addEventListener('directOpenModal', (e) => {
console.log("Received direct open modal event for:", e.detail.noteId);
openModal(e.detail.noteId);
});
// Alternate: Single click with shift key (easier to test)
li.addEventListener("click", (e) => {
if (e.target.classList.contains("tag")) return;
if (e.shiftKey) {
console.log("Shift+click detected on note:", note.id);
e.preventDefault();
openModal(note.id);
}
});
// Mobile: Enhanced touch gestures - Long press and Double tap
let pressTimer;
let lastTapTime = 0;
let tapCount = 0;
li.addEventListener("touchstart", (e) => {
if (e.target.classList && e.target.classList.contains("tag")) return;
console.log("Touch start detected on note:", note.id);
// Clear any existing timers
if (pressTimer) clearTimeout(pressTimer);
// Long press timer
pressTimer = setTimeout(() => {
console.log("Long press triggered on note:", note.id);
clearTimeout(pressTimer);
// Reset tap count to avoid double-tap confusion after long press
tapCount = 0;
if (typeof window !== 'undefined' && window.openModal) {
window.openModal(note.id);
}
}, 750); // Increased to 750ms for better usability
});
li.addEventListener("touchend", (e) => {
if (e.target.classList && e.target.classList.contains("tag")) return;
console.log("Touch end - checking for double tap");
clearTimeout(pressTimer);
const currentTime = new Date().getTime();
const timeDiff = currentTime - lastTapTime;
if (timeDiff < 300 && timeDiff > 50) { // Double tap within 300ms, minimum 50ms to prevent double fire
tapCount++;
} else {
tapCount = 1; // Reset tap count
}