-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
306 lines (264 loc) · 8.54 KB
/
utils.js
File metadata and controls
306 lines (264 loc) · 8.54 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
// Utility Functions Module for TLNotes
// ID generation
function generateId() {
return crypto.randomUUID ? crypto.randomUUID() : Date.now().toString() + Math.random().toString(36).substr(2, 9);
}
// Date utility functions
function getPartialDateTime(dateObj, fallbackTime) {
if (!dateObj) return fallbackTime;
const fallbackDate = new Date(fallbackTime);
const y = dateObj.year ?? fallbackDate.getFullYear();
const m = dateObj.month ? dateObj.month - 1 : 0;
const d = dateObj.day || 1;
return new Date(y, m, d).getTime();
}
function getSortDate(note) {
if (note.type === 'draft') return note.created;
let dateObj = null;
if (note.type === 'event') dateObj = note.date;
else if (note.type === 'period') dateObj = note.date ? note.date.begin : null;
else if (note.date && note.date.year) dateObj = note.date;
return getPartialDateTime(dateObj, note.created);
}
function getEndDate(note) {
if (note.type !== 'period') return null;
const endObj = note.date ? note.date.end : null;
if (!endObj || endObj.year == null) return Infinity;
const begin = note.date.begin || {};
const fallbackYear = begin.year ?? new Date(note.created).getFullYear();
const fallbackTime = new Date(fallbackYear, 0, 1).getTime();
return getPartialDateTime(endObj, fallbackTime);
}
function getWeek(time) {
const d = new Date(time);
d.setHours(0, 0, 0, 0);
d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7);
const week1 = new Date(d.getFullYear(), 0, 4);
return 1 + Math.round(((d.getTime() - week1.getTime()) / 86400000 + (week1.getDay() + 6) % 7 - 3) / 7);
}
function formatPartialDate(dateObj) {
if (!dateObj) return '';
const parts = [];
if (dateObj.year) parts.push(dateObj.year);
if (dateObj.month) parts.push(new Date(2000, dateObj.month - 1).toLocaleString('default', { month: 'long' }));
if (dateObj.day) parts.push(dateObj.day);
return parts.join(' ') || '';
}
function getDayStart(time) {
const d = new Date(time);
d.setHours(0, 0, 0, 0);
return d.getTime();
}
// HTML and text utilities
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function highlightSearch(text, query) {
if (!query) return escapeHtml(text);
const escapedText = escapeHtml(text);
const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
return escapedText.replace(regex, '<span class="search-highlight">$1</span>');
}
// Note sorting and comparison
const typePriority = {
'period': 0,
'event': 1,
'task': 2,
'dream': 3,
'idea': 4,
'dict': 5,
'draft': 6
};
function compareNotes(a, b) {
const da = getSortDate(a);
const db = getSortDate(b);
const dayA = getDayStart(da);
const dayB = getDayStart(db);
if (dayA !== dayB) return dayA - dayB;
const priA = typePriority[a.type] || 10;
const priB = typePriority[b.type] || 10;
if (priA !== priB) return priA - priB;
return a.created - b.created;
}
// DOM utilities
function scrollToNote(noteId) {
setTimeout(() => {
const noteElement = document.querySelector(`[data-note-id="${noteId}"]`);
if (noteElement) {
noteElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
noteElement.classList.add('new-note');
setTimeout(() => noteElement.classList.remove('new-note'), 2000);
}
}, 100);
}
function showView(viewId) {
// Hide all views
document.querySelectorAll('.view').forEach(view => {
view.classList.remove('active');
});
// Show selected view
const targetView = document.getElementById(viewId);
if (targetView) {
targetView.classList.add('active');
}
// Update nav buttons
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.remove('active');
});
}
// File operations
function downloadFile(data, filename, type = 'application/json') {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
function readFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) => reject(e);
reader.readAsText(file);
});
}
// Confirmation dialog utility
function showConfirmDialog(title, message, callback) {
const dialog = document.getElementById('confirmDialog');
const titleEl = document.getElementById('confirmTitle');
const messageEl = document.getElementById('confirmMessage');
const okBtn = document.getElementById('confirmOk');
const cancelBtn = document.getElementById('confirmCancel');
titleEl.textContent = title;
messageEl.textContent = message;
// Remove old listeners
const newOkBtn = okBtn.cloneNode(true);
const newCancelBtn = cancelBtn.cloneNode(true);
okBtn.parentNode.replaceChild(newOkBtn, okBtn);
cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn);
// Add new listeners
newOkBtn.addEventListener('click', () => {
dialog.close();
callback(true);
});
newCancelBtn.addEventListener('click', () => {
dialog.close();
callback(false);
});
dialog.showModal();
}
// Debounce utility
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Validation utilities
function validateNote(note) {
if (!note.content || note.content.trim() === '') {
throw new Error('Note content cannot be empty');
}
if (!note.type) {
throw new Error('Note type is required');
}
if (!note.id) {
note.id = generateId();
}
if (!note.created) {
note.created = Date.now();
}
note.edited = Date.now();
return note;
}
// Error handling utilities
function handleError(error, context = '') {
console.error(`Error ${context}:`, error);
let message = 'An unexpected error occurred.';
if (error.message) {
message = error.message;
}
// Show user-friendly error message
const errorDiv = document.createElement('div');
errorDiv.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #f44336;
color: white;
padding: 12px 16px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
z-index: 1000;
max-width: 300px;
font-size: 14px;
`;
errorDiv.textContent = message;
document.body.appendChild(errorDiv);
setTimeout(() => {
if (errorDiv.parentNode) {
errorDiv.parentNode.removeChild(errorDiv);
}
}, 5000);
}
// Success message utility
function showSuccess(message) {
const successDiv = document.createElement('div');
successDiv.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 12px 16px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
z-index: 1000;
max-width: 300px;
font-size: 14px;
`;
successDiv.textContent = message;
document.body.appendChild(successDiv);
setTimeout(() => {
if (successDiv.parentNode) {
successDiv.parentNode.removeChild(successDiv);
}
}, 3000);
}
// Local storage migration utility (for users upgrading from localStorage version)
function migrateFromLocalStorage() {
try {
const oldNotes = localStorage.getItem('tlnotes');
const oldTrash = localStorage.getItem('tlnotes-trash');
if (oldNotes || oldTrash) {
return {
notes: oldNotes ? JSON.parse(oldNotes) : [],
trash: oldTrash ? JSON.parse(oldTrash) : []
};
}
return null;
} catch (error) {
console.error('Error migrating from localStorage:', error);
return null;
}
}
function clearLocalStorageData() {
try {
localStorage.removeItem('tlnotes');
localStorage.removeItem('tlnotes-trash');
console.log('Old localStorage data cleared');
} catch (error) {
console.error('Error clearing localStorage:', error);
}
}