-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
657 lines (557 loc) · 18.5 KB
/
renderer.js
File metadata and controls
657 lines (557 loc) · 18.5 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
// DOM Elements
const journalView = document.getElementById('journal-view');
const entriesView = document.getElementById('entries-view');
const statsView = document.getElementById('stats-view');
const settingsView = document.getElementById('settings-view');
const newEntryBtn = document.getElementById('new-entry-btn');
const viewEntriesBtn = document.getElementById('view-entries-btn');
const statsBtn = document.getElementById('stats-btn');
const settingsBtn = document.getElementById('settings-btn');
const entryDate = document.getElementById('entry-date');
const journalEditor = document.getElementById('journal-editor');
const saveEntryBtn = document.getElementById('save-entry-btn');
const aiSummarizeBtn = document.getElementById('ai-summarize-btn');
const promptText = document.getElementById('prompt-text');
const newPromptBtn = document.getElementById('new-prompt-btn');
const moodButtons = document.querySelectorAll('.mood');
const entriesListContainer = document.getElementById('entries-list-container');
const searchEntries = document.getElementById('search-entries');
const moodFilter = document.getElementById('mood-filter');
const dateFilterStart = document.getElementById('date-filter-start');
const dateFilterEnd = document.getElementById('date-filter-end');
const applyFiltersBtn = document.getElementById('apply-filters');
// Current state
let currentEntry = {
id: null,
date: new Date().toISOString().split('T')[0],
content: '',
mood: null,
summary: null,
sentiment: null
};
// Set today's date as default
entryDate.value = currentEntry.date;
// Navigation
function showView(viewToShow) {
// Hide all views
document.querySelectorAll('.view').forEach(view => {
view.classList.remove('active');
});
// Show the requested view
viewToShow.classList.add('active');
}
newEntryBtn.addEventListener('click', () => {
resetEntryForm();
showView(journalView);
});
viewEntriesBtn.addEventListener('click', () => {
loadEntries();
showView(entriesView);
});
statsBtn.addEventListener('click', () => {
loadStats();
showView(statsView);
});
settingsBtn.addEventListener('click', () => {
showView(settingsView);
});
// Journal Entry Functions
function resetEntryForm() {
currentEntry = {
id: null,
date: new Date().toISOString().split('T')[0],
content: '',
mood: null,
summary: null,
sentiment: null
};
entryDate.value = currentEntry.date;
journalEditor.value = '';
// Reset mood selection
moodButtons.forEach(btn => {
btn.classList.remove('selected');
});
// Hide AI summary
document.getElementById('ai-summary-container').style.display = 'none';
// Get a new prompt suggestion
generatePromptSuggestion();
}
// Save the current entry
saveEntryBtn.addEventListener('click', async () => {
if (!journalEditor.value.trim()) {
alert('Please write something before saving.');
return;
}
currentEntry.date = entryDate.value;
currentEntry.content = journalEditor.value;
try {
const result = await window.api.saveEntry(currentEntry);
currentEntry.id = result.id;
// Show success message
const successMessage = document.createElement('div');
successMessage.className = 'success-message';
successMessage.textContent = 'Entry saved successfully!';
document.body.appendChild(successMessage);
// Remove message after 3 seconds
setTimeout(() => {
successMessage.remove();
}, 3000);
} catch (error) {
console.error('Error saving entry:', error);
alert('Failed to save entry. Please try again.');
}
});
// Handle mood selection
moodButtons.forEach(btn => {
btn.addEventListener('click', () => {
// Remove selected class from all buttons
moodButtons.forEach(b => b.classList.remove('selected'));
// Add selected class to clicked button
btn.classList.add('selected');
// Update current entry mood
currentEntry.mood = btn.dataset.mood;
});
});
// Date change handler
entryDate.addEventListener('change', () => {
currentEntry.date = entryDate.value;
});
// AI Features
async function generatePromptSuggestion() {
try {
const prompt = await window.api.generatePrompt();
promptText.textContent = prompt || "What's on your mind today?";
} catch (error) {
console.error('Error generating prompt:', error);
promptText.textContent = "What's on your mind today?";
}
}
newPromptBtn.addEventListener('click', generatePromptSuggestion);
aiSummarizeBtn.addEventListener('click', async () => {
if (!journalEditor.value.trim()) {
alert('Please write something before summarizing.');
return;
}
// Show loading state
aiSummarizeBtn.textContent = 'Summarizing...';
aiSummarizeBtn.disabled = true;
try {
// Get summary from AI
const summary = await window.api.summarizeEntry(journalEditor.value);
// Get sentiment analysis
const sentiment = await window.api.analyzeSentiment(journalEditor.value);
// Update current entry
currentEntry.summary = summary;
currentEntry.sentiment = sentiment;
// Display summary
document.getElementById('summary-content').textContent = summary;
// Display sentiment with appropriate emoji
const sentimentEl = document.getElementById('sentiment-analysis');
let sentimentEmoji = '';
switch (sentiment) {
case 'positive':
sentimentEmoji = '😊';
break;
case 'negative':
sentimentEmoji = '😔';
break;
case 'neutral':
sentimentEmoji = '😐';
break;
default:
sentimentEmoji = '❓';
}
sentimentEl.textContent = `Overall sentiment: ${sentiment} ${sentimentEmoji}`;
// Show summary container
document.getElementById('ai-summary-container').style.display = 'block';
} catch (error) {
console.error('Error summarizing entry:', error);
alert('Failed to summarize entry. Please check if Ollama is running.');
} finally {
// Reset button state
aiSummarizeBtn.textContent = 'AI Summarize';
aiSummarizeBtn.disabled = false;
}
});
// Entries List Functions
async function loadEntries(filters = {}) {
try {
const entries = await window.api.getEntries(filters);
// Clear entries container
entriesListContainer.innerHTML = '';
if (entries.length === 0) {
entriesListContainer.innerHTML = '<p class="no-entries">No entries found. Start writing your first journal entry!</p>';
return;
}
// Create entry cards
entries.forEach(entry => {
const entryCard = document.createElement('div');
entryCard.className = 'entry-card';
entryCard.dataset.id = entry.id;
// Format date
const date = new Date(entry.date);
const formattedDate = date.toLocaleDateString('en-US', {
weekday: 'short',
year: 'numeric',
month: 'short',
day: 'numeric'
});
// Get mood emoji
let moodEmoji = '';
switch (entry.mood) {
case 'happy': moodEmoji = '😊'; break;
case 'sad': moodEmoji = '😔'; break;
case 'angry': moodEmoji = '😠'; break;
case 'neutral': moodEmoji = '😐'; break;
case 'excited': moodEmoji = '🤩'; break;
default: moodEmoji = '';
}
// Create preview (first 150 characters)
const preview = entry.content.length > 150
? entry.content.substring(0, 150) + '...'
: entry.content;
entryCard.innerHTML = `
<div class="entry-card-header">
<span class="entry-card-date">${formattedDate}</span>
<span class="entry-card-mood">${moodEmoji}</span>
<span class="entry-delete-btn" data-id="${entry.id}">🗑️</span>
</div>
<p class="entry-card-preview">${preview}</p>
`;
// Add click event to open entry (but not when clicking delete button)
entryCard.addEventListener('click', (e) => {
if (!e.target.classList.contains('entry-delete-btn')) {
openEntry(entry.id);
}
});
entriesListContainer.appendChild(entryCard);
});
// Add event listeners for delete buttons after all entries are added
document.querySelectorAll('.entry-delete-btn').forEach(btn => {
btn.addEventListener('click', async (e) => {
e.stopPropagation(); // Prevent opening the entry
const entryId = btn.dataset.id;
if (confirm('Are you sure you want to delete this entry? This cannot be undone.')) {
try {
await window.api.deleteEntry(entryId);
// Reload entries after deletion
loadEntries({
search: searchEntries.value,
mood: moodFilter.value,
startDate: dateFilterStart.value || null,
endDate: dateFilterEnd.value || null
});
} catch (error) {
console.error('Error deleting entry:', error);
alert('Failed to delete entry. Please try again.');
}
}
});
});
} catch (error) {
console.error('Error loading entries:', error);
entriesListContainer.innerHTML = '<p class="error">Failed to load entries. Please try again.</p>';
}
}
async function openEntry(id) {
try {
const entry = await window.api.getEntryById(id);
if (!entry) {
alert('Entry not found.');
return;
}
// Update current entry
currentEntry = {
id: entry.id,
date: entry.date,
content: entry.content,
mood: entry.mood,
summary: entry.summary,
sentiment: entry.sentiment
};
// Update form
entryDate.value = entry.date;
journalEditor.value = entry.content;
// Update mood selection
moodButtons.forEach(btn => {
btn.classList.remove('selected');
if (btn.dataset.mood === entry.mood) {
btn.classList.add('selected');
}
});
// Show summary if available
if (entry.summary) {
document.getElementById('summary-content').textContent = entry.summary;
// Display sentiment with appropriate emoji
const sentimentEl = document.getElementById('sentiment-analysis');
let sentimentEmoji = '';
switch (entry.sentiment) {
case 'positive':
sentimentEmoji = '😊';
break;
case 'negative':
sentimentEmoji = '😔';
break;
case 'neutral':
sentimentEmoji = '😐';
break;
default:
sentimentEmoji = '❓';
}
sentimentEl.textContent = `Overall sentiment: ${entry.sentiment} ${sentimentEmoji}`;
// Show summary container
document.getElementById('ai-summary-container').style.display = 'block';
} else {
document.getElementById('ai-summary-container').style.display = 'none';
}
// Switch to journal view
showView(journalView);
} catch (error) {
console.error('Error opening entry:', error);
alert('Failed to open entry. Please try again.');
}
}
// Search and filter
searchEntries.addEventListener('input', debounce(() => {
const filters = {
search: searchEntries.value,
mood: moodFilter.value,
startDate: dateFilterStart.value || null,
endDate: dateFilterEnd.value || null
};
loadEntries(filters);
}, 300));
applyFiltersBtn.addEventListener('click', () => {
const filters = {
search: searchEntries.value,
mood: moodFilter.value,
startDate: dateFilterStart.value || null,
endDate: dateFilterEnd.value || null
};
loadEntries(filters);
});
// Stats Functions
async function loadStats() {
try {
const stats = await window.api.getStats();
// Render charts
renderFrequencyChart(stats.entriesByDate);
renderMoodChart(stats.moodDistribution);
renderWordCountChart(stats.wordCountByDate);
} catch (error) {
console.error('Error loading stats:', error);
document.getElementById('stats-view').innerHTML = '<p class="error">Failed to load statistics. Please try again.</p>';
}
}
function renderFrequencyChart(data) {
const ctx = document.getElementById('frequency-chart').getContext('2d');
// Prepare data for Chart.js
const labels = data.map(item => item.date);
const counts = data.map(item => item.count);
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Number of Entries',
data: counts,
backgroundColor: 'rgba(74, 111, 165, 0.7)',
borderColor: 'rgba(74, 111, 165, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
ticks: {
stepSize: 1
}
}
}
}
});
}
function renderMoodChart(data) {
const ctx = document.getElementById('mood-chart').getContext('2d');
// Prepare data for Chart.js
const labels = data.map(item => item.mood);
const counts = data.map(item => item.count);
const backgroundColors = labels.map(mood => {
switch (mood) {
case 'happy': return 'rgba(76, 175, 80, 0.7)';
case 'sad': return 'rgba(33, 150, 243, 0.7)';
case 'angry': return 'rgba(244, 67, 54, 0.7)';
case 'neutral': return 'rgba(158, 158, 158, 0.7)';
case 'excited': return 'rgba(255, 193, 7, 0.7)';
default: return 'rgba(189, 189, 189, 0.7)';
}
});
new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: counts,
backgroundColor: backgroundColors,
borderColor: 'rgba(255, 255, 255, 0.8)',
borderWidth: 1
}]
},
options: {
responsive: true
}
});
}
function renderWordCountChart(data) {
const ctx = document.getElementById('wordcount-chart').getContext('2d');
// Prepare data for Chart.js
const labels = data.map(item => item.date);
const counts = data.map(item => item.word_count);
new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Word Count',
data: counts,
backgroundColor: 'rgba(79, 195, 247, 0.2)',
borderColor: 'rgba(79, 195, 247, 1)',
borderWidth: 2,
tension: 0.3,
fill: true
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
// Settings Functions
const exportTxtBtn = document.getElementById('export-txt-btn');
const exportPdfBtn = document.getElementById('export-pdf-btn');
const exportJsonBtn = document.getElementById('export-json-btn');
const backupBtn = document.getElementById('backup-btn');
const autoSaveCheckbox = document.getElementById('auto-save');
const ollamaPathInput = document.getElementById('ollama-path');
const aiModelSelect = document.getElementById('ai-model');
// Load settings
async function loadSettings() {
try {
const autoSave = await window.api.getSetting('autoSave');
const ollamaPath = await window.api.getSetting('ollamaPath');
const aiModel = await window.api.getSetting('aiModel');
autoSaveCheckbox.checked = autoSave === 'true';
ollamaPathInput.value = ollamaPath || '';
aiModelSelect.value = aiModel || 'llama2';
} catch (error) {
console.error('Error loading settings:', error);
}
}
// Save settings
autoSaveCheckbox.addEventListener('change', () => {
window.api.saveSetting('autoSave', autoSaveCheckbox.checked.toString());
});
ollamaPathInput.addEventListener('blur', () => {
window.api.saveSetting('ollamaPath', ollamaPathInput.value);
});
aiModelSelect.addEventListener('change', () => {
window.api.saveSetting('aiModel', aiModelSelect.value);
});
// Export functions
exportTxtBtn.addEventListener('click', async () => {
try {
const entries = await window.api.getEntries();
let txtContent = '';
entries.forEach(entry => {
const date = new Date(entry.date).toLocaleDateString();
txtContent += `Date: ${date}\n`;
txtContent += `Mood: ${entry.mood || 'Not specified'}\n\n`;
txtContent += `${entry.content}\n\n`;
if (entry.summary) {
txtContent += `Summary: ${entry.summary}\n`;
}
txtContent += '------------------------\n\n';
});
const result = await window.api.exportJournal('txt', txtContent);
if (result.success) {
alert(`Journal exported successfully to ${result.path}`);
}
} catch (error) {
console.error('Error exporting journal:', error);
alert('Failed to export journal. Please try again.');
}
});
exportJsonBtn.addEventListener('click', async () => {
try {
const entries = await window.api.getEntries();
const jsonContent = JSON.stringify(entries, null, 2);
const result = await window.api.exportJournal('json', jsonContent);
if (result.success) {
alert(`Journal exported successfully to ${result.path}`);
}
} catch (error) {
console.error('Error exporting journal:', error);
alert('Failed to export journal. Please try again.');
}
});
// Auto-save functionality
let autoSaveTimer;
journalEditor.addEventListener('input', () => {
clearTimeout(autoSaveTimer);
if (autoSaveCheckbox.checked) {
autoSaveTimer = setTimeout(async () => {
if (journalEditor.value.trim() && currentEntry.date) {
currentEntry.content = journalEditor.value;
try {
const result = await window.api.saveEntry(currentEntry);
currentEntry.id = result.id;
// Show subtle indicator that save happened
const saveIndicator = document.createElement('div');
saveIndicator.className = 'auto-save-indicator';
saveIndicator.textContent = 'Saved';
document.body.appendChild(saveIndicator);
setTimeout(() => {
saveIndicator.remove();
}, 2000);
} catch (error) {
console.error('Error auto-saving:', error);
}
}
}, 3000); // Auto-save after 3 seconds of inactivity
}
});
// Utility Functions
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
// Set default view
showView(journalView);
// Load settings
loadSettings();
// Generate initial prompt
generatePromptSuggestion();
// Load Chart.js dynamically
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/chart.js';
script.onload = () => {
console.log('Chart.js loaded');
};
document.head.appendChild(script);
});