-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
495 lines (449 loc) · 18.1 KB
/
Copy pathapp.js
File metadata and controls
495 lines (449 loc) · 18.1 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
// Minimal one-page app to load a local RSS file and render submission deadlines.
// Expects a local file named `rss.xml` in the same directory as index.html.
const FEED_URL = './rss.xml';
// localStorage keys
const LS_NS = 'submissionCalendar/v1';
const LS_FOLLOWS = `${LS_NS}/follows`;
const LS_DONE = `${LS_NS}/completed`;
// UI elements
const statusEl = document.getElementById('status');
const calendarEl = document.getElementById('calendar');
const refreshBtn = document.getElementById('refreshBtn');
const filterFollowedOnly = document.getElementById('filterFollowedOnly');
const searchBox = document.getElementById('searchBox');
const filterShowClosed = document.getElementById('filterShowClosed');
// Modal elements
const modalOverlay = document.getElementById('modalOverlay');
const modalTitle = document.getElementById('modalTitle');
const modalDue = document.getElementById('modalDue');
const modalBody = document.getElementById('modalBody');
const modalOpenLink = document.getElementById('modalOpenLink');
const modalCloseBtn = document.getElementById('modalCloseBtn');
const modalFollowBtn = document.getElementById('modalFollowBtn');
const modalCompleteBtn = document.getElementById('modalCompleteBtn');
let modalCurrentItem = null;
// Header nav (multiple dropdowns: e.g., Shows, Tools)
const navDropdownItems = document.querySelectorAll('.mainnav .nav-item.has-dropdown');
// State
let items = []; // [{ id, title, link, date, dateText, sourceSnippet }]
let follows = loadSet(LS_FOLLOWS);
let completed = loadSet(LS_DONE);
// Utilities
function loadSet(key){
try{ const raw = localStorage.getItem(key); return new Set(raw ? JSON.parse(raw) : []); }catch{ return new Set(); }
}
function saveSet(key, set){ localStorage.setItem(key, JSON.stringify([...set])); }
function setStatus(msg){ statusEl.textContent = msg; }
// Convert "The closing date for submissions is 11.59pm on Thursday, 02 October 2025"
// into a Date. We parse the DD Month YYYY, and if a time like 11.59pm exists, combine it.
const DATE_RE = /(\b\d{1,2})\s+([A-Za-z]+)\s+(\d{4})/; // 02 October 2025
const TIME_RE = /(\d{1,2})[.:](\d{2})\s*(am|pm)/i; // 11.59pm or 11:59pm
const MONTHS = {
january:0,february:1,march:2,april:3,may:4,june:5,
july:6,august:7,september:8,october:9,november:10,december:11
};
function parseDeadline(text){
if(!text) return null;
const dateMatch = text.match(DATE_RE);
if(!dateMatch) return null;
const day = parseInt(dateMatch[1], 10);
const monthName = dateMatch[2].toLowerCase();
const year = parseInt(dateMatch[3], 10);
const monthIdx = MONTHS[monthName];
if(monthIdx == null) return null;
let hours = 17, minutes = 0; // default 5pm if not specified
const timeMatch = text.match(TIME_RE);
if(timeMatch){
let h = parseInt(timeMatch[1], 10);
const m = parseInt(timeMatch[2], 10);
const ap = timeMatch[3].toLowerCase();
if(ap === 'pm' && h < 12) h += 12;
if(ap === 'am' && h === 12) h = 0;
hours = h; minutes = m;
}
// Use local time zone (NZ users will see local). If you need NZT specifically, you'd adjust with Intl.
const d = new Date(year, monthIdx, day, hours, minutes, 0, 0);
return isNaN(d.getTime()) ? null : d;
}
// Fetch local RSS (same directory as index.html)
async function fetchRSS(url){
const res = await fetch(`${url}?v=${Date.now()}`, { cache: 'no-store' });
if(!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.text();
}
function parseXML(text){
const parser = new DOMParser();
// Some proxies might deliver as text/html; DOMParser can still parse fairly well.
const xml = parser.parseFromString(text, 'text/xml');
// If parsing error, DOM will contain <parsererror>
if(xml.querySelector('parsererror')){
// Retry as text/html then extract the XML looking fragment
const html = parser.parseFromString(text, 'text/html');
const pre = html.querySelector('pre');
if(pre){
const inner = parser.parseFromString(pre.textContent, 'text/xml');
return inner;
}
}
return xml;
}
// Ensure a content snippet ends with a natural sentence ending.
function ensureNaturalSentenceEnd(text){
if(!text) return text;
const s = text.trim();
if(!s) return s;
// Check if ends with ., !, ?, or … possibly followed by quotes/brackets
const naturalEnd = /[.!?…](?:['"”’)\]]*)$/; // e.g., "." or ")."
if(naturalEnd.test(s)) return s;
return s + '…';
}
function escapeRegExp(str){
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function extractEntries(xml){
// Try Atom ('entry') and RSS ('item') for robustness
let nodes = [...xml.querySelectorAll('entry')];
if(nodes.length === 0){
nodes = [...xml.querySelectorAll('item')];
}
return nodes.map(n => {
const title = (n.querySelector('title')?.textContent || '').trim();
const link = n.querySelector('link')?.getAttribute('href') || n.querySelector('link')?.textContent || '';
// Content can be in <content> or <description>
const content = (n.querySelector('content')?.textContent || n.querySelector('description')?.textContent || '').trim();
const date = parseDeadline(content);
const id = n.querySelector('id')?.textContent || n.querySelector('guid')?.textContent || link || title;
return { id, title, link, content, date, dateText: date ? date.toISOString() : null };
}).filter(x => x.title && x.date);
}
function groupByDate(items){
// Group by local yyyy-mm-dd to avoid UTC day-shift issues
const pad = n => String(n).padStart(2,'0');
const by = new Map(); // key -> { date: Date(midnight local), items: [] }
for(const it of items){
const y = it.date.getFullYear();
const m = it.date.getMonth();
const d = it.date.getDate();
const key = `${y}-${pad(m+1)}-${pad(d)}`;
if(!by.has(key)) by.set(key, { date: new Date(y, m, d), items: [] });
by.get(key).items.push(it);
}
// Sort within groups by title
for(const obj of by.values()) obj.items.sort((a,b)=>a.title.localeCompare(b.title));
// Sort groups by date asc
return [...by.entries()]
.map(([key, obj]) => ({ key, date: obj.date, items: obj.items }))
.sort((a,b)=>a.date - b.date);
}
function formatDateLong(d){
return new Intl.DateTimeFormat(undefined, { weekday:'long', year:'numeric', month:'long', day:'numeric' }).format(d);
}
function formatTime(d){
return new Intl.DateTimeFormat(undefined, { hour:'numeric', minute:'2-digit' }).format(d);
}
function formatAgo(from, to){
const diffMs = Math.max(0, to.getTime() - from.getTime());
// If from is in the past relative to 'to', diffMs will be negative; we clamp above to 0 then recalc with absolute
const absMs = Math.abs(from.getTime() - to.getTime());
const sec = Math.floor(absMs/1000);
const min = Math.floor(sec/60);
const hr = Math.floor(min/60);
const day = Math.floor(hr/24);
if(day >= 1) return `${day}d ago`;
if(hr >= 1) return `${hr}h ago`;
if(min >= 1) return `${min}m ago`;
return `${sec}s ago`;
}
function render(){
const q = searchBox.value.trim().toLowerCase();
const nowTs = Date.now();
const filtered = items.filter(it => {
if(filterFollowedOnly.checked && !follows.has(it.id)) return false;
const isClosed = it.date.getTime() < nowTs;
if(isClosed && !filterShowClosed.checked) return false; // hide closed always unless toggle on
if(q && !it.title.toLowerCase().includes(q)) return false;
return true;
});
const groups = groupByDate(filtered);
calendarEl.innerHTML = '';
const now = new Date();
const todayY = now.getFullYear(), todayM = now.getMonth(), todayD = now.getDate();
for(const gInfo of groups){
const d = gInfo.date;
const arr = gInfo.items;
const g = document.createElement('div');
g.className = 'group';
const isToday = d.getFullYear()===todayY && d.getMonth()===todayM && d.getDate()===todayD;
if(isToday) g.classList.add('today');
const gh = document.createElement('div');
gh.className = 'group-header';
const title = document.createElement('div');
title.className = 'group-title';
title.textContent = `${formatDateLong(d)}`;
const count = document.createElement('div');
count.className = 'group-count';
count.textContent = `${arr.length} item${arr.length!==1?'s':''}`;
if(isToday){
const todayBadge = document.createElement('span');
todayBadge.className = 'badge follow';
todayBadge.textContent = 'Today';
title.append(' ', todayBadge);
}
gh.append(title, count);
g.appendChild(gh);
for(const it of arr){
const item = document.createElement('article');
item.className = 'item';
const left = document.createElement('div');
const title = document.createElement('div');
title.className = 'item-title';
const a = document.createElement('a');
a.href = it.link || '#';
a.target = '_blank';
a.rel = 'noopener';
a.textContent = it.title;
title.appendChild(a);
// Open modal on title click instead of direct navigation
a.addEventListener('click', (e) => {
e.preventDefault();
openModal(it);
});
// Apply state-based title color (completed overrides followed)
if(completed.has(it.id)){
title.classList.add('completed');
} else if(follows.has(it.id)){
title.classList.add('following');
}
const meta = document.createElement('div');
meta.className = 'item-meta';
const tBadge = document.createElement('span');
tBadge.className = 'badge';
const isPast = it.date.getTime() < now.getTime();
if(isPast){
tBadge.textContent = `Closed • ${formatAgo(it.date, now)}`;
tBadge.classList.add('overdue');
} else {
tBadge.textContent = `Due ${formatTime(it.date)}`;
}
if(follows.has(it.id)){
const b = document.createElement('span');
b.className = 'badge follow'; b.textContent = 'Following';
meta.append(b);
}
if(completed.has(it.id)){
const b = document.createElement('span');
b.className = 'badge completed'; b.textContent = 'Completed';
meta.append(b);
}
meta.prepend(tBadge);
left.append(title, meta);
const actions = document.createElement('div');
actions.className = 'item-actions';
// Add a strong visual cue for overdue items that are not marked completed
if(isPast){
item.classList.add('closed');
if(!completed.has(it.id)){
item.classList.add('overdue');
}
}
const menuWrap = document.createElement('div');
menuWrap.className = 'menu-wrap';
const kebabBtn = document.createElement('button');
kebabBtn.className = 'kebab-btn';
kebabBtn.setAttribute('aria-haspopup','menu');
kebabBtn.setAttribute('aria-expanded','false');
kebabBtn.title = 'More';
kebabBtn.textContent = '⋮'; // vertical ellipsis
const menu = document.createElement('div');
menu.className = 'menu';
menu.setAttribute('role','menu');
const followItem = document.createElement('button');
followItem.className = 'menu-item';
followItem.setAttribute('role','menuitem');
followItem.textContent = follows.has(it.id) ? 'Unfollow' : 'Follow';
followItem.addEventListener('click', () => {
if(follows.has(it.id)) follows.delete(it.id); else follows.add(it.id);
saveSet(LS_FOLLOWS, follows);
closeAllMenus();
render();
});
const completeItem = document.createElement('button');
completeItem.className = 'menu-item';
completeItem.setAttribute('role','menuitem');
completeItem.textContent = completed.has(it.id) ? 'Mark uncompleted' : 'Mark completed';
completeItem.addEventListener('click', () => {
if(completed.has(it.id)) completed.delete(it.id); else completed.add(it.id);
saveSet(LS_DONE, completed);
closeAllMenus();
render();
});
// Optional: separator, open link
const sep = document.createElement('div'); sep.className = 'menu-sep';
const openLink = document.createElement('button');
openLink.className = 'menu-item'; openLink.setAttribute('role','menuitem');
openLink.textContent = 'Open link';
openLink.addEventListener('click', () => { if(it.link) window.open(it.link,'_blank','noopener'); closeAllMenus(); });
menu.append(followItem, completeItem, sep, openLink);
menuWrap.append(kebabBtn, menu);
actions.append(menuWrap);
item.append(left, actions);
kebabBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = kebabBtn.getAttribute('aria-expanded') === 'true';
closeAllMenus();
if(!isOpen){
kebabBtn.setAttribute('aria-expanded','true');
menu.classList.add('open');
}
});
g.appendChild(item);
}
calendarEl.appendChild(g);
}
if(groups.length === 0){
calendarEl.innerHTML = '<div class="group"><div class="group-header"><div class="group-title">No matching items</div></div></div>';
}
setStatus(`${items.length} loaded • Showing ${filtered.length}`);
}
async function load(){
setStatus('Loading feed…');
try{
const xmlText = await fetchRSS(FEED_URL);
const xml = parseXML(xmlText);
const entries = extractEntries(xml);
// Sort by date ascending
items = entries.sort((a,b) => a.date - b.date);
render();
setStatus(`Loaded ${items.length} items.`);
}catch(err){
console.error(err);
setStatus('Failed to load feed. If CORS blocked, try opening this file with a local server.');
}
}
// Wire controls
refreshBtn.addEventListener('click', () => load());
filterFollowedOnly.addEventListener('change', render);
searchBox.addEventListener('input', () => { render(); });
filterShowClosed.addEventListener('change', render);
// Initial load
load();
// Close menus on click outside or Escape
document.addEventListener('click', () => closeAllMenus());
document.addEventListener('keydown', (e) => {
if(e.key === 'Escape'){
closeAllMenus();
closeModal();
closeAllNavDropdowns();
}
});
function closeAllMenus(){
document.querySelectorAll('.kebab-btn[aria-expanded="true"]').forEach(btn=>btn.setAttribute('aria-expanded','false'));
document.querySelectorAll('.menu.open').forEach(m=>m.classList.remove('open'));
}
// Shows dropdown behavior
function openNavDropdown(item){
const toggle = item.querySelector('.nav-btn');
const menu = item.querySelector('.dropdown');
if(!toggle || !menu) return;
// Close others first
closeAllNavDropdowns(item);
toggle.setAttribute('aria-expanded','true');
menu.classList.add('open');
}
function closeNavDropdown(item){
const toggle = item.querySelector('.nav-btn');
const menu = item.querySelector('.dropdown');
if(!toggle || !menu) return;
toggle.setAttribute('aria-expanded','false');
menu.classList.remove('open');
}
function closeAllNavDropdowns(except){
navDropdownItems.forEach(i=>{ if(except && i===except) return; closeNavDropdown(i); });
}
navDropdownItems.forEach(item=>{
const toggle = item.querySelector('.nav-btn');
const menu = item.querySelector('.dropdown');
if(!toggle || !menu) return;
toggle.addEventListener('click', (e)=>{
e.preventDefault();
e.stopPropagation();
const isOpen = toggle.getAttribute('aria-expanded') === 'true';
if(isOpen) closeNavDropdown(item); else openNavDropdown(item);
});
toggle.addEventListener('mouseenter', ()=> openNavDropdown(item));
menu.addEventListener('mouseenter', ()=> openNavDropdown(item));
menu.addEventListener('mouseleave', ()=> closeNavDropdown(item));
});
document.addEventListener('click', (e)=>{
// Close any open nav dropdown on outside click
if(!e.target.closest('.mainnav .nav-item.has-dropdown')) closeAllNavDropdowns();
});
// Modal logic
function openModal(it){
modalCurrentItem = it;
modalTitle.textContent = it.title;
modalDue.textContent = `${formatDateLong(it.date)} • ${formatTime(it.date)}`;
// Store the link on the element dataset for the click handler
modalOpenLink.dataset.href = it.link || '';
// Basic sanitize: allow simple text only; strip potential scripts by using textContent as fallback
// If content contains HTML, you could use a sanitizer; here we will show plaintext to be safe.
let raw = it.content || '';
// If the title appears immediately followed by a letter, insert a newline after the title
if(it.title){
try{
const re = new RegExp(`(${escapeRegExp(it.title.trim())})(?=\\p{L})`, 'gu');
raw = raw.replace(re, '$1\n');
}catch{ /* ignore if regex unsupported */ }
}
const lines = raw.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);
// Ensure last line ends naturally
if(lines.length > 0){
lines[lines.length - 1] = ensureNaturalSentenceEnd(lines[lines.length - 1]);
}
modalBody.innerHTML = '';
if(lines.length === 0){
const p = document.createElement('p');
p.textContent = 'No additional details.';
modalBody.appendChild(p);
} else {
for(const ln of lines){
const p = document.createElement('p');
p.textContent = ln;
modalBody.appendChild(p);
}
}
modalOverlay.hidden = false;
// Focus the close button for accessibility
setTimeout(()=>modalCloseBtn.focus(), 0);
updateModalButtons();
}
function closeModal(){ modalOverlay.hidden = true; }
modalCloseBtn?.addEventListener('click', closeModal);
modalOverlay?.addEventListener('click', (e) => { if(e.target === modalOverlay) closeModal(); });
// Open link button handler
modalOpenLink?.addEventListener('click', () => {
const url = modalOpenLink.dataset.href;
if(url) window.open(url, '_blank', 'noopener');
});
function updateModalButtons(){
if(!modalCurrentItem) return;
const id = modalCurrentItem.id;
modalFollowBtn.textContent = follows.has(id) ? 'Unfollow' : 'Follow';
modalCompleteBtn.textContent = completed.has(id) ? 'Mark uncompleted' : 'Mark completed';
}
modalFollowBtn?.addEventListener('click', () => {
if(!modalCurrentItem) return;
const id = modalCurrentItem.id;
if(follows.has(id)) follows.delete(id); else follows.add(id);
saveSet(LS_FOLLOWS, follows);
updateModalButtons();
render();
});
modalCompleteBtn?.addEventListener('click', () => {
if(!modalCurrentItem) return;
const id = modalCurrentItem.id;
if(completed.has(id)) completed.delete(id); else completed.add(id);
saveSet(LS_DONE, completed);
updateModalButtons();
render();
});