Skip to main content

max / makenotwork

21.0 KB · 565 lines History Blame Raw
1 /* Multithreaded: Core JavaScript */
2 'use strict';
3
4 /* Everything below is wrapped in one IIFE so no helper (showToast,
5 showFormError, openSearchModal, ...) leaks onto `window`. Templates carry no
6 inline handlers (the CSP has no 'unsafe-inline'); every binding is via
7 addEventListener, so nothing needs to be a global. */
8 (function () {
9
10 (function() {
11 var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
12 if (csrfToken) {
13 document.body.addEventListener('htmx:config:request', function(evt) {
14 evt.detail.ctx.request.headers['X-CSRF-Token'] = csrfToken;
15 });
16 }
17 })();
18
19 /* TOAST NOTIFICATIONS */
20
21 function showToast(message, type) {
22 var container = document.getElementById('notifications');
23 if (!container) return;
24 var toast = document.createElement('div');
25 toast.className = 'toast toast-' + (type || 'error');
26 toast.textContent = message;
27 container.appendChild(toast);
28 setTimeout(function() {
29 toast.classList.add('fade-out');
30 setTimeout(function() { toast.remove(); }, 300);
31 }, 3000);
32 }
33
34 document.body.addEventListener('showToast', function(evt) {
35 showToast(evt.detail.message || 'Action completed', evt.detail.type || 'info');
36 });
37
38 /* INLINE FORM ERRORS
39
40 A failed submit (422) keeps the user on the page with their input intact and
41 shows a persistent error attached to the form, and when the handler names
42 the offending field via X-Form-Field, highlights and focuses that input.
43 This replaces the transient error toast for validation failures. */
44
45 function clearFormError(form) {
46 var prev = form.querySelector('.form-error');
47 if (prev) prev.remove();
48 form.querySelectorAll('[aria-invalid="true"]').forEach(function(el) {
49 el.removeAttribute('aria-invalid');
50 });
51 }
52
53 function showFormError(form, message, field) {
54 clearFormError(form);
55 var err = document.createElement('div');
56 err.className = 'form-error';
57 err.setAttribute('role', 'alert');
58 err.textContent = message;
59 form.insertBefore(err, form.firstChild);
60
61 var focusTarget = null;
62 if (field) {
63 focusTarget = form.querySelector('[name="' + field + '"]');
64 if (focusTarget) focusTarget.setAttribute('aria-invalid', 'true');
65 }
66 (focusTarget || err).scrollIntoView({ block: 'nearest', behavior: 'smooth' });
67 if (focusTarget) focusTarget.focus();
68 }
69
70 // Clear a field's invalid state (and the form error) once the user edits it.
71 document.addEventListener('input', function(e) {
72 var field = e.target;
73 if (field.getAttribute && field.getAttribute('aria-invalid') === 'true') {
74 var form = field.closest('form');
75 if (form) clearFormError(form);
76 }
77 });
78
79 // The toast is the whole response to a 4xx or 5xx: base.html's htmx-config
80 // keeps those statuses out of the swap, so nothing has replaced the target by
81 // the time this runs.
82 document.body.addEventListener('htmx:response:error', function(evt) {
83 var container = document.getElementById('notifications');
84 if (!container) return;
85 var toast = document.createElement('div');
86 toast.className = 'toast toast-error';
87 var msg = document.createElement('span');
88 msg.textContent = 'An error occurred.';
89 toast.appendChild(msg);
90 var retryBtn = document.createElement('button');
91 retryBtn.textContent = 'Retry';
92 retryBtn.className = 'toast-retry-btn';
93 retryBtn.onclick = function() {
94 toast.remove();
95 // A click, whatever the element's `hx-trigger` says. The branch here
96 // used to dispatch `htmx:trigger` for anything under an `hx-trigger`,
97 // which htmx emits and has never listened for, so that half was always
98 // a no-op. `htmx.closest` is gone in htmx 4 besides.
99 var elt = evt.detail.ctx.sourceElement;
100 if (elt) elt.click();
101 };
102 toast.appendChild(retryBtn);
103 container.appendChild(toast);
104 setTimeout(function() {
105 toast.classList.add('fade-out');
106 setTimeout(function() { toast.remove(); }, 300);
107 }, 6000);
108 });
109
110 /* HTMX FORM STATE (loading buttons) */
111
112 document.body.addEventListener('htmx:before:request', function(evt) {
113 var form = evt.detail.ctx.sourceElement.closest('form');
114 if (form) {
115 var btn = form.querySelector('button[type="submit"], .primary');
116 if (btn) { btn.dataset.origText = btn.textContent; btn.textContent = 'Saving...'; btn.disabled = true; }
117 }
118 });
119
120 document.body.addEventListener('htmx:finally:request', function(evt) {
121 var form = evt.detail.ctx.sourceElement.closest('form');
122 if (form) {
123 var btn = form.querySelector('button[type="submit"], .primary');
124 if (btn && btn.dataset.origText) { btn.textContent = btn.dataset.origText; btn.disabled = false; }
125 }
126 });
127
128 /* SEARCH MODAL */
129
130 function openSearchModal() {
131 var modal = document.getElementById('search-modal');
132 if (!modal) return;
133 modal.hidden = false;
134 var input = document.getElementById('search-input');
135 if (input) { input.value = ''; input.focus(); }
136 document.getElementById('search-results').innerHTML = '';
137 }
138
139 function closeSearchModal() {
140 var modal = document.getElementById('search-modal');
141 if (modal) modal.hidden = true;
142 }
143
144 // Wire up search button and backdrop via event listeners (no inline handlers)
145 (function() {
146 var btn = document.getElementById('search-btn');
147 if (btn) btn.addEventListener('click', openSearchModal);
148 var backdrop = document.getElementById('search-backdrop');
149 if (backdrop) backdrop.addEventListener('click', closeSearchModal);
150 })();
151
152 (function() {
153 // Keyboard navigation within search results
154 document.addEventListener('keydown', function(e) {
155 var modal = document.getElementById('search-modal');
156 if (!modal || modal.hidden) return;
157
158 if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
159 e.preventDefault();
160 var items = modal.querySelectorAll('.search-result');
161 if (!items.length) return;
162 var active = modal.querySelector('.search-result.search-active');
163 var idx = -1;
164 if (active) {
165 active.classList.remove('search-active');
166 idx = Array.prototype.indexOf.call(items, active);
167 }
168 if (e.key === 'ArrowDown') idx = (idx + 1) % items.length;
169 else idx = idx <= 0 ? items.length - 1 : idx - 1;
170 items[idx].classList.add('search-active');
171 items[idx].scrollIntoView({ block: 'nearest' });
172 }
173
174 if (e.key === 'Enter') {
175 var active = modal.querySelector('.search-result.search-active');
176 if (active) {
177 var link = active.querySelector('a');
178 if (link) { window.location.href = link.href; e.preventDefault(); }
179 }
180 }
181 });
182 })();
183
184 /* KEYBOARD SHORTCUTS */
185
186 document.addEventListener('keydown', function(e) {
187 // Search shortcut: / key (when not in input)
188 if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
189 var tag = document.activeElement?.tagName;
190 if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
191 e.preventDefault();
192 openSearchModal();
193 return;
194 }
195 if (e.key === 'Escape') {
196 var modal = document.getElementById('search-modal');
197 if (modal && !modal.hidden) { closeSearchModal(); return; }
198 var overlay = document.querySelector('.modal-overlay');
199 if (overlay) overlay.remove();
200 }
201 if ((e.metaKey || e.ctrlKey) && e.key === 's') {
202 e.preventDefault();
203 var form = document.activeElement?.closest('form');
204 if (form) { var btn = form.querySelector('button[type="submit"]'); if (btn) btn.click(); }
205 }
206 });
207
208 /* IMAGE CLICK: open full size in new tab */
209
210 document.addEventListener('click', function(e) {
211 var img = e.target;
212 if (img.tagName === 'IMG' && img.closest('.post-body')) {
213 window.open(img.src, '_blank');
214 }
215 });
216
217 /* NAV TOGGLE */
218
219 document.addEventListener('click', function(e) {
220 var toggle = document.getElementById('nav-toggle');
221 if (toggle && toggle.checked && e.target.closest('.nav-links a, .nav-links .link-button')) {
222 toggle.checked = false;
223 }
224 });
225
226 /* FORM POST WITH CSRF */
227
228 document.addEventListener('submit', function(e) {
229 // Another handler may have already cancelled this submit; respect it.
230 if (e.defaultPrevented) return;
231 var form = e.target;
232 if (form.method && form.method.toUpperCase() === 'POST') {
233 // Destructive-action guard. Inline `onsubmit="return confirm(...)"`
234 // cannot run under our CSP (no script-src 'unsafe-inline'), so the
235 // prompt lives here, driven by a `data-confirm` attribute on the form.
236 var confirmMsg = form.getAttribute('data-confirm');
237 if (confirmMsg && !window.confirm(confirmMsg)) {
238 e.preventDefault();
239 return;
240 }
241 var token = document.querySelector('meta[name="csrf-token"]')?.content;
242 if (!token) return;
243 e.preventDefault();
244 clearFormError(form);
245 fetch(form.action || window.location.href, {
246 method: 'POST',
247 headers: { 'X-CSRF-Token': token, 'Content-Type': 'application/x-www-form-urlencoded' },
248 body: new URLSearchParams(new FormData(form)),
249 redirect: 'follow',
250 }).then(function(resp) {
251 if (resp.ok) {
252 // Success: the draft is no longer needed, and the handler issued
253 // a redirect we should follow.
254 localStorage.removeItem('mt_draft:' + window.location.pathname);
255 window.location.href = resp.url;
256 return;
257 }
258 return resp.text().then(function(msg) {
259 if (resp.status === 422) {
260 // Validation failure: persistent inline error on the form,
261 // input preserved, offending field highlighted/focused.
262 showFormError(form, msg || 'Please check your input and try again.',
263 resp.headers.get('X-Form-Field'));
264 } else {
265 // Auth/rate-limit/server errors aren't field problems;
266 // a transient toast is the right surface.
267 showToast(msg || 'Something went wrong. Please try again.', 'error');
268 }
269 });
270 }).catch(function() {
271 showToast('Network error. Please try again.', 'error');
272 });
273 }
274 });
275
276 /* TOAST FROM URL PARAMETER */
277
278 (function() {
279 var p = new URLSearchParams(window.location.search).get('toast');
280 if (p) {
281 showToast(decodeURIComponent(p), 'success');
282 history.replaceState(null, '', window.location.pathname);
283 }
284 })();
285
286 /* DRAFT AUTO-SAVE */
287
288 (function() {
289 var body = document.getElementById('body') || document.getElementById('reply-body');
290 if (!body || body.tagName !== 'TEXTAREA') return;
291 // NB: draft autosave is independent of the read-position tracking opt-out
292 // (mt_tracking_enabled). They share no behavior; gating drafts on the
293 // privacy toggle silently dropped a long post on a validation error.
294
295 var title = document.getElementById('title');
296 if (title && title.tagName !== 'INPUT') title = null;
297 var key = 'mt_draft:' + window.location.pathname;
298 var timer = null;
299 var MAX_DRAFTS = 20;
300 var WEEK_MS = 7 * 24 * 60 * 60 * 1000;
301
302 // Restore
303 var raw = localStorage.getItem(key);
304 if (raw && !body.value.trim()) {
305 try {
306 var draft = JSON.parse(raw);
307 if (Date.now() - draft.ts > WEEK_MS) { localStorage.removeItem(key); }
308 else {
309 body.value = draft.body || '';
310 if (title && !title.value.trim()) title.value = draft.title || '';
311 var ind = document.createElement('div');
312 ind.className = 'draft-indicator';
313 ind.textContent = 'Draft restored. ';
314 var discard = document.createElement('a');
315 discard.textContent = 'Discard';
316 discard.href = '#';
317 discard.className = 'draft-discard';
318 discard.onclick = function(e) {
319 e.preventDefault();
320 localStorage.removeItem(key);
321 body.value = '';
322 if (title) title.value = '';
323 ind.remove();
324 };
325 ind.appendChild(discard);
326 body.parentNode.insertBefore(ind, body);
327 }
328 } catch(e) { localStorage.removeItem(key); }
329 }
330
331 // Save (debounced)
332 function save() {
333 var b = body.value.trim();
334 var t = title ? title.value.trim() : '';
335 if (!b && !t) { localStorage.removeItem(key); return; }
336 localStorage.setItem(key, JSON.stringify({ body: body.value, title: title ? title.value : '', ts: Date.now() }));
337 // LRU cleanup
338 var drafts = [];
339 for (var i = 0; i < localStorage.length; i++) {
340 var k = localStorage.key(i);
341 if (k && k.indexOf('mt_draft:') === 0 && k !== key) {
342 try { drafts.push({ k: k, ts: JSON.parse(localStorage.getItem(k)).ts }); } catch(e) {}
343 }
344 }
345 if (drafts.length >= MAX_DRAFTS) {
346 drafts.sort(function(a, b) { return a.ts - b.ts; });
347 while (drafts.length >= MAX_DRAFTS) { localStorage.removeItem(drafts.shift().k); }
348 }
349 }
350 function debounced() { clearTimeout(timer); timer = setTimeout(save, 1000); }
351 body.addEventListener('input', debounced);
352 if (title) title.addEventListener('input', debounced);
353
354 // The draft is cleared only on a successful submit (see the POST handler
355 // above), so a validation failure keeps the user's text.
356 })();
357
358 /* LOCAL UNREAD TRACKING (category pages) */
359
360 (function() {
361 if (localStorage.getItem('mt_tracking_enabled') === 'false') return;
362 var rows = document.querySelectorAll('tr[data-thread-id]');
363 if (!rows.length) return;
364
365 var KEY = 'mt_thread_state';
366 var MAX_ENTRIES = 1000;
367 var state = {};
368 try { state = JSON.parse(localStorage.getItem(KEY) || '{}'); } catch(e) { state = {}; }
369
370 rows.forEach(function(row) {
371 var tid = row.getAttribute('data-thread-id');
372 var count = parseInt(row.getAttribute('data-reply-count'), 10) || 0;
373 var prev = state[tid];
374 if (prev !== undefined && count > prev) {
375 row.classList.add('unread');
376 }
377 });
378
379 // On thread link click, store current count
380 rows.forEach(function(row) {
381 var link = row.querySelector('.thread-title a');
382 if (!link) return;
383 link.addEventListener('click', function() {
384 var tid = row.getAttribute('data-thread-id');
385 var count = parseInt(row.getAttribute('data-reply-count'), 10) || 0;
386 state[tid] = count;
387 // LRU cleanup
388 var keys = Object.keys(state);
389 if (keys.length > MAX_ENTRIES) {
390 keys.slice(0, keys.length - MAX_ENTRIES).forEach(function(k) { delete state[k]; });
391 }
392 localStorage.setItem(KEY, JSON.stringify(state));
393 });
394 });
395 })();
396
397 /* TRACKING OPT-OUT TOGGLE */
398
399 (function() {
400 var checkbox = document.getElementById('tracking-opt-out');
401 if (!checkbox) return;
402 var isDisabled = localStorage.getItem('mt_tracking_enabled') === 'false';
403 checkbox.checked = isDisabled;
404 checkbox.addEventListener('change', function() {
405 if (checkbox.checked) {
406 localStorage.setItem('mt_tracking_enabled', 'false');
407 } else {
408 localStorage.removeItem('mt_tracking_enabled');
409 }
410 });
411 })();
412
413 /* IMAGE UPLOAD (drag-and-drop + paste) */
414
415 (function() {
416 var textarea = document.getElementById('body') || document.getElementById('reply-body');
417 if (!textarea || textarea.tagName !== 'TEXTAREA') return;
418
419 var form = textarea.closest('form');
420 if (!form) return;
421
422 // Extract community slug from form action or URL
423 var match = window.location.pathname.match(/^\/p\/([^/]+)/);
424 if (!match) return;
425 var slug = match[1];
426
427 function uploadFile(file) {
428 var ALLOWED = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
429 if (ALLOWED.indexOf(file.type) === -1) {
430 showToast('Only PNG, JPG, GIF, and WebP images allowed.', 'error');
431 return;
432 }
433 if (file.size > 5 * 1024 * 1024) {
434 showToast('Image exceeds 5 MB limit.', 'error');
435 return;
436 }
437
438 // Insert placeholder
439 var placeholder = '![Uploading ' + file.name + '...]()';
440 var start = textarea.selectionStart;
441 textarea.value = textarea.value.substring(0, start) + placeholder + textarea.value.substring(textarea.selectionEnd);
442 textarea.selectionStart = textarea.selectionEnd = start + placeholder.length;
443
444 var formData = new FormData();
445 formData.append('file', file);
446
447 var token = document.querySelector('meta[name="csrf-token"]')?.content;
448 var headers = {};
449 if (token) headers['X-CSRF-Token'] = token;
450
451 fetch('/p/' + slug + '/upload', {
452 method: 'POST',
453 headers: headers,
454 body: formData,
455 })
456 .then(function(resp) {
457 if (!resp.ok) return resp.text().then(function(t) { throw new Error(t); });
458 return resp.json();
459 })
460 .then(function(data) {
461 textarea.value = textarea.value.replace(placeholder, data.markdown);
462 })
463 .catch(function(err) {
464 textarea.value = textarea.value.replace(placeholder, '');
465 showToast(err.message || 'Upload failed.', 'error');
466 });
467 }
468
469 // Drag and drop
470 textarea.addEventListener('dragover', function(e) {
471 e.preventDefault();
472 textarea.classList.add('drag-over');
473 });
474 textarea.addEventListener('dragleave', function() {
475 textarea.classList.remove('drag-over');
476 });
477 textarea.addEventListener('drop', function(e) {
478 e.preventDefault();
479 textarea.classList.remove('drag-over');
480 var files = e.dataTransfer?.files;
481 if (files) {
482 for (var i = 0; i < files.length; i++) {
483 if (files[i].type.indexOf('image/') === 0) uploadFile(files[i]);
484 }
485 }
486 });
487
488 // Paste
489 textarea.addEventListener('paste', function(e) {
490 var items = e.clipboardData?.items;
491 if (!items) return;
492 for (var i = 0; i < items.length; i++) {
493 if (items[i].type.indexOf('image/') === 0) {
494 e.preventDefault();
495 var file = items[i].getAsFile();
496 if (file) uploadFile(file);
497 return;
498 }
499 }
500 });
501 })();
502
503 /* SELECT-TO-QUOTE (thread pages) */
504
505 (function() {
506 var quoteBtn = null;
507
508 document.addEventListener('mouseup', function(e) {
509 var sel = window.getSelection();
510 if (!sel || sel.isCollapsed || !sel.toString().trim()) {
511 if (quoteBtn) { quoteBtn.remove(); quoteBtn = null; }
512 return;
513 }
514 var postBody = sel.anchorNode;
515 while (postBody && !postBody.classList) postBody = postBody.parentElement;
516 while (postBody && !postBody.classList.contains('post-body')) postBody = postBody.parentElement;
517 if (!postBody) return;
518 var postItem = postBody.closest('.post-item');
519 if (!postItem || postItem.classList.contains('post-removed')) return;
520 var replyBody = document.getElementById('reply-body');
521 if (!replyBody) return;
522
523 if (quoteBtn) quoteBtn.remove();
524 quoteBtn = document.createElement('button');
525 quoteBtn.className = 'quote-btn';
526 quoteBtn.textContent = 'Quote';
527 quoteBtn.type = 'button';
528
529 var range = sel.getRangeAt(0);
530 var rect = range.getBoundingClientRect();
531 quoteBtn.style.top = (window.scrollY + rect.top - 30) + 'px';
532 quoteBtn.style.left = (window.scrollX + rect.left) + 'px';
533 document.body.appendChild(quoteBtn);
534
535 quoteBtn.addEventListener('mousedown', function(ev) {
536 ev.preventDefault();
537 var text = sel.toString().trim();
538 var postId = postItem.getAttribute('data-post-id');
539 if (!text || !postId) return;
540
541 crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)).then(function(buf) {
542 var arr = new Uint8Array(buf);
543 var hash = '';
544 for (var i = 0; i < 4; i++) hash += ('0' + arr[i].toString(16)).slice(-2);
545 var quoted = text.split('\n').map(function(l) { return '> ' + l; }).join('\n');
546 var marker = '[quote:' + postId + ':' + hash + ']';
547 var insert = quoted + '\n' + marker + '\n\n';
548 replyBody.value = replyBody.value + insert;
549 replyBody.focus();
550 var form = document.getElementById('reply-form');
551 if (form) form.scrollIntoView({ behavior: 'smooth' });
552 if (quoteBtn) { quoteBtn.remove(); quoteBtn = null; }
553 });
554 });
555 });
556
557 document.addEventListener('mousedown', function(e) {
558 if (quoteBtn && e.target !== quoteBtn) {
559 quoteBtn.remove();
560 quoteBtn = null;
561 }
562 });
563 })();
564 })();
565