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

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

// 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 refreshText = document.getElementById('refresh-text');
    const originalText = refreshText.textContent;

    // Show loading state
    button.disabled = true;
    refreshText.innerHTML = `
        <svg class="animate-spin h-5 w-5 inline mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        Refreshing...
    `;

    try {
        // Force API refresh (updates cache)
        const refreshResponse = await fetch('/api/refresh', {
            method: 'POST'
        });

        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;
        refreshText.textContent = originalText;
    }
}

// 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'
        });

        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
}