forked from NimaMaria/My-Calendar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
512 lines (408 loc) · 14.7 KB
/
app.js
File metadata and controls
512 lines (408 loc) · 14.7 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
(function(){
const $ = (id) => document.getElementById(id);
const els = {
// month controls (now inside calendar panel)
prevBtn: $("prevBtn"),
nextBtn: $("nextBtn"),
todayBtn: $("todayBtn"),
monthLabel: $("monthLabel"),
// calendar + side
grid: $("grid"),
searchInput: $("searchInput"),
dayLabel: $("dayLabel"),
dayList: $("dayList"),
// side buttons
addBtn: $("addBtn"),
editBtn: $("editBtn"),
deleteSideBtn: $("deleteSideBtn"),
// modal
modal: $("eventModal"),
backdrop: $("backdrop"),
eventForm: $("eventForm"),
closeBtn: $("closeBtn"),
cancelBtn: $("cancelBtn"),
deleteBtn: $("deleteBtn"),
modalTitle: $("modalTitle"),
modalSub: $("modalSub"),
// form inputs
idInput: $("idInput"),
titleInput: $("titleInput"),
dateInput: $("dateInput"),
startInput: $("startInput"),
endInput: $("endInput"),
descInput: $("descInput"),
remindInput: $("remindInput"),
conflictBox: $("conflictBox"),
};
const STORAGE_KEY = "calendra_lite_events_v2";
const POPUP_SEEN_KEY = "calendra_lite_popup_seen_v1";
let events = loadEvents();
let viewDate = new Date();
let selectedDate = toDateKey(new Date());
let editingId = null;
let selectedEventId = null;
init();
function init(){
bind();
render();
renderDayPanel();
checkPopupReminders();
}
function bind(){
els.prevBtn.addEventListener("click", () => { viewDate = addMonths(viewDate, -1); render(); });
els.nextBtn.addEventListener("click", () => { viewDate = addMonths(viewDate, 1); render(); });
els.todayBtn.addEventListener("click", () => {
viewDate = new Date();
selectedDate = toDateKey(new Date());
selectedEventId = null;
render();
renderDayPanel();
});
els.searchInput.addEventListener("input", () => { render(); renderDayPanel(); });
els.addBtn.addEventListener("click", () => openModalForDate(selectedDate));
els.editBtn.addEventListener("click", () => {
if(!selectedEventId) return toast("Select an event first");
openModalForEdit(selectedEventId);
});
els.deleteSideBtn.addEventListener("click", () => {
if(!selectedEventId) return toast("Select an event first");
editingId = selectedEventId; // reuse delete logic
onDelete();
});
els.closeBtn.addEventListener("click", closeModal);
els.cancelBtn.addEventListener("click", closeModal);
els.backdrop.addEventListener("click", closeModal);
els.eventForm.addEventListener("submit", (e) => {
e.preventDefault();
onSave();
});
els.deleteBtn.addEventListener("click", onDelete);
["dateInput","startInput","endInput"].forEach(id => $(id).addEventListener("input", () => updateConflictWarning(editingId)));
}
// ---------- RENDER CALENDAR (ONLY CURRENT MONTH DAYS) ----------
function render(){
const y = viewDate.getFullYear();
const m = viewDate.getMonth();
els.monthLabel.textContent = viewDate.toLocaleString(undefined, { month:"long", year:"numeric" });
const first = new Date(y, m, 1);
const startDay = first.getDay(); // 0=Sun
const daysInMonth = new Date(y, m+1, 0).getDate();
// Build cells: blanks before 1st, then days, then blanks after
const cells = [];
for(let i=0;i<startDay;i++) cells.push({ empty:true });
for(let d=1; d<=daysInMonth; d++){
cells.push({ empty:false, date: new Date(y, m, d) });
}
while(cells.length % 7 !== 0) cells.push({ empty:true });
while(cells.length < 42) cells.push({ empty:true });
const q = (els.searchInput.value || "").trim().toLowerCase();
els.grid.innerHTML = "";
cells.forEach(cellData => {
const cell = document.createElement("div");
if(cellData.empty){
cell.className = "cell empty";
cell.innerHTML = `<div class="date"><span></span><span></span></div>`;
els.grid.appendChild(cell);
return;
}
const date = cellData.date;
const key = toDateKey(date);
const dayEvents = getEventsByDate(key)
.filter(ev => !q || formatSearch(ev).includes(q))
.sort((a,b) => (a.start||"").localeCompare(b.start||""));
cell.className = "cell";
if(key === toDateKey(new Date())) cell.classList.add("today");
cell.addEventListener("click", () => {
selectedDate = key;
selectedEventId = null;
render();
renderDayPanel();
});
const head = document.createElement("div");
head.className = "date";
const left = document.createElement("span");
left.textContent = String(date.getDate());
head.appendChild(left);
const right = document.createElement("span");
if(dayEvents.length){
const pill = document.createElement("span");
pill.className = "pill";
pill.textContent = String(dayEvents.length);
right.appendChild(pill);
}
head.appendChild(right);
const list = document.createElement("div");
list.className = "events";
dayEvents.slice(0,3).forEach(ev => {
const item = document.createElement("div");
item.className = "event-chip";
const timeText = (ev.start && ev.end) ? ` ${ev.start}` : "";
const bell = (ev.remindMode === "popup") ? " ⏰" : "";
item.innerHTML = `<div><b>${escapeHtml(ev.title)}</b><span class="t">${timeText}${bell}</span></div><div class="t"></div>`;
item.addEventListener("click", (e) => {
e.stopPropagation();
selectedEventId = ev.id;
openModalForEdit(ev.id);
});
list.appendChild(item);
});
cell.appendChild(head);
cell.appendChild(list);
els.grid.appendChild(cell);
});
}
function renderDayPanel(){
const d = new Date(selectedDate + "T00:00:00");
els.dayLabel.textContent = d.toLocaleDateString(undefined, { weekday:"long", year:"numeric", month:"long", day:"numeric" });
const q = (els.searchInput.value || "").trim().toLowerCase();
const dayEvents = getEventsByDate(selectedDate)
.filter(ev => !q || formatSearch(ev).includes(q))
.sort((a,b) => (a.start||"").localeCompare(b.start||""));
els.dayList.innerHTML = "";
if(!dayEvents.length){
const empty = document.createElement("div");
empty.className = "day-item";
empty.innerHTML = `<div class="top"><div class="title">No events</div><div class="tag">—</div></div><div class="meta">Click “Add Event” to create one.</div>`;
empty.addEventListener("click", () => openModalForDate(selectedDate));
els.dayList.appendChild(empty);
return;
}
dayEvents.forEach(ev => {
const item = document.createElement("div");
item.className = "day-item" + (selectedEventId === ev.id ? " selected" : "");
const tag = (ev.start && ev.end) ? `${ev.start}–${ev.end}` : "All day";
item.innerHTML = `
<div class="top">
<div class="title">${escapeHtml(ev.title)}</div>
<div class="tag">${escapeHtml(tag)}</div>
</div>
<div class="meta">
${ev.remindMode === "popup" ? "🔔 Popup reminder enabled<br/>" : ""}
${ev.description ? escapeHtml(ev.description) : ""}
</div>
`;
item.addEventListener("click", () => {
selectedEventId = ev.id;
renderDayPanel(); // update highlight
});
els.dayList.appendChild(item);
});
}
// ---------- MODAL ----------
function openModalForDate(dateKey){
editingId = null;
els.deleteBtn.hidden = true;
els.modalTitle.textContent = "New event";
els.modalSub.textContent = "Fill details and click Save.";
els.idInput.value = "";
els.titleInput.value = "";
els.dateInput.value = dateKey;
// time optional
els.startInput.value = "";
els.endInput.value = "";
els.descInput.value = "";
els.remindInput.value = "off";
els.conflictBox.hidden = true;
showModal();
}
function openModalForEdit(id){
const ev = events.find(e => e.id === id);
if(!ev) return;
editingId = id;
els.deleteBtn.hidden = false;
els.modalTitle.textContent = "Edit event";
els.modalSub.textContent = "Update or delete this event.";
els.idInput.value = id;
els.titleInput.value = ev.title || "";
els.dateInput.value = ev.date;
els.startInput.value = ev.start || "";
els.endInput.value = ev.end || "";
els.descInput.value = ev.description || "";
els.remindInput.value = ev.remindMode || "off";
updateConflictWarning(editingId);
showModal();
}
function draftFromForm(){
const id = els.idInput.value || editingId || safeUUID();
return {
id,
title: els.titleInput.value.trim(),
date: els.dateInput.value,
start: els.startInput.value || null,
end: els.endInput.value || null,
description: els.descInput.value.trim(),
remindMode: els.remindInput.value // "off" or "popup"
};
}
function onSave(){
const ev = draftFromForm();
// required only title + date
if(!ev.title || !ev.date){
toast("Please fill required fields");
return;
}
// time optional, but if one is set, require the other
if((ev.start && !ev.end) || (!ev.start && ev.end)){
toast("If you set time, set both Start and End");
return;
}
// if both exist, validate order
if(ev.start && ev.end && ev.end <= ev.start){
toast("End time must be after start time");
return;
}
// conflicts only when time exists
const conflicts = detectConflicts(ev, editingId);
els.conflictBox.hidden = conflicts.length === 0;
if(conflicts.length){
const sample = conflicts.slice(0,2).map(e => `• ${e.title} (${e.start}-${e.end})`).join("\n");
if(!confirm(`Conflict detected with:\n${sample}\n\nSave anyway?`)) return;
}
// upsert
const idx = events.findIndex(e => e.id === ev.id);
if(idx >= 0) events[idx] = ev;
else events.push(ev);
saveEvents(events);
selectedDate = ev.date;
selectedEventId = ev.id;
viewDate = new Date(ev.date + "T00:00:00");
render();
renderDayPanel();
closeModal();
toast("Saved");
// after save, re-check popups (in case they added reminder for tomorrow/today)
checkPopupReminders();
}
function onDelete(){
if(!editingId) return;
if(!confirm("Delete this event?")) return;
events = events.filter(e => e.id !== editingId);
saveEvents(events);
if(selectedEventId === editingId) selectedEventId = null;
render();
renderDayPanel();
closeModal();
toast("Deleted");
}
function showModal(){ els.backdrop.hidden = false; els.modal.showModal(); }
function closeModal(){ els.modal.close(); els.backdrop.hidden = true; }
// ---------- SEARCH / CONFLICTS ----------
function formatSearch(ev){
return (ev.title + " " + (ev.description || "")).toLowerCase();
}
function overlap(a,b){
// only overlap if both have time
if(!a.start || !a.end || !b.start || !b.end) return false;
return a.start < b.end && b.start < a.end;
}
function detectConflicts(candidate, excludeId=null){
if(!candidate.start || !candidate.end) return []; // no time = no conflict check
return events
.filter(e => e.date === candidate.date && e.id !== excludeId)
.filter(e => overlap(candidate, e));
}
function updateConflictWarning(excludeId=null){
const d = draftFromForm();
if(!d.date || !d.start || !d.end || d.end <= d.start){
els.conflictBox.hidden = true;
return;
}
els.conflictBox.hidden = detectConflicts(d, excludeId).length === 0;
}
// ---------- LOCAL STORAGE ----------
function loadEvents(){
try{
const raw = localStorage.getItem(STORAGE_KEY);
const items = raw ? JSON.parse(raw) : [];
return Array.isArray(items) ? items : [];
}catch{
return [];
}
}
function saveEvents(list){
localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
}
function getEventsByDate(dateKey){
return events.filter(e => e.date === dateKey);
}
// ---------- DATE HELPERS ----------
function toDateKey(d){
const y = d.getFullYear();
const m = String(d.getMonth()+1).padStart(2,"0");
const day = String(d.getDate()).padStart(2,"0");
return `${y}-${m}-${day}`;
}
function addMonths(d, n){
return new Date(d.getFullYear(), d.getMonth() + n, 1);
}
// ---------- POPUP REMINDERS (YESTERDAY + TODAY) ----------
// Rule:
// - If event is TOMORROW and reminder enabled => popup today
// - If event is TODAY and reminder enabled => popup today
// Shows once per day (no repeat spam)
function checkPopupReminders(){
const todayKey = toDateKey(new Date());
// avoid repeating popup on refresh
let seen = {};
try{
seen = JSON.parse(localStorage.getItem(POPUP_SEEN_KEY) || "{}");
}catch{ seen = {}; }
if(seen[todayKey]) return;
const today = new Date(todayKey + "T00:00:00");
const tomorrowKey = toDateKey(new Date(today.getTime() + 24*60*60*1000));
const todayEvents = getEventsByDate(todayKey).filter(e => e.remindMode === "popup");
const tomorrowEvents = getEventsByDate(tomorrowKey).filter(e => e.remindMode === "popup");
const list = [
...todayEvents.map(e => ({ e, when: "Today" })),
...tomorrowEvents.map(e => ({ e, when: "Tomorrow" }))
];
if(!list.length) return;
const lines = list.slice(0,6).map(x => `• ${x.e.title} (${x.when})`);
const msg =
"🔔 Reminder\n\n" +
lines.join("\n") +
(list.length > 6 ? `\n+${list.length - 6} more` : "");
alert(msg);
seen[todayKey] = true;
localStorage.setItem(POPUP_SEEN_KEY, JSON.stringify(seen));
}
// ---------- UTILS ----------
function safeUUID(){
return (crypto && crypto.randomUUID) ? crypto.randomUUID()
: (String(Date.now()) + "_" + Math.random().toString(16).slice(2));
}
function escapeHtml(s=""){
return String(s)
.replaceAll("&","&")
.replaceAll("<","<")
.replaceAll(">",">")
.replaceAll('"',""")
.replaceAll("'","'");
}
let toastTimer = null;
function toast(msg){
let el = document.getElementById("toast");
if(!el){
el = document.createElement("div");
el.id = "toast";
Object.assign(el.style, {
position:"fixed", left:"50%", bottom:"18px",
transform:"translateX(-50%)",
background:"rgba(0,0,0,.78)",
color:"#fff",
padding:"10px 12px",
borderRadius:"999px",
fontWeight:"900",
fontSize:"12px",
zIndex:"100",
maxWidth:"calc(100% - 24px)",
textAlign:"center"
});
document.body.appendChild(el);
}
el.textContent = msg;
el.style.opacity = "1";
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.style.opacity = "0"; }, 1600);
}
})();