summaryrefslogtreecommitdiff
path: root/web/static/js/app.js
blob: 6646400b64d8be529ce9d73fdda2612e75d1b330 (plain)
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
// Personal Dashboard JavaScript with HTMX Integration

// Constants
const AUTO_REFRESH_INTERVAL = 5 * 60 * 1000; // 5 minutes in milliseconds

// Get CSRF token from body hx-headers attribute
function getCSRFToken() {
    const body = document.body;
    const headers = body.getAttribute('hx-headers');
    if (headers) {
        try {
            const parsed = JSON.parse(headers);
            return parsed['X-CSRF-Token'] || '';
        } catch (e) {
            console.error('Failed to parse CSRF token:', e);
        }
    }
    return '';
}

// Track current active tab (read from URL for state persistence)
const urlParams = new URLSearchParams(window.location.search);
let currentTab = urlParams.get('tab') || 'tasks';
let autoRefreshTimer = null;

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('Dashboard initialized');

    // Set up HTMX event listeners
    setupHtmxListeners();

    // Start auto-refresh
    startAutoRefresh();
});

// HTMX Event Listeners
function setupHtmxListeners() {
    // Before HTMX request
    document.body.addEventListener('htmx:beforeRequest', function(evt) {
        const target = evt.detail.target;
        if (target.id === 'tab-content') {
            // Show loading state
            target.classList.add('opacity-50', 'pointer-events-none');
        }
    });

    // After HTMX request completes
    document.body.addEventListener('htmx:afterRequest', function(evt) {
        const target = evt.detail.target;
        if (target.id === 'tab-content') {
            // Hide loading state
            target.classList.remove('opacity-50', 'pointer-events-none');

            // Update timestamp
            updateLastUpdatedTime();
        }
    });

    // Handle HTMX errors
    document.body.addEventListener('htmx:responseError', function(evt) {
        console.error('HTMX request failed:', evt.detail);
        alert('Failed to load content. Please try again.');

        // Remove loading state
        const target = evt.detail.target;
        if (target) {
            target.classList.remove('opacity-50', 'pointer-events-none');
        }
    });
}

// Tab Management
function setActiveTab(button) {
    // Remove active class from all tabs
    document.querySelectorAll('.tab-button').forEach(tab => {
        tab.classList.remove('tab-button-active');
    });

    // Add active class to clicked tab
    button.classList.add('tab-button-active');

    // Extract tab name from hx-get attribute
    const endpoint = button.getAttribute('hx-get');
    currentTab = endpoint.split('/').pop(); // "tasks" or "notes"

    console.log('Switched to tab:', currentTab);

    // Reset auto-refresh timer when switching tabs
    resetAutoRefresh();
}

// Manual Refresh
async function refreshData() {
    const button = event.target.closest('button');
    const icon = button.querySelector('svg');

    // Show loading state
    button.disabled = true;
    if (icon) icon.classList.add('animate-spin');

    try {
        // Force API refresh (updates cache)
        const refreshResponse = await fetch('/api/refresh', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': getCSRFToken()
            }
        });

        if (!refreshResponse.ok) throw new Error('Refresh failed');

        // Reload current tab from cache
        const tabResponse = await fetch(`/tabs/${currentTab}`);

        if (!tabResponse.ok) throw new Error('Tab reload failed');

        // Get HTML response and update tab content
        const html = await tabResponse.text();
        const tabContent = document.getElementById('tab-content');
        tabContent.innerHTML = html;
        htmx.process(tabContent);

        // Update timestamp
        updateLastUpdatedTime();

        // Reset auto-refresh timer
        resetAutoRefresh();

        console.log('Manual refresh successful');

    } catch (error) {
        console.error('Refresh failed:', error);
        alert('Failed to refresh data. Please try again.');
    } finally {
        // Restore button state
        button.disabled = false;
        if (icon) icon.classList.remove('animate-spin');
    }
}

// Auto-refresh Functions
function startAutoRefresh() {
    if (autoRefreshTimer) {
        clearInterval(autoRefreshTimer);
    }
    autoRefreshTimer = setInterval(autoRefresh, AUTO_REFRESH_INTERVAL);
    console.log('Auto-refresh started (5 min interval)');
}

function resetAutoRefresh() {
    clearInterval(autoRefreshTimer);
    startAutoRefresh();
}

async function autoRefresh() {
    console.log(`Auto-refreshing ${currentTab} tab...`);

    try {
        // Force API refresh (updates cache)
        const refreshResponse = await fetch('/api/refresh', {
            method: 'POST',
            headers: {
                'X-CSRF-Token': getCSRFToken()
            }
        });

        if (!refreshResponse.ok) throw new Error('Refresh failed');

        // Reload current tab from cache
        const tabResponse = await fetch(`/tabs/${currentTab}`);

        if (tabResponse.ok) {
            const html = await tabResponse.text();
            const tabContent = document.getElementById('tab-content');
            tabContent.innerHTML = html;
            htmx.process(tabContent);
            updateLastUpdatedTime();
            console.log('Auto-refresh successful');
        }
    } catch (error) {
        console.error('Auto-refresh failed:', error);
    }
}

// Update Last Updated Time
function updateLastUpdatedTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit'
    });
    const element = document.getElementById('last-updated');
    if (element) {
        element.textContent = timeString;
    }
}

// Filter tasks by status (Phase 2 feature)
function filterTasks(status) {
    console.log('Filter tasks:', status);
    // To be implemented in Phase 2
}

// Toggle task completion (Phase 2 feature)
function toggleTask(taskId) {
    console.log('Toggle task:', taskId);
    // To be implemented in Phase 2
}

// Mobile Swipe Navigation
(function() {
    let touchStartX = 0;
    let touchEndX = 0;
    const SWIPE_THRESHOLD = 50; // Minimum px for a swipe

    // Get ordered list of tab names (main tabs only for swipe)
    const TAB_ORDER = ['timeline', 'shopping', 'tasks', 'planning', 'meals'];

    function handleSwipe() {
        const swipeDistance = touchEndX - touchStartX;

        if (Math.abs(swipeDistance) < SWIPE_THRESHOLD) {
            return; // Not a significant swipe
        }

        const currentIndex = TAB_ORDER.indexOf(currentTab);
        if (currentIndex === -1) return;

        let newIndex;
        if (swipeDistance > 0) {
            // Swiped right -> previous tab
            newIndex = currentIndex - 1;
        } else {
            // Swiped left -> next tab
            newIndex = currentIndex + 1;
        }

        // Bounds check
        if (newIndex < 0 || newIndex >= TAB_ORDER.length) {
            return;
        }

        const newTab = TAB_ORDER[newIndex];
        const tabButton = document.querySelector(`[hx-get="/tabs/${newTab}"]`);

        if (tabButton) {
            console.log(`Swipe navigation: ${currentTab} -> ${newTab}`);
            tabButton.click();
        }
    }

    // Set up touch event listeners on the tab content area
    document.addEventListener('DOMContentLoaded', function() {
        const tabContent = document.getElementById('tab-content');
        if (!tabContent) return;

        tabContent.addEventListener('touchstart', function(e) {
            touchStartX = e.changedTouches[0].screenX;
        }, { passive: true });

        tabContent.addEventListener('touchend', function(e) {
            touchEndX = e.changedTouches[0].screenX;
            handleSwipe();
        }, { passive: true });
    });
})();