-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
478 lines (420 loc) · 20.6 KB
/
script.js
File metadata and controls
478 lines (420 loc) · 20.6 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
let SQL; // Define SQL globally to make it accessible in all functions
document.addEventListener("DOMContentLoaded", async () => {
const currentDateElement = document.getElementById("current-date");
const currentMonthElement = document.getElementById("current-month");
const calendarElement = document.getElementById("calendar");
const modal = document.getElementById("modal");
const modalContent = document.getElementById("submission-content");
const closeModal = document.getElementById("close-modal");
const editButton = document.getElementById("edit-button");
const deleteButton = document.getElementById("delete-button");
const submissionInput = document.getElementById("submission-input");
const submitButton = document.getElementById("submit-button");
const submissionEditor = document.getElementById("submission-editor");
const submissionPreview = document.getElementById("submission-preview");
const modalTitle = document.getElementById("modal-title");
const searchModal = document.getElementById("search-modal");
const closeSearchModal = document.getElementById("close-search-modal");
const searchInput = document.getElementById("search-input");
const searchResults = document.getElementById("search-results");
const todayLink = document.getElementById("today-link");
const converter = new showdown.Converter();
let db;
let lastPreviewMarkdown = ""; // Store last shown markdown for copy in preview mode
async function initDatabase() {
SQL = await initSqlJs({
locateFile: file => `https://sql.js.org/dist/${file}`
});
// Load database from IndexedDB if it exists
const savedDb = await loadDatabaseFromIndexedDB();
if (savedDb) {
const uint8Array = new Uint8Array(savedDb);
db = new SQL.Database(uint8Array); // Load the saved database
} else {
db = new SQL.Database(); // Create a new database
db.run("CREATE TABLE IF NOT EXISTS submissions (date TEXT PRIMARY KEY, content TEXT)");
}
}
function saveDatabase() {
const data = db.export(); // Export the database to a Uint8Array
saveDatabaseToIndexedDB(data); // Save to IndexedDB
}
function saveDatabaseToIndexedDB(data) {
const request = indexedDB.open("DailyUpdatesDB", 1);
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains("databases")) {
db.createObjectStore("databases");
}
};
request.onsuccess = event => {
const db = event.target.result;
const transaction = db.transaction("databases", "readwrite");
const store = transaction.objectStore("databases");
store.put(data, "dailyUpdatesDb");
};
request.onerror = event => {
console.error("Failed to save database to IndexedDB:", event.target.error);
};
}
function loadDatabaseFromIndexedDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open("DailyUpdatesDB", 1);
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains("databases")) {
db.createObjectStore("databases");
}
};
request.onsuccess = event => {
const db = event.target.result;
const transaction = db.transaction("databases", "readonly");
const store = transaction.objectStore("databases");
const getRequest = store.get("dailyUpdatesDb");
getRequest.onsuccess = () => {
resolve(getRequest.result || null);
};
getRequest.onerror = () => {
reject(getRequest.error);
};
};
request.onerror = event => {
reject(event.target.error);
};
});
}
let currentDate = new Date();
function updateDate() {
//currentDateElement.textContent = currentDate.toDateString();
}
function renderCalendar() {
calendarElement.innerHTML = "";
const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
currentMonthElement.textContent = firstDay.toLocaleString("default", { month: "long", year: "numeric" });
// Add day headers (Monday to Sunday)
const dayHeaders = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
dayHeaders.forEach(day => {
const headerElement = document.createElement("div");
headerElement.classList.add("day-header");
headerElement.textContent = day;
calendarElement.appendChild(headerElement);
});
// Fill in blank days before the first day of the month
const startDay = (firstDay.getDay() + 6) % 7; // Adjust to make Monday the first day
for (let i = 0; i < startDay; i++) {
const blankElement = document.createElement("div");
blankElement.classList.add("day", "blank");
calendarElement.appendChild(blankElement);
}
// Render days of the month
for (let i = 1; i <= lastDay.getDate(); i++) {
const dayElement = document.createElement("div");
dayElement.classList.add("day");
dayElement.textContent = i;
const dayOfWeek = (startDay + i - 1) % 7;
if (dayOfWeek === 5 || dayOfWeek === 6) {
dayElement.classList.add("weekend");
} else {
dayElement.classList.add("weekday");
}
// 当前日期高亮
if (
currentDate.getFullYear() === today.getFullYear() &&
currentDate.getMonth() === today.getMonth() &&
i === today.getDate()
) {
dayElement.classList.add("today");
}
const dateKey = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, "0")}-${String(i).padStart(2, "0")}`;
const result = db.exec("SELECT content FROM submissions WHERE date = ?", [dateKey]);
if (result.length > 0) {
const content = result[0].values[0][0];
dayElement.classList.add("has-submission");
dayElement.addEventListener("click", () => {
modalTitle.textContent = `${dateKey}`;
modal.setAttribute("data-selected-day", i); // Set the selected day
submissionPreview.style.display = 'none';
modalContent.innerHTML = '';
const previewDiv = document.createElement('div');
previewDiv.className = 'preview-content';
previewDiv.innerHTML = converter.makeHtml(content);
modalContent.appendChild(previewDiv);
modalContent.style.display = 'block';
submissionEditor.style.display = 'none';
editButton.style.display = 'inline-block';
deleteButton.style.display = 'inline-block';
submitButton.style.display = 'none';
modal.style.display = 'flex';
editButton.onclick = () => {
// Load existing content into the input field
const selectedDay = modal.getAttribute("data-selected-day");
const dateKey = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDay).padStart(2, "0")}`;
const result = db.exec("SELECT content FROM submissions WHERE date = ?", [dateKey]);
if (result.length > 0) {
const existingContent = result[0].values[0][0];
submissionInput.value = existingContent;
// Update preview with existing content
submissionPreview.innerHTML = '<div class="preview-content">' + converter.makeHtml(existingContent) + '</div>';
}
modalContent.style.display = 'none';
submissionEditor.style.display = 'grid';
submissionPreview.style.display = 'block';
editButton.style.display = 'none';
deleteButton.style.display = 'none';
submitButton.style.display = 'inline-block';
};
deleteButton.onclick = () => {
if (confirm('Are you sure you want to delete this record?')) {
db.run("DELETE FROM submissions WHERE date = ?", [dateKey]);
saveDatabase();
modal.style.display = 'none';
renderCalendar();
}
};
});
} else {
dayElement.addEventListener("click", () => {
modalTitle.textContent = `Daily Submission - ${dateKey}`;
modal.setAttribute("data-selected-day", i); // Set the selected day
modalContent.style.display = 'none';
submissionEditor.style.display = 'grid';
submissionPreview.style.display = 'block';
editButton.style.display = 'none';
deleteButton.style.display = 'none';
submitButton.style.display = 'inline-block';
// Clear input field for new submissions
submissionInput.value = '';
submissionPreview.innerHTML = '';
modal.style.display = 'flex';
});
}
calendarElement.appendChild(dayElement);
}
}
submissionInput.addEventListener("input", () => {
const markdownText = submissionInput.value;
submissionPreview.innerHTML = '';
submissionPreview.innerHTML += '<div class="preview-content">' + converter.makeHtml(markdownText) + '</div>';
});
submitButton.addEventListener("click", () => {
const inputContent = submissionInput.value.trim(); // Ensure no leading/trailing whitespace
const selectedDay = modal.getAttribute("data-selected-day");
if (!selectedDay) {
alert("No date selected.");
return;
}
const selectedDate = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, "0")}-${String(selectedDay).padStart(2, "0")}`;
if (!inputContent) {
alert("Submission content cannot be empty.");
return;
}
try {
db.run(
"INSERT INTO submissions (date, content) VALUES (?, ?) ON CONFLICT(date) DO UPDATE SET content = ?",
[selectedDate, inputContent, inputContent]
);
saveDatabase(); // Save the database after every submission
alert("Submission saved successfully!");
modal.style.display = 'none';
renderCalendar(); // Re-render the calendar to reflect the new submission
} catch (error) {
console.error("Failed to save submission:", error);
alert("Failed to save submission. Please try again.");
}
});
closeModal.addEventListener("click", () => {
// Check if submission editor is visible and has content
const isEditorVisible = !submissionEditor.classList.contains('hidden') &&
(submissionEditor.style.display === 'grid' ||
window.getComputedStyle(submissionEditor).display === 'grid');
const hasContent = submissionInput.value.trim();
if ( hasContent) {
const confirmDiscard = confirm('You have unsaved content. Are you sure you want to discard it?');
if (confirmDiscard) {
submissionInput.value = ''; // Clear the input
submissionPreview.innerHTML = ''; // Clear the preview
modal.style.display = 'none';
}
// If user clicks "No", do nothing (don't close the modal)
} else {
modal.style.display = 'none';
}
});
// Menu dropdown logic
const menuButton = document.getElementById("menu-button");
const dropdownMenu = document.getElementById("dropdown-menu");
const dropdownSearch = document.getElementById("dropdown-search");
const dropdownBackup = document.getElementById("dropdown-backup");
const dropdownImport = document.getElementById("dropdown-import");
const importFileInput = document.getElementById("import-file");
// Toggle dropdown
menuButton.addEventListener("click", (e) => {
e.stopPropagation();
dropdownMenu.classList.toggle("hidden");
});
// Close dropdown when clicking outside
document.addEventListener("click", (e) => {
if (!dropdownMenu.classList.contains("hidden")) {
if (!dropdownMenu.contains(e.target) && e.target !== menuButton) {
dropdownMenu.classList.add("hidden");
}
}
});
// Dropdown actions
dropdownSearch.addEventListener("click", () => {
dropdownMenu.classList.add("hidden");
searchModal.classList.remove("hidden");
searchInput.value = "";
searchResults.innerHTML = "";
setTimeout(() => searchInput.focus(), 100);
});
dropdownBackup.addEventListener("click", () => {
dropdownMenu.classList.add("hidden");
const data = db.export();
const blob = new Blob([data], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
// Generate timestamp for filename
const now = new Date();
const timestamp = now.getFullYear() +
String(now.getMonth() + 1).padStart(2, '0') +
String(now.getDate()).padStart(2, '0') + '_' +
String(now.getHours()).padStart(2, '0') +
String(now.getMinutes()).padStart(2, '0') +
String(now.getSeconds()).padStart(2, '0');
a.download = `daily_updates_backup_${timestamp}.db`;
a.click();
URL.revokeObjectURL(url);
alert("Backup successful!");
});
dropdownImport.addEventListener("click", () => {
dropdownMenu.classList.add("hidden");
importFileInput.click();
});
document.getElementById("import-file").addEventListener("change", async (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async (e) => {
const importedData = new Uint8Array(e.target.result);
const importedDb = new SQL.Database(importedData);
const importedSubmissions = importedDb.exec("SELECT * FROM submissions");
if (importedSubmissions.length === 0) {
alert("No submissions found in the imported database.");
return;
}
const importedRows = importedSubmissions[0].values;
const userChoice = confirm(
"How would you like to handle conflicts?\n" +
"OK: Append new content to existing entries.\n" +
"Cancel: Overwrite existing entries with new content."
);
for (const [date, content] of importedRows) {
const existingResult = db.exec("SELECT content FROM submissions WHERE date = ?", [date]);
if (existingResult.length > 0) {
const existingContent = existingResult[0].values[0][0];
if (userChoice) {
const appendedContent = `${existingContent}\n\n[New Import - ${new Date().toLocaleString()}]\n${content}`;
db.run("UPDATE submissions SET content = ? WHERE date = ?", [appendedContent, date]);
} else {
db.run("UPDATE submissions SET content = ? WHERE date = ?", [content, date]);
}
} else {
db.run("INSERT INTO submissions (date, content) VALUES (?, ?)", [date, content]);
}
}
saveDatabase(); // Save the updated database
alert("Database imported successfully!");
renderCalendar(); // Re-render the calendar to reflect the imported data
};
reader.onerror = () => {
alert("Failed to read the file. Please try again.");
};
reader.readAsArrayBuffer(file);
});
document.getElementById("prev-month").addEventListener("click", () => {
currentDate.setMonth(currentDate.getMonth() - 1);
renderCalendar();
});
document.getElementById("next-month").addEventListener("click", () => {
currentDate.setMonth(currentDate.getMonth() + 1);
renderCalendar();
});
// Close search modal
closeSearchModal.addEventListener("click", () => {
searchModal.classList.add("hidden");
});
// ESC关闭
searchInput.addEventListener("keydown", e => {
if (e.key === "Escape") searchModal.classList.add("hidden");
});
// Search on Enter
searchInput.addEventListener("keydown", async e => {
if (e.key === "Enter" && searchInput.value.trim().length > 1) {
const keyword = searchInput.value.trim();
// LIKE查询
const sql = "SELECT date, content FROM submissions WHERE content LIKE ? ORDER BY date DESC";
const param = `%${keyword}%`;
const result = db.exec(sql, [param]);
searchResults.innerHTML = "";
if (result.length === 0 || result[0].values.length === 0) {
searchResults.innerHTML = '<div style="color:#888;text-align:center;">No results found.</div>';
return;
}
const rows = result[0].values;
for (const [date, content] of rows) {
let html = converter.makeHtml(content);
const item = document.createElement('div');
item.className = 'search-result-item';
// Create a container for the rendered HTML
const htmlContainer = document.createElement('div');
htmlContainer.innerHTML = html;
// Highlight keyword in all text nodes (safe, non-recursive)
function getTextNodes(node) {
let nodes = [];
if (node.nodeType === 3) {
nodes.push(node);
} else if (node.nodeType === 1) {
for (let child of node.childNodes) {
nodes = nodes.concat(getTextNodes(child));
}
}
return nodes;
}
function highlightInTextNode(node, keyword) {
let idx = node.data.toLowerCase().indexOf(keyword.toLowerCase());
if (idx > -1 && keyword.length > 0) {
const span = document.createElement('span');
span.className = 'highlight';
span.textContent = node.data.substr(idx, keyword.length);
const after = node.splitText(idx);
after.data = after.data.substr(keyword.length);
node.parentNode.insertBefore(span, after);
}
}
const textNodes = getTextNodes(htmlContainer);
for (const tn of textNodes) {
// 只高亮每个文本节点的第一个匹配,多个节点会全部高亮
highlightInTextNode(tn, keyword);
}
item.innerHTML = `<span class='search-result-date'>${date}</span>`;
item.appendChild(htmlContainer);
searchResults.appendChild(item);
}
}
});
// Set today link text
const today = new Date();
const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
todayLink.textContent = todayStr;
todayLink.addEventListener("click", (e) => {
e.preventDefault();
currentDate = new Date();
renderCalendar();
});
await initDatabase();
updateDate();
renderCalendar();
});