-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathapp.js
More file actions
3575 lines (3144 loc) · 152 KB
/
Copy pathapp.js
File metadata and controls
3575 lines (3144 loc) · 152 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
// Toast Notification System
window.Toast = {
container: null,
init() {
this.container = document.getElementById('toast-container');
},
show(message, type = 'info', duration = 3000) {
if (!this.container) this.init();
if (!this.container) return;
const toast = document.createElement('div');
const baseClasses = 'min-w-[280px] max-w-[90vw] px-5 py-3 rounded-2xl shadow-xl text-sm font-medium flex items-center gap-3 transform transition-all duration-300 ease-out';
const typeClasses = {
warning: 'bg-rose-100 dark:bg-rose-900/50 text-rose-700 dark:text-rose-300 border border-rose-200 dark:border-rose-800',
info: 'bg-stone-100 dark:bg-stone-700 text-stone-700 dark:text-stone-200 border border-stone-200 dark:border-stone-600',
success: 'bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300 border border-emerald-200 dark:border-emerald-800'
};
toast.className = `${baseClasses} ${typeClasses[type] || typeClasses.info}`;
toast.innerHTML = `
<svg class="w-5 h-5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
${type === 'warning' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636a9 9 0 010 12.728m0 0l-2.829-2.829m2.829 2.829L21 21M15.536 8.464a5 5 0 010 7.072m0 0l-2.829-2.829m-4.243 2.829a4.978 4.978 0 01-1.414-2.83m-1.414 5.658a9 9 0 01-2.167-9.238m7.824 2.167a1 1 0 111.414 1.414m-1.414-1.414L3 3m8.293 8.293l1.414 1.414"></path>' : ''}
${type === 'success' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>' : ''}
${type === 'info' ? '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>' : ''}
</svg>
<span class="flex-1">${message}</span>
`;
// Start hidden
toast.style.opacity = '0';
toast.style.transform = 'translateY(1rem)';
this.container.appendChild(toast);
// Animate in
requestAnimationFrame(() => {
toast.style.opacity = '1';
toast.style.transform = 'translateY(0)';
});
// Remove after duration
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateY(1rem)';
setTimeout(() => toast.remove(), 300);
}, duration);
}
};
// Form error handler for section creation
window.handleSectionFormError = function(form, xhr) {
// Remove any existing error message
form.querySelector('.error-msg')?.remove();
// Get error text from response
let errorText = xhr.responseText || t('error.generic');
// Create and insert error message
const errorDiv = document.createElement('div');
errorDiv.className = 'error-msg text-sm text-red-500';
errorDiv.textContent = errorText;
form.appendChild(errorDiv);
};
// Check and update all empty states (no sections / no products) and add form visibility
window.checkEmptyStates = function() {
const sl = document.getElementById('sections-list');
if (!sl) return;
const hasSections = sl.querySelector('[data-section-id]') !== null;
const hasItems = sl.querySelector('[id^="item-"]') !== null;
const daf = document.getElementById('desktop-add-form');
const mab = document.getElementById('mobile-add-item-btn');
if (!hasSections) {
// No sections: show "No sections", hide "No products", hide add form
document.getElementById('empty-no-products')?.remove();
if (!document.getElementById('empty-no-sections')) {
sl.insertAdjacentHTML('beforeend',
'<div id="empty-no-sections" class="text-center py-20">' +
'<div class="w-16 h-16 mx-auto mb-4 bg-stone-100 dark:bg-stone-800 rounded-2xl flex items-center justify-center">' +
'<svg class="w-8 h-8 text-stone-400 dark:text-stone-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">' +
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>' +
'</svg></div>' +
'<p class="text-stone-600 dark:text-stone-300 font-medium" x-text="t(\'sections.no_sections\')"></p>' +
'<p class="text-sm text-stone-400 dark:text-stone-500 mt-1" x-text="t(\'sections.add_first_section\')"></p>' +
'<button @click="showManageSections = true" class="mt-4 bg-pink-400 hover:bg-pink-500 text-white px-5 py-2.5 rounded-lg text-sm font-medium transition-colors" x-text="t(\'sections.add_section_btn\')"></button>' +
'</div>'
);
Alpine.initTree(document.getElementById('empty-no-sections'));
}
if (daf) daf.style.display = 'none';
if (mab) mab.style.display = 'none';
} else if (!hasItems) {
// Sections exist but no items: show "No products", hide "No sections", show add form
document.getElementById('empty-no-sections')?.remove();
if (!document.getElementById('empty-no-products')) {
sl.insertAdjacentHTML('beforeend',
'<div id="empty-no-products" class="text-center py-20">' +
'<div class="w-16 h-16 mx-auto mb-4 bg-stone-100 dark:bg-stone-800 rounded-2xl flex items-center justify-center">' +
'<svg class="w-8 h-8 text-stone-400 dark:text-stone-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">' +
'<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>' +
'</svg></div>' +
'<p class="text-stone-600 dark:text-stone-300 font-medium" x-text="t(\'items.no_items\')"></p>' +
'<p class="text-sm text-stone-400 dark:text-stone-500 mt-1" x-text="t(\'items.add_first_item\')"></p>' +
'</div>'
);
Alpine.initTree(document.getElementById('empty-no-products'));
}
if (daf) daf.style.removeProperty('display');
if (mab) mab.style.removeProperty('display');
} else {
// Has sections and items: remove all empty states, show add form
document.getElementById('empty-no-sections')?.remove();
document.getElementById('empty-no-products')?.remove();
if (daf) daf.style.removeProperty('display');
if (mab) mab.style.removeProperty('display');
}
};
// Fuzzy Search Utilities
function normalizePolish(str) {
const map = {
'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n',
'ó': 'o', 'ś': 's', 'ź': 'z', 'ż': 'z',
'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N',
'Ó': 'O', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z'
};
return str.replace(/[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/g, c => map[c] || c);
}
function jaroSimilarity(s1, s2) {
if (s1 === s2) return 1.0;
if (s1.length === 0 || s2.length === 0) return 0.0;
const matchWindow = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
const s1Matches = new Array(s1.length).fill(false);
const s2Matches = new Array(s2.length).fill(false);
let matches = 0;
let transpositions = 0;
for (let i = 0; i < s1.length; i++) {
const start = Math.max(0, i - matchWindow);
const end = Math.min(i + matchWindow + 1, s2.length);
for (let j = start; j < end; j++) {
if (s2Matches[j] || s1[i] !== s2[j]) continue;
s1Matches[i] = true;
s2Matches[j] = true;
matches++;
break;
}
}
if (matches === 0) return 0.0;
let k = 0;
for (let i = 0; i < s1.length; i++) {
if (!s1Matches[i]) continue;
while (!s2Matches[k]) k++;
if (s1[i] !== s2[k]) transpositions++;
k++;
}
return (matches / s1.length + matches / s2.length + (matches - transpositions / 2) / matches) / 3;
}
function jaroWinklerSimilarity(s1, s2) {
const jaro = jaroSimilarity(s1, s2);
let prefixLength = 0;
const maxPrefix = Math.min(4, s1.length, s2.length);
for (let i = 0; i < maxPrefix; i++) {
if (s1[i] === s2[i]) prefixLength++;
else break;
}
return jaro + prefixLength * 0.1 * (1 - jaro);
}
function fuzzyMatchScore(query, text) {
const normQuery = normalizePolish(query.toLowerCase());
const normText = normalizePolish(text.toLowerCase());
// Exact substring match
if (normText.includes(normQuery)) {
const startBonus = normText.startsWith(normQuery) ? 0.1 : 0;
return 0.9 + startBonus;
}
// Word-level match
const words = normText.split(/\s+/);
let bestWordScore = 0;
for (const word of words) {
const score = jaroWinklerSimilarity(normQuery, word);
if (score > bestWordScore) bestWordScore = score;
}
// Full text match
const fullScore = jaroWinklerSimilarity(normQuery, normText);
return Math.max(bestWordScore, fullScore);
}
// Shopping List Alpine.js Component
function shoppingList() {
return {
// WebSocket
ws: null,
connected: false,
reconnectAttempts: 0,
maxReconnectAttempts: 5,
// Offline support
isOnline: navigator.onLine,
processingQueue: false,
offlineStorageReady: false,
// Modals
showManageSections: false,
showAddItem: false,
addMore: false,
addItemQuantity: 0,
addItemQuantityEditing: false,
showEditModal: false,
showSettings: false,
showOfflineModal: false,
showListSwitcher: false,
// Section management
selectMode: false,
selectedSections: [],
// History management
showHistoryModal: false,
historyItems: [],
historySearch: '',
selectedHistoryIds: [],
historySectionMode: localStorage.getItem('history_section_mode') || 'use_first_section',
// Import/Export
showImportPreview: false,
importPreview: {},
importFile: null,
importConflictResolution: 'skip',
// Stats (updated from server)
stats: {
total: window.initialStats?.total || 0,
completed: window.initialStats?.completed || 0,
percentage: window.initialStats?.percentage || 0
},
// Current item for mobile actions
mobileActionItem: null,
// Edit item
editingItem: null,
editItemName: '',
editItemDescription: '',
editItemQuantity: 0,
// Auto-completion
suggestions: [],
showSuggestions: false,
selectedSuggestionIndex: -1,
itemNameInput: '',
_suggestionTimer: null,
// Quick Add inline
quickAddSectionId: null,
quickAddName: '',
quickAddSuggestions: [],
showQuickAddSuggestions: false,
selectedQuickAddSuggestionIndex: -1,
_quickAddSuggestionTimer: null,
// Show/hide completed items (shared state for both desktop + mobile toggle buttons)
showCompleted: document.querySelector('[data-show-completed]')?.dataset?.showCompleted === 'true',
// Search
searchQuery: '',
searchResults: [],
// Track pending local actions to avoid WebSocket race conditions
pendingLocalActions: {},
localActionTimeout: 1000, // ms to ignore WebSocket updates after local action
// Debounce timers for refresh
_refreshListTimer: null,
_refreshStatsTimer: null,
_isRefreshing: false,
_suppressOverlayUntil: 0, // Timestamp until which overlay should be suppressed
_fullRefreshInProgress: false, // Flag to suppress WS-driven refreshes during full refresh
// Return the current list ID extracted from the page URL (e.g. /lists/5 → 5), or null if not on a list page.
currentListId() {
const match = window.location.pathname.match(/^\/lists\/(\d+)/);
return match ? match[1] : null;
},
// Check if add-item form is currently active (to prevent dropdown updates during form use)
_isAddFormActive() {
// Check if mobile add-item modal is open
if (this.showAddItem) {
return true;
}
// Check if desktop form has focus (name input or section select)
const desktopForm = document.getElementById('add-item-form');
if (desktopForm) {
const activeEl = document.activeElement;
if (desktopForm.contains(activeEl)) {
return true;
}
}
return false;
},
async init() {
await this.initOffline();
this.initWebSocket();
this.initCompletedSectionsStore();
this.initLocalActionTracking();
this.cacheSuggestions();
// Listen for mobile action modal
this.$el.addEventListener('open-mobile-action', (e) => {
this.openMobileAction(e.detail);
});
// Keyboard shortcut for save (Cmd+Enter)
document.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && this.editingItem) {
e.preventDefault();
this.submitEditItem();
}
});
// Keyboard shortcut for search (Ctrl+F / Cmd+F)
document.addEventListener('keydown', (e) => {
if (!((e.ctrlKey || e.metaKey) && e.key === 'f')) return;
if (window.innerWidth <= 768) return;
if (this.stats.total <= 5) return;
const activeEl = document.activeElement;
if (activeEl === this.$refs.searchInput) return;
e.preventDefault();
this.$refs.searchInput?.focus();
this.$refs.searchInput?.select();
});
// Initialize mobile drag-and-drop
this.$nextTick(() => {
this.initMobileSortable();
});
// Re-initialize sortable after any remaining HTMX swaps (e.g. section rename)
// NOTE: Alpine.initTree is NOT called here - Alpine's MutationObserver
// auto-initializes new elements. Calling initTree manually causes duplicate
// event handlers (e.g. confirm() dialog appearing multiple times).
const _sortableInitTimers = {};
document.body.addEventListener('htmx:afterSwap', (e) => {
const target = e.detail.target;
const targetId = target?.id || '';
if (target && targetId) {
const isSection = targetId.startsWith('section-') || targetId === 'sections-list';
if (isSection) {
clearTimeout(_sortableInitTimers[targetId]);
_sortableInitTimers[targetId] = setTimeout(() => {
delete _sortableInitTimers[targetId];
const el = document.getElementById(targetId);
if (el) {
const container = el.querySelector('.items-sortable');
if (container) this.initSortableForContainer(container);
}
}, 50);
}
}
});
// Listen for refresh-sections events (fallback)
window.addEventListener('refresh-sections', (e) => {
const fromSectionId = e.detail.fromSectionId;
const toSectionId = e.detail.toSectionId;
const fromSection = document.getElementById(`section-${fromSectionId}`);
const toSection = document.getElementById(`section-${toSectionId}`);
if (fromSection) this.updateSectionCounter(fromSection);
if (toSection) {
toSection.classList.remove('hidden');
this.updateSectionCounter(toSection);
}
this.refreshStats();
});
// Stats refresh triggered by server via HX-Trigger-After-Settle
document.body.addEventListener('statsRefresh', () => {
htmx.trigger('#stats-container', 'refresh');
});
// Full list refresh triggered by server (e.g. template apply)
document.body.addEventListener('refreshList', () => {
this.refreshList();
});
},
initCompletedSectionsStore() {
// Load state from localStorage
try {
const saved = localStorage.getItem('completedSections');
Alpine.store('completedSections', saved ? JSON.parse(saved) : {});
} catch (e) {
Alpine.store('completedSections', {});
}
},
saveCompletedSections() {
try {
const store = Alpine.store('completedSections');
localStorage.setItem('completedSections', JSON.stringify(store));
} catch (e) {
console.error('Failed to save completed sections:', e);
}
},
initLocalActionTracking() {
// Listen for HTMX requests to track local actions
document.body.addEventListener('htmx:beforeRequest', (e) => {
const path = e.detail.requestConfig?.path || '';
// Track reorder actions
if (path.includes('/move-up') || path.includes('/move-down')) {
this.markLocalAction('items_reordered');
}
// Track delete actions
if (e.detail.requestConfig?.verb === 'delete' && path.includes('/items/')) {
this.markLocalAction('item_deleted');
}
// Track uncertain toggle
if (path.includes('/uncertain')) {
this.markLocalAction('item_updated');
}
// Track item toggle (checked/unchecked)
if (path.includes('/toggle')) {
this.markLocalAction('item_toggled');
}
});
},
markLocalAction(actionType) {
this.pendingLocalActions[actionType] = Date.now();
// Auto-clear after timeout
setTimeout(() => {
if (this.pendingLocalActions[actionType] &&
Date.now() - this.pendingLocalActions[actionType] >= this.localActionTimeout) {
delete this.pendingLocalActions[actionType];
}
}, this.localActionTimeout + 100);
},
isLocalAction(actionType) {
const timestamp = this.pendingLocalActions[actionType];
if (timestamp && Date.now() - timestamp < this.localActionTimeout) {
return true;
}
return false;
},
// ===== OFFLINE SUPPORT =====
async initOffline() {
// Initialize IndexedDB
try {
await window.offlineStorage.init();
this.offlineStorageReady = true;
console.log('[App] Offline storage initialized');
// Process any pending offline actions first (retry after reload)
if (this.isOnline) {
const pendingCount = await window.offlineStorage.getQueueLength();
if (pendingCount > 0) {
console.log('[App] Found', pendingCount, 'pending offline actions, syncing...');
await this.processOfflineQueue();
}
this.cacheData();
}
} catch (error) {
console.error('[App] Failed to initialize offline storage:', error);
}
// Online/offline event listeners
window.addEventListener('online', async () => {
// Prevent double execution
if (this._onlineHandled) return;
this._onlineHandled = true;
console.log('[App] Back online');
this.isOnline = true;
// Sync offline actions and refresh (no page reload)
const hadActions = await this.processOfflineQueue();
window.Toast.show(t('offline.back_online'), 'success', 2000);
// Only refresh if no queued actions (processOfflineQueue already refreshes)
if (!hadActions) {
this.refreshList();
this.refreshStats();
}
});
window.addEventListener('offline', () => {
console.log('[App] Gone offline');
this.isOnline = false;
this._onlineHandled = false; // Reset for next online event
});
},
async cacheData() {
if (!this.offlineStorageReady) return;
try {
const response = await fetch('/api/data');
if (response.ok) {
const data = await response.json();
await window.offlineStorage.saveSections(data.sections || []);
await window.offlineStorage.setLastSyncTimestamp(data.timestamp);
console.log('[App] Data cached for offline use');
}
} catch (error) {
console.error('[App] Failed to cache data:', error);
}
},
async queueOfflineAction(action) {
if (!this.offlineStorageReady) {
console.warn('[App] Offline storage not ready, action lost:', action);
return;
}
await window.offlineStorage.queueAction(action);
console.log('[App] Action queued for sync:', action.type);
},
async processOfflineQueue() {
if (this.processingQueue || !this.isOnline || !this.offlineStorageReady) return false;
this.processingQueue = true;
console.log('[App] Processing offline queue...');
try {
const actions = await window.offlineStorage.getQueuedActions();
if (actions.length === 0) {
console.log('[App] No queued actions');
this.processingQueue = false;
return false;
}
console.log('[App] Processing', actions.length, 'queued actions');
for (const action of actions) {
try {
// For all modifying actions - check server version (Last Write Wins)
if (action.type === 'toggle_item' || action.type === 'update_item' || action.type === 'edit_item') {
const itemId = this.extractItemId(action.url);
if (itemId) {
const serverVersion = await this.getItemVersion(itemId);
if (serverVersion && serverVersion.updated_at > action.timestamp) {
// Server has newer version - skip offline action
console.log('[Sync] Server version newer, skipping:', action.type,
'server:', serverVersion.updated_at, 'offline:', action.timestamp);
await window.offlineStorage.clearAction(action.id);
continue;
}
}
}
const fetchOptions = {
method: action.method,
headers: action.headers || {}
};
if (action.body) {
fetchOptions.body = action.body;
}
const response = await fetch(action.url, fetchOptions);
if (response.ok || response.status === 404) {
// Success or item no longer exists - remove from queue
await window.offlineStorage.clearAction(action.id);
console.log('[App] Synced action:', action.type);
} else {
console.error('[App] Failed to sync action:', action.type, response.status);
}
} catch (error) {
console.error('[App] Error syncing action:', action.type, error);
// Keep in queue for retry
}
}
// Refresh data after sync - small delay to ensure server processed all changes
await new Promise(resolve => setTimeout(resolve, 150));
await this.cacheData();
// Refresh sections list using lightweight per-section fetches
this.refreshList(false);
this.refreshStats();
console.log('[App] Offline queue processed, UI refreshed');
return true; // Had queued actions
} finally {
this.processingQueue = false;
}
},
// Get item version from server for conflict resolution
async getItemVersion(itemId) {
try {
const response = await fetch(`/api/item/${itemId}/version`);
if (response.ok) {
return await response.json();
}
} catch (e) {
console.error('[Sync] Failed to get item version:', e);
}
return null;
},
// Extract item ID from URL like /items/123/toggle
extractItemId(url) {
const match = url.match(/\/items\/(\d+)/);
return match ? match[1] : null;
},
async fullRefresh() {
console.log('[App] Full refresh triggered');
// Suppress WS-driven refreshes during full refresh to prevent race conditions
this._fullRefreshInProgress = true;
// Reconnect WebSocket if needed
const wsOpen = this.ws && this.ws.readyState === WebSocket.OPEN;
if (!wsOpen && this.isOnline) {
console.log('[App] Reconnecting');
this.reconnectAttempts = 0;
this.connect();
}
try {
if (this.isOnline) {
const hadQueuedActions = await this.processOfflineQueue();
if (!hadQueuedActions) {
// Smooth per-section update instead of full innerHTML swap
await this.refreshSectionsSmooth();
this.refreshStats();
}
this.cacheData();
}
} finally {
this._fullRefreshInProgress = false;
}
},
async refreshSectionsSmooth() {
// Delegates to refreshList which now uses lightweight per-section fetches
this.refreshList(false);
},
// Wrapper for fetch that queues action when offline
async offlineFetch(url, options, actionType) {
if (this.isOnline) {
return fetch(url, options);
}
// Queue action for later sync
await this.queueOfflineAction({
type: actionType,
url: url,
method: options.method || 'GET',
headers: options.headers || {},
body: options.body || null
});
// Return fake successful response
return { ok: true, offline: true };
},
// ===== WEBSOCKET =====
initWebSocket() {
if (this._wsInitialized) return;
this._wsInitialized = true;
this.connect();
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
this.fullRefresh();
}
});
},
connect() {
// Close existing connection to prevent duplicates
if (this.ws) {
this.ws.onclose = null; // Prevent scheduleReconnect from firing
this.ws.close();
this.ws = null;
}
this.stopPingPong();
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws`;
try {
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('WebSocket connected');
this.connected = true;
this.reconnectAttempts = 0;
};
this.ws.onclose = () => {
console.log('WebSocket disconnected');
this.connected = false;
this.stopPingPong();
this.scheduleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.ws.onmessage = (event) => {
this.handleMessage(event.data);
};
this.startPingPong();
} catch (error) {
console.error('Failed to create WebSocket:', error);
this.scheduleReconnect();
}
},
scheduleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.log('Max reconnection attempts reached');
return;
}
// Clear any pending reconnect timer
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
}
this.reconnectAttempts++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
this._reconnectTimer = setTimeout(() => {
this._reconnectTimer = null;
this.connect();
}, delay);
},
startPingPong() {
this.stopPingPong();
this._pingInterval = setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({ type: 'ping' }));
}
}, 30000);
},
stopPingPong() {
if (this._pingInterval) {
clearInterval(this._pingInterval);
this._pingInterval = null;
}
},
handleMessage(data) {
try {
const message = JSON.parse(data);
console.log('WebSocket message:', message.type);
// Skip refresh-triggering messages during full refresh (background return)
if (this._fullRefreshInProgress && message.type !== 'pong') {
console.log(`[App] Skipping WebSocket message '${message.type}' - full refresh in progress`);
return;
}
const sectionId = message.data?.section_id;
switch (message.type) {
case 'section_created':
// Skip on creating client - HTMX already handled DOM insertion
if (!this.isLocalAction('section_created')) {
// Add new section to DOM without refreshing the entire list
if (message.data?.id) {
const sectionsList = document.getElementById('sections-list');
if (sectionsList && !document.getElementById(`section-${message.data.id}`)) {
fetch(`/sections/${message.data.id}/html`).then(r => {
if (r.ok) return r.text();
}).then(html => {
// Re-check to avoid race condition with concurrent fetches
if (html && sectionsList && !document.getElementById(`section-${message.data.id}`)) {
sectionsList.insertAdjacentHTML('beforeend', html.trim());
window.checkEmptyStates();
this.$nextTick(() => {
const newEl = document.getElementById(`section-${message.data.id}`);
if (newEl) {
const container = newEl.querySelector('.items-sortable');
if (container) this.initSortableForContainer(container);
}
this.initMobileSortable();
});
}
}).catch(e => console.error('[App] Failed to add new section:', e));
}
}
this.refreshSectionSelectsFromServer();
this.refreshManageSectionsModal();
}
break;
case 'section_updated':
if (!this.isLocalAction('section_updated')) {
// Refresh only the changed section, not the entire list
if (message.data?.id) {
this.refreshSection(message.data.id);
}
this.refreshSectionSelectsFromServer();
this.refreshManageSectionsModal();
}
break;
case 'section_deleted':
if (!this.isLocalAction('section_deleted')) {
// Remove section from DOM
if (message.data?.id) {
const delEl = document.getElementById(`section-${message.data.id}`);
if (delEl) {
Alpine.destroyTree(delEl);
delEl.remove();
}
}
window.checkEmptyStates();
this.refreshSectionSelectsFromServer();
this.refreshManageSectionsModal();
this.refreshStats();
}
break;
case 'sections_deleted':
if (!this.isLocalAction('sections_deleted')) {
// Remove multiple sections from DOM
if (message.data?.ids) {
for (const id of message.data.ids) {
const delSecEl = document.getElementById(`section-${id}`);
if (delSecEl) {
Alpine.destroyTree(delSecEl);
delSecEl.remove();
}
}
}
window.checkEmptyStates();
this.refreshSectionSelectsFromServer();
this.refreshManageSectionsModal();
this.refreshStats();
}
break;
case 'sections_reordered':
if (!this.isLocalAction('sections_reordered')) {
// Lightweight reorder - move existing DOM elements
this.reorderSections();
this.refreshManageSectionsModal();
}
break;
case 'item_created':
if (!this.isLocalAction('item_created')) {
const itemId = message.data?.id;
if (itemId && sectionId) {
this.insertRemoteItem(itemId, sectionId);
} else {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
}
this.refreshStats();
break;
case 'item_moved':
if (!this.isLocalAction('item_moved')) {
const fromId = message.data?.from_section_id;
const toId = message.data?.section_id;
if (fromId) this.refreshSection(fromId);
if (toId && toId !== fromId) this.refreshSection(toId);
}
this.refreshStats();
break;
case 'item_deleted':
if (!this.isLocalAction('item_deleted')) {
const delItemId = message.data?.id;
if (delItemId && sectionId) {
this.removeRemoteItem(delItemId, sectionId);
} else {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
}
this.refreshStats();
break;
case 'items_reordered':
if (!this.isLocalAction('items_reordered')) {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
break;
case 'item_toggled':
if (!this.isLocalAction('item_toggled')) {
const togItemId = message.data?.id;
const togCompleted = message.data?.completed;
if (togItemId && sectionId) {
this.toggleRemoteItem(togItemId, sectionId, togCompleted);
} else {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
}
this.refreshStats();
break;
case 'item_updated':
if (!this.isLocalAction('item_updated')) {
const updItemId = message.data?.id;
if (updItemId) {
this.replaceRemoteItem(updItemId);
} else {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
}
this.refreshStats();
break;
case 'template_applied':
// Template adds items to multiple sections - full refresh needed
this.refreshList();
this.refreshStats();
break;
case 'section_sort_changed':
if (!this.isLocalAction('section_sort_changed')) {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
break;
case 'section_items_checked':
if (!this.isLocalAction('section_items_checked')) {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
this.refreshStats();
break;
case 'section_items_unchecked':
if (!this.isLocalAction('section_items_unchecked')) {
sectionId ? this.refreshSection(sectionId) : this.refreshList();
}
this.refreshStats();
break;
case 'completed_items_deleted':
if (!this.isLocalAction('completed_items_deleted')) {
this.removeAllCompletedItemsFromDOM();
}
this.refreshStats();
break;
case 'pong':
break;
case 'list_updated':
if (message.data?.id) {
const currentListId = document.querySelector('[data-list-id]')?.dataset?.listId;
if (String(message.data.id) === currentListId) {
if (!this.isLocalAction('list_updated')) {
if (message.data.show_completed !== undefined) {
this.showCompleted = message.data.show_completed;
}
this.refreshList();
}
}
}
break;
default:
console.log('Unknown message type:', message.type);
}
} catch (error) {
console.error('Failed to parse WebSocket message:', error);
}
},
refreshList(showOverlay = true) {
// Debounce - prevent multiple rapid refreshes
if (this._refreshListTimer) {
clearTimeout(this._refreshListTimer);
}
this._refreshListTimer = setTimeout(async () => {
if (this._isRefreshing) return;
this._isRefreshing = true;