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
|
// Personal Dashboard JavaScript with HTMX Integration
// Constants
const AUTO_REFRESH_INTERVAL = 5 * 60 * 1000; // 5 minutes in milliseconds
// Timeline Calendar Initialization
function initTimelineCalendar(calendarId, nowLineId, untimedSectionId) {
const calendar = document.getElementById(calendarId);
if (!calendar) return;
const events = calendar.querySelectorAll('.calendar-event');
const hourHeight = 40;
const startHour = parseInt(calendar.dataset.startHour) || 8;
const nowHour = parseInt(calendar.dataset.nowHour);
const nowMinute = parseInt(calendar.dataset.nowMinute);
// Build event data for overlap detection
const eventData = [];
events.forEach(function(el) {
const hour = parseInt(el.dataset.hour);
const minute = parseInt(el.dataset.minute);
const endHourVal = parseInt(el.dataset.endHour);
const endMinute = parseInt(el.dataset.endMinute);
const startMin = hour * 60 + minute;
let endMin;
if (endHourVal > hour || (endHourVal === hour && endMinute > minute)) {
endMin = endHourVal * 60 + endMinute;
} else {
endMin = startMin + 55;
}
eventData.push({ el, startMin, endMin, column: 0 });
});
// Assign columns for overlapping events
eventData.sort((a, b) => a.startMin - b.startMin);
for (let i = 0; i < eventData.length; i++) {
const ev = eventData[i];
const overlaps = eventData.filter((other, j) =>
j < i && other.endMin > ev.startMin && other.startMin < ev.endMin
);
const usedCols = overlaps.map(o => o.column);
let col = 0;
while (usedCols.includes(col)) col++;
ev.column = col;
}
// Position events with column-based indentation
eventData.forEach(function(ev) {
const el = ev.el;
const hour = parseInt(el.dataset.hour);
const minute = parseInt(el.dataset.minute);
const top = (hour - startHour) * hourHeight + (minute / 60) * hourHeight;
const durationMinutes = ev.endMin - ev.startMin;
const height = Math.max(28, (durationMinutes / 60) * hourHeight - 4);
el.style.top = top + 'px';
el.style.height = height + 'px';
el.style.left = (8 + ev.column * 16) + 'px';
el.style.display = 'block';
// Debounced hover effect (100ms delay)
let hoverTimeout;
el.addEventListener('mouseenter', function() {
hoverTimeout = setTimeout(() => el.classList.add('hover-active'), 100);
});
el.addEventListener('mouseleave', function() {
clearTimeout(hoverTimeout);
el.classList.remove('hover-active');
});
const url = el.dataset.url;
if (url) {
el.style.cursor = 'pointer';
el.addEventListener('click', function(e) {
if (e.target.tagName !== 'INPUT') {
window.open(url, '_blank');
}
});
}
});
// Position the "now" line
if (nowLineId) {
const nowLine = document.getElementById(nowLineId);
if (nowLine && !isNaN(nowHour)) {
const nowTop = (nowHour - startHour) * hourHeight + (nowMinute / 60) * hourHeight;
if (nowTop >= 0) {
nowLine.style.top = nowTop + 'px';
nowLine.style.display = 'block';
}
}
}
// Hide untimed section if empty
if (untimedSectionId) {
const untimedSection = document.getElementById(untimedSectionId);
if (untimedSection && untimedSection.querySelectorAll('.untimed-item').length === 0) {
untimedSection.style.display = 'none';
}
}
}
function initAllTimelineCalendars() {
initTimelineCalendar('today-calendar', 'now-line', 'untimed-section');
initTimelineCalendar('tomorrow-calendar', null, 'tomorrow-untimed-section');
}
// 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') || 'timeline';
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 swap completes - reinitialize JS components
document.body.addEventListener('htmx:afterSwap', function(evt) {
// Initialize timeline calendars if they exist in the swapped content
initAllTimelineCalendars();
});
// 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', 'conditions', '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 });
});
})();
// Agent Access Request Notifications
(function() {
let wsConnection = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5;
const RECONNECT_DELAY_BASE = 1000;
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws/notifications`;
try {
wsConnection = new WebSocket(wsUrl);
wsConnection.onopen = function() {
console.log('WebSocket connected');
reconnectAttempts = 0;
};
wsConnection.onmessage = function(event) {
try {
const msg = JSON.parse(event.data);
if (msg.type === 'agent_request') {
showAgentApprovalModal(msg.payload);
}
} catch (e) {
console.error('Failed to parse WebSocket message:', e);
}
};
wsConnection.onclose = function(event) {
console.log('WebSocket disconnected');
if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
const delay = RECONNECT_DELAY_BASE * Math.pow(2, reconnectAttempts);
reconnectAttempts++;
console.log(`Reconnecting in ${delay}ms (attempt ${reconnectAttempts})`);
setTimeout(connectWebSocket, delay);
}
};
wsConnection.onerror = function(error) {
console.error('WebSocket error:', error);
};
} catch (e) {
console.error('Failed to create WebSocket:', e);
}
}
function showAgentApprovalModal(payload) {
// Remove any existing modal
const existingModal = document.getElementById('agent-approval-modal');
if (existingModal) {
existingModal.remove();
}
// Truncate agent ID for display
const shortAgentId = payload.agent_id.substring(0, 8);
// Determine trust indicator
let trustBadge = '';
let trustClass = '';
switch (payload.trust_level) {
case 'recognized':
trustBadge = 'Recognized';
trustClass = 'bg-green-500';
break;
case 'suspicious':
trustBadge = 'Warning: Different ID';
trustClass = 'bg-yellow-500';
break;
default:
trustBadge = 'New Agent';
trustClass = 'bg-blue-500';
}
// Calculate time remaining
const expiresAt = new Date(payload.expires_at);
const timeRemaining = Math.max(0, Math.floor((expiresAt - new Date()) / 1000));
const modal = document.createElement('div');
modal.id = 'agent-approval-modal';
modal.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50';
modal.innerHTML = `
<div class="bg-gray-900 rounded-lg p-6 max-w-md mx-4 shadow-xl border border-gray-700">
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-white">Agent Access Request</h2>
<span class="px-2 py-1 text-xs rounded ${trustClass} text-white">${trustBadge}</span>
</div>
<div class="mb-6 text-gray-300">
<p class="mb-2"><strong class="text-white">Agent Name:</strong> ${escapeHtml(payload.agent_name)}</p>
<p class="mb-2"><strong class="text-white">Agent ID:</strong> <code class="bg-gray-800 px-1 rounded">${shortAgentId}...</code></p>
<p class="text-sm text-gray-400">Expires in <span id="agent-countdown">${timeRemaining}</span>s</p>
</div>
<div class="flex gap-3">
<button id="agent-approve-btn" class="flex-1 bg-green-600 hover:bg-green-700 text-white py-2 px-4 rounded transition">
Approve
</button>
<button id="agent-deny-btn" class="flex-1 bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded transition">
Deny
</button>
</div>
</div>
`;
document.body.appendChild(modal);
// Countdown timer
const countdownEl = document.getElementById('agent-countdown');
const countdownInterval = setInterval(() => {
const remaining = Math.max(0, Math.floor((expiresAt - new Date()) / 1000));
countdownEl.textContent = remaining;
if (remaining <= 0) {
clearInterval(countdownInterval);
modal.remove();
}
}, 1000);
// Button handlers
document.getElementById('agent-approve-btn').addEventListener('click', async () => {
await handleAgentDecision(payload.request_token, 'approve');
clearInterval(countdownInterval);
modal.remove();
});
document.getElementById('agent-deny-btn').addEventListener('click', async () => {
await handleAgentDecision(payload.request_token, 'deny');
clearInterval(countdownInterval);
modal.remove();
});
// Click outside to dismiss (treat as no action)
modal.addEventListener('click', (e) => {
if (e.target === modal) {
clearInterval(countdownInterval);
modal.remove();
}
});
}
async function handleAgentDecision(requestToken, decision) {
try {
const response = await fetch(`/agent/auth/${decision}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': getCSRFToken()
},
body: JSON.stringify({ request_token: requestToken })
});
if (!response.ok) {
const error = await response.text();
console.error(`Failed to ${decision} agent:`, error);
alert(`Failed to ${decision} agent request. Please try again.`);
} else {
console.log(`Agent request ${decision}d successfully`);
}
} catch (e) {
console.error(`Error during agent ${decision}:`, e);
alert(`Error processing request. Please try again.`);
}
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Initialize WebSocket on page load
document.addEventListener('DOMContentLoaded', function() {
connectWebSocket();
});
})();
|