| 1 | 'use strict'; |
| 2 | |
| 3 | const MONTHS = ['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december']; |
| 4 | const ROMAN = ['I', 'II', 'III']; |
| 5 | const state = { me: null, csrf: '', local: false, freshKey: null, revealedKey: null }; |
| 6 | let renderToken = 0; |
| 7 | let menuAnchor = null; |
| 8 | let ignoreCloseUntil = 0; |
| 9 | |
| 10 | const app = document.querySelector('#app'); |
| 11 | if (app) boot(); |
| 12 | |
| 13 | function formatDate(iso) { |
| 14 | const [year, month, day] = iso.split('-').map(Number); |
| 15 | return day + ' ' + MONTHS[month - 1] + ' ' + year; |
| 16 | } |
| 17 | |
| 18 | function pathNow() { |
| 19 | const raw = location.hash.replace(/^#/, ''); |
| 20 | if (!raw || raw === '/') return '/'; |
| 21 | return raw.startsWith('/') ? raw : '/' + raw; |
| 22 | } |
| 23 | |
| 24 | function isDayRoute(path) { |
| 25 | return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path); |
| 26 | } |
| 27 | |
| 28 | // Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per |
| 29 | // geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag |
| 30 | // bovenaan en geven terug/vooruit de opgeslagen plek terug. |
| 31 | let historyTraversal = false; |
| 32 | let scrollGeneration = 0; |
| 33 | |
| 34 | function savedScrollY() { |
| 35 | const entry = history.state; |
| 36 | if (!entry || typeof entry !== 'object' || typeof entry.scrollY !== 'number') return null; |
| 37 | return entry.scrollY; |
| 38 | } |
| 39 | |
| 40 | function saveScrollPosition() { |
| 41 | const y = window.scrollY || document.documentElement.scrollTop || 0; |
| 42 | const entry = history.state && typeof history.state === 'object' ? history.state : {}; |
| 43 | if (entry.scrollY === y) return; |
| 44 | try { history.replaceState({ ...entry, scrollY: y }, ''); } |
| 45 | catch (error) { /* een volle geschiedenis mag het lezen niet blokkeren */ } |
| 46 | } |
| 47 | |
| 48 | function scrollToPosition(y) { |
| 49 | const root = document.documentElement; |
| 50 | const body = document.body; |
| 51 | // De stylesheet zet scroll-behavior op smooth. Een kale scrollTo leest dat |
| 52 | // en glijdt vanaf de onderkant omhoog; de nieuwe dag moet meteen bovenaan staan. |
| 53 | root.style.scrollBehavior = 'auto'; |
| 54 | if (body) body.style.scrollBehavior = 'auto'; |
| 55 | root.style.overflowAnchor = 'none'; |
| 56 | if (body) body.style.overflowAnchor = 'none'; |
| 57 | try { |
| 58 | window.scrollTo({ top: y, left: 0, behavior: 'instant' }); |
| 59 | } catch (error) { |
| 60 | window.scrollTo(0, y); |
| 61 | } |
| 62 | if (root.scrollTop !== y) root.scrollTop = y; |
| 63 | if (body && body.scrollTop !== y) body.scrollTop = y; |
| 64 | requestAnimationFrame(() => { |
| 65 | root.style.scrollBehavior = ''; |
| 66 | if (body) body.style.scrollBehavior = ''; |
| 67 | root.style.overflowAnchor = ''; |
| 68 | if (body) body.style.overflowAnchor = ''; |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | function settleScroll(path, traversal) { |
| 73 | let y = null; |
| 74 | if (traversal) y = savedScrollY(); |
| 75 | if (y === null && isDayRoute(path)) y = 0; |
| 76 | if (y === null) { |
| 77 | // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen, |
| 78 | // zodat terug/vooruit die plek terugzet. |
| 79 | saveScrollPosition(); |
| 80 | return; |
| 81 | } |
| 82 | const generation = ++scrollGeneration; |
| 83 | scrollToPosition(y); |
| 84 | saveScrollPosition(); |
| 85 | requestAnimationFrame(() => { |
| 86 | if (generation !== scrollGeneration || pathNow() !== path) return; |
| 87 | scrollToPosition(y); |
| 88 | saveScrollPosition(); |
| 89 | }); |
| 90 | } |
| 91 | |
| 92 | function navigateHash(hash) { |
| 93 | saveScrollPosition(); |
| 94 | location.hash = hash; |
| 95 | } |
| 96 | |
| 97 | function el(tag, attrs, children) { |
| 98 | const node = document.createElement(tag); |
| 99 | Object.entries(attrs || {}).forEach(([key, value]) => { |
| 100 | if (value == null || value === false) return; |
| 101 | if (key === 'class') node.className = value; |
| 102 | else node.setAttribute(key, value === true ? '' : value); |
| 103 | }); |
| 104 | (children || []).forEach((child) => node.append(child instanceof Node ? child : document.createTextNode(String(child)))); |
| 105 | return node; |
| 106 | } |
| 107 | |
| 108 | function toast(message) { |
| 109 | const node = document.querySelector('#toast'); |
| 110 | node.textContent = message; |
| 111 | node.dataset.show = '1'; |
| 112 | clearTimeout(toast.timer); |
| 113 | toast.timer = setTimeout(() => { node.dataset.show = '0'; }, 4200); |
| 114 | } |
| 115 | |
| 116 | async function api(method, path, body) { |
| 117 | const headers = { Accept: 'application/json' }; |
| 118 | if (body !== undefined) headers['Content-Type'] = 'application/json'; |
| 119 | if (method !== 'GET' && state.csrf) headers['X-CSRF-Token'] = state.csrf; |
| 120 | const response = await fetch('api.php' + path, { |
| 121 | method, |
| 122 | headers, |
| 123 | body: body !== undefined ? JSON.stringify(body) : undefined, |
| 124 | }); |
| 125 | let data = null; |
| 126 | try { data = await response.json(); } catch (error) { data = null; } |
| 127 | if (!response.ok) { |
| 128 | const failure = new Error((data && data.error) || 'Er ging iets mis.'); |
| 129 | failure.status = response.status; |
| 130 | throw failure; |
| 131 | } |
| 132 | return data; |
| 133 | } |
| 134 | |
| 135 | function applyPrefs(user) { |
| 136 | document.documentElement.dataset.theme = user.theme || 'system'; |
| 137 | document.documentElement.dataset.font = user.font || 'serif'; |
| 138 | const dark = user.theme === 'dark' || (user.theme !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); |
| 139 | const meta = document.querySelector('meta[name="theme-color"]'); |
| 140 | if (meta) meta.content = dark ? '#141210' : '#f4efe6'; |
| 141 | } |
| 142 | |
| 143 | function highlight(path) { |
| 144 | document.querySelectorAll('[data-nav]').forEach((link) => { |
| 145 | const nav = link.getAttribute('data-nav'); |
| 146 | let current = path === nav; |
| 147 | if (nav === '/') current = path === '/' || path.startsWith('/week/'); |
| 148 | if (nav === '/beheer') current = path.startsWith('/beheer'); |
| 149 | if (current) link.setAttribute('aria-current', 'page'); |
| 150 | else link.removeAttribute('aria-current'); |
| 151 | }); |
| 152 | } |
| 153 | |
| 154 | function localToday() { |
| 155 | const now = new Date(); |
| 156 | const month = String(now.getMonth() + 1).padStart(2, '0'); |
| 157 | const day = String(now.getDate()).padStart(2, '0'); |
| 158 | return now.getFullYear() + '-' + month + '-' + day; |
| 159 | } |
| 160 | |
| 161 | function overviewQuery(explicitWeek) { |
| 162 | const params = new URLSearchParams(); |
| 163 | if (explicitWeek) params.set('week', explicitWeek); |
| 164 | else params.set('today', localToday()); |
| 165 | return '/days?' + params.toString(); |
| 166 | } |
| 167 | |
| 168 | function closeMenu() { |
| 169 | const menu = document.querySelector('#read-menu'); |
| 170 | if (!menu || menu.hidden) return; |
| 171 | menu.hidden = true; |
| 172 | if (menuAnchor && menuAnchor.isConnected) menuAnchor.focus(); |
| 173 | menuAnchor = null; |
| 174 | } |
| 175 | |
| 176 | function openMenu(x, y, day, anchor) { |
| 177 | const menu = document.querySelector('#read-menu'); |
| 178 | menu.hidden = false; |
| 179 | menu.dataset.date = day.date; |
| 180 | menu.querySelector('[data-caption]').textContent = formatDate(day.date) + ' · ' + day.title; |
| 181 | const button = menu.querySelector('button'); |
| 182 | button.textContent = day.read ? 'Markeer als ongelezen' : 'Markeer als gelezen'; |
| 183 | button.dataset.makeRead = day.read ? '0' : '1'; |
| 184 | menu.style.left = '0px'; |
| 185 | menu.style.top = '0px'; |
| 186 | const rect = menu.getBoundingClientRect(); |
| 187 | menu.style.left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8)) + 'px'; |
| 188 | menu.style.top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8)) + 'px'; |
| 189 | menuAnchor = anchor; |
| 190 | ignoreCloseUntil = Date.now() + 450; |
| 191 | button.focus(); |
| 192 | } |
| 193 | |
| 194 | function bindReadMenu() { |
| 195 | const menu = document.querySelector('#read-menu'); |
| 196 | menu.querySelector('button').addEventListener('click', async () => { |
| 197 | const date = menu.dataset.date; |
| 198 | const makeRead = menu.querySelector('button').dataset.makeRead === '1'; |
| 199 | closeMenu(); |
| 200 | try { |
| 201 | await api(makeRead ? 'POST' : 'DELETE', '/days/' + date + '/read'); |
| 202 | await render(); |
| 203 | } catch (error) { |
| 204 | toast(error.message); |
| 205 | } |
| 206 | }); |
| 207 | document.addEventListener('click', (event) => { |
| 208 | if (menu.hidden || Date.now() < ignoreCloseUntil || menu.contains(event.target)) return; |
| 209 | closeMenu(); |
| 210 | }); |
| 211 | document.addEventListener('keydown', (event) => { |
| 212 | if (event.key === 'Escape') closeMenu(); |
| 213 | }); |
| 214 | window.addEventListener('scroll', () => closeMenu(), true); |
| 215 | } |
| 216 | |
| 217 | function bindDayLink(link, day) { |
| 218 | let timer = null; |
| 219 | let startX = 0; |
| 220 | let startY = 0; |
| 221 | let suppressClick = false; |
| 222 | const cancel = () => { |
| 223 | if (timer) clearTimeout(timer); |
| 224 | timer = null; |
| 225 | link.classList.remove('is-holding'); |
| 226 | }; |
| 227 | link.addEventListener('contextmenu', (event) => { |
| 228 | event.preventDefault(); |
| 229 | cancel(); |
| 230 | suppressClick = true; |
| 231 | openMenu(event.clientX, event.clientY, day, link); |
| 232 | }); |
| 233 | link.addEventListener('pointerdown', (event) => { |
| 234 | if (event.pointerType === 'mouse' || event.button !== 0) return; |
| 235 | startX = event.clientX; |
| 236 | startY = event.clientY; |
| 237 | suppressClick = false; |
| 238 | link.classList.add('is-holding'); |
| 239 | timer = setTimeout(() => { |
| 240 | timer = null; |
| 241 | suppressClick = true; |
| 242 | openMenu(startX, startY, day, link); |
| 243 | }, 550); |
| 244 | }); |
| 245 | link.addEventListener('pointermove', (event) => { |
| 246 | if (timer && Math.hypot(event.clientX - startX, event.clientY - startY) > 12) cancel(); |
| 247 | }); |
| 248 | link.addEventListener('pointerup', cancel); |
| 249 | link.addEventListener('pointercancel', cancel); |
| 250 | link.addEventListener('selectstart', (event) => event.preventDefault()); |
| 251 | link.addEventListener('dragstart', (event) => event.preventDefault()); |
| 252 | link.addEventListener('click', (event) => { |
| 253 | if (!suppressClick) return; |
| 254 | event.preventDefault(); |
| 255 | suppressClick = false; |
| 256 | }); |
| 257 | } |
| 258 | |
| 259 | function unreadLabel(count) { |
| 260 | if (count === 1) return '1 dag ongelezen'; |
| 261 | return count + ' dagen ongelezen'; |
| 262 | } |
| 263 | |
| 264 | function friendInitial(name) { |
| 265 | const trimmed = String(name || '').trim(); |
| 266 | const first = Array.from(trimmed)[0] || '?'; |
| 267 | return first.toLocaleUpperCase('nl'); |
| 268 | } |
| 269 | |
| 270 | function friendColor(id) { |
| 271 | const palette = ['#8a624f', '#6d7a62', '#5f6e78', '#7a6558', '#6a5d78', '#8d5346']; |
| 272 | const key = String(id || ''); |
| 273 | let hash = 0; |
| 274 | for (let index = 0; index < key.length; index += 1) hash = (hash * 33 + key.charCodeAt(index)) >>> 0; |
| 275 | return palette[hash % palette.length]; |
| 276 | } |
| 277 | |
| 278 | function friendDot(friend) { |
| 279 | const label = friend.name || 'Vriend'; |
| 280 | const dot = el('span', { class: 'friend-dot', title: label }); |
| 281 | dot.style.background = friendColor(friend.id || label); |
| 282 | dot.setAttribute('aria-hidden', 'true'); |
| 283 | if (friend.avatar_url) { |
| 284 | const img = el('img', { |
| 285 | src: friend.avatar_url, |
| 286 | alt: '', |
| 287 | width: '18', |
| 288 | height: '18', |
| 289 | referrerpolicy: 'no-referrer', |
| 290 | }); |
| 291 | img.addEventListener('error', () => { |
| 292 | img.remove(); |
| 293 | dot.textContent = friendInitial(label); |
| 294 | }); |
| 295 | dot.append(img); |
| 296 | } else { |
| 297 | dot.textContent = friendInitial(label); |
| 298 | } |
| 299 | return dot; |
| 300 | } |
| 301 | |
| 302 | function friendReadsLabel(readers) { |
| 303 | const names = readers.map((friend) => friend.name).filter((name) => name); |
| 304 | if (names.length === 1) return 'Gelezen door ' + names[0]; |
| 305 | return 'Gelezen door ' + names.join(', '); |
| 306 | } |
| 307 | |
| 308 | function paintFriendReads(byDay) { |
| 309 | document.querySelectorAll('.day-link').forEach((link) => { |
| 310 | const existing = link.querySelector('.friend-reads'); |
| 311 | if (existing) existing.remove(); |
| 312 | link.classList.remove('has-friends'); |
| 313 | const date = link.getAttribute('data-date'); |
| 314 | const readers = date && byDay && byDay[date] ? byDay[date] : []; |
| 315 | if (!readers.length) return; |
| 316 | const row = el('span', { class: 'friend-reads', 'aria-label': friendReadsLabel(readers) }, readers.slice(0, 5).map(friendDot)); |
| 317 | link.classList.add('has-friends'); |
| 318 | link.append(row); |
| 319 | }); |
| 320 | } |
| 321 | |
| 322 | function paintOverview(data) { |
| 323 | const days = data.days || []; |
| 324 | const visible = data.weekDays || []; |
| 325 | const week = data.week; |
| 326 | const unread = days.filter((day) => !day.read); |
| 327 | const wrap = el('div', { class: 'continue-wrap' }); |
| 328 | if (!days.length) { |
| 329 | wrap.append(el('p', { class: 'empty' }, [state.me.admin ? 'Er staan nog geen dagen in het boek.' : 'Er staan nog geen verhalen klaar.'])); |
| 330 | if (state.me.admin) wrap.append(el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag'])); |
| 331 | } else if (unread.length) { |
| 332 | wrap.append(el('a', { class: 'button primary continue', href: '#/dag/' + unread[0].date }, ['Verderlezen'])); |
| 333 | wrap.append(el('p', { class: 'continue-note' }, [unreadLabel(unread.length)])); |
| 334 | } else { |
| 335 | const done = el('button', { class: 'button continue', type: 'button', disabled: 'disabled' }, ['Alles gelezen']); |
| 336 | wrap.append(done); |
| 337 | } |
| 338 | const links = []; |
| 339 | if (week.hasPrevious) links.push(el('a', { class: 'button quiet week-prev', href: '#/week/' + week.previous }, ['← Vorige week'])); |
| 340 | if (week.hasNext) links.push(el('a', { class: 'button quiet week-next', href: '#/week/' + week.next }, ['Volgende week →'])); |
| 341 | const nodes = [el('h1', { class: 'week-label' }, [week.label])]; |
| 342 | if (links.length) nodes.push(el('nav', { class: 'week-nav', 'aria-label': 'Weken' }, links)); |
| 343 | nodes.push(wrap); |
| 344 | if (visible.length) { |
| 345 | const list = el('ol', { class: 'day-list' }); |
| 346 | visible.forEach((day) => { |
| 347 | const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date, 'data-date': day.date }, [ |
| 348 | el('span', { class: 'day-date' }, [formatDate(day.date)]), |
| 349 | el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']), |
| 350 | el('span', { class: 'day-title' }, [day.title]), |
| 351 | ]); |
| 352 | if (!day.complete) link.append(el('span', { class: 'badge' }, ['Onvolledig'])); |
| 353 | bindDayLink(link, day); |
| 354 | list.append(el('li', {}, [link])); |
| 355 | }); |
| 356 | nodes.push(list); |
| 357 | app.replaceChildren(...nodes); |
| 358 | const firstUnread = list.querySelector('.unread'); |
| 359 | if (firstUnread) firstUnread.scrollIntoView({ block: 'nearest' }); |
| 360 | } else { |
| 361 | if (days.length) nodes.push(el('p', { class: 'empty' }, ['Geen dagen in deze week.'])); |
| 362 | app.replaceChildren(...nodes); |
| 363 | } |
| 364 | document.title = week.label + ' · Verhalenboek'; |
| 365 | } |
| 366 | |
| 367 | function paintDay(day) { |
| 368 | const head = el('header', { class: 'day-head' }, [ |
| 369 | el('p', { class: 'day-kicker' }, [formatDate(day.date)]), |
| 370 | el('h1', {}, [day.title]), |
| 371 | ]); |
| 372 | const top = el('div', { class: 'pager' }); |
| 373 | if (day.previous) top.append(el('a', { class: 'button quiet', href: '#/dag/' + day.previous }, ['← Vorige dag'])); |
| 374 | const stories = day.stories.map((story) => el('article', { class: 'story' }, [ |
| 375 | el('h2', {}, [el('span', {}, [ROMAN[(story.position || 1) - 1] || String(story.position)]), story.title]), |
| 376 | ...story.paragraphs.map((paragraph) => el('p', {}, [paragraph])), |
| 377 | ])); |
| 378 | if (!day.complete) stories.unshift(el('p', { class: 'form-error' }, ['Deze dag is onvolledig.'])); |
| 379 | const bottom = el('div', { class: 'pager bottom' }); |
| 380 | if (day.next) bottom.append(el('a', { class: 'button primary continue', href: '#/dag/' + day.next }, ['Volgende dag →'])); |
| 381 | else bottom.append(el('a', { class: 'button quiet', href: '#/' }, ['Terug naar het overzicht'])); |
| 382 | app.replaceChildren(head, top, ...stories, bottom); |
| 383 | } |
| 384 | |
| 385 | function choice(name, value, label, current) { |
| 386 | const input = el('input', { type: 'radio', name, value }); |
| 387 | input.checked = current === value; |
| 388 | return el('label', {}, [input, label]); |
| 389 | } |
| 390 | |
| 391 | function paintSettings() { |
| 392 | const theme = el('fieldset', {}, [ |
| 393 | el('legend', {}, ['Weergave']), |
| 394 | el('div', { class: 'choice' }, [ |
| 395 | choice('theme', 'system', 'Systeem', state.me.theme), |
| 396 | choice('theme', 'light', 'Licht', state.me.theme), |
| 397 | choice('theme', 'dark', 'Donker', state.me.theme), |
| 398 | ]), |
| 399 | ]); |
| 400 | const font = el('fieldset', {}, [ |
| 401 | el('legend', {}, ['Lettertype']), |
| 402 | el('div', { class: 'choice' }, [ |
| 403 | choice('font', 'serif', 'Serif', state.me.font), |
| 404 | choice('font', 'sans', 'Schreefloos', state.me.font), |
| 405 | choice('font', 'rounded', 'Rond', state.me.font), |
| 406 | ]), |
| 407 | ]); |
| 408 | const preview = el('p', { class: 'lede' }, ['Zo lees je een verhaal. De regen tikte zacht op het dak, en de bladzijde bleef openliggen.']); |
| 409 | const error = el('p', { class: 'form-error' }); |
| 410 | async function persist() { |
| 411 | const nextTheme = theme.querySelector('input:checked').value; |
| 412 | const nextFont = font.querySelector('input:checked').value; |
| 413 | const previous = { theme: state.me.theme, font: state.me.font }; |
| 414 | state.me = { ...state.me, theme: nextTheme, font: nextFont }; |
| 415 | applyPrefs(state.me); |
| 416 | try { |
| 417 | const result = await api('PUT', '/me/settings', { theme: nextTheme, font: nextFont }); |
| 418 | state.me = result.user; |
| 419 | applyPrefs(state.me); |
| 420 | error.textContent = ''; |
| 421 | } catch (failure) { |
| 422 | state.me = { ...state.me, ...previous }; |
| 423 | applyPrefs(state.me); |
| 424 | theme.querySelector('input[value="' + previous.theme + '"]').checked = true; |
| 425 | font.querySelector('input[value="' + previous.font + '"]').checked = true; |
| 426 | error.textContent = failure.message; |
| 427 | } |
| 428 | } |
| 429 | theme.addEventListener('change', persist); |
| 430 | font.addEventListener('change', persist); |
| 431 | const actions = el('div', { class: 'row-actions' }, [ |
| 432 | el('button', { class: 'quiet', type: 'button' }, ['Exporteer mijn gegevens (JSON)']), |
| 433 | el('button', { class: 'danger', type: 'button' }, ['Uitloggen']), |
| 434 | ]); |
| 435 | actions.children[0].addEventListener('click', () => { window.location.href = 'api.php/me/export'; }); |
| 436 | actions.children[1].addEventListener('click', async () => { |
| 437 | try { |
| 438 | await api('POST', '/session/logout'); |
| 439 | window.location.href = 'index.php'; |
| 440 | } catch (failure) { toast(failure.message); } |
| 441 | }); |
| 442 | const section = el('section', { class: 'settings' }, [ |
| 443 | el('h1', {}, ['Instellingen']), |
| 444 | el('p', { class: 'continue-note' }, ['Ingelogd als ' + state.me.name + (state.me.admin ? ' · beheerder' : '')]), |
| 445 | theme, font, preview, error, actions, |
| 446 | ]); |
| 447 | if (state.local) { |
| 448 | const other = state.me.name === 'test_user_2' ? 'test_user_1' : 'test_user_2'; |
| 449 | const swap = el('button', { class: 'quiet', type: 'button' }, ['Wissel naar ' + other]); |
| 450 | swap.addEventListener('click', async () => { |
| 451 | try { |
| 452 | await api('POST', '/session/switch', { user: other }); |
| 453 | window.location.reload(); |
| 454 | } catch (failure) { toast(failure.message); } |
| 455 | }); |
| 456 | section.append(swap); |
| 457 | } |
| 458 | app.replaceChildren(section); |
| 459 | } |
| 460 | |
| 461 | function paragraphField(value) { |
| 462 | const area = el('textarea', { rows: '4' }); |
| 463 | area.value = value || ''; |
| 464 | const remove = el('button', { class: 'quiet', type: 'button' }, ['Alinea verwijderen']); |
| 465 | const block = el('div', { class: 'paragraph-actions' }, [area, remove]); |
| 466 | remove.addEventListener('click', () => { |
| 467 | const boxes = block.parentElement.querySelectorAll('textarea'); |
| 468 | if (boxes.length <= 1) { area.value = ''; return; } |
| 469 | block.remove(); |
| 470 | }); |
| 471 | return block; |
| 472 | } |
| 473 | |
| 474 | function storyField(position, story, onDelete) { |
| 475 | const title = el('input', { type: 'text', maxlength: '200', 'data-title': '1', required: 'required' }); |
| 476 | title.value = story.title || ''; |
| 477 | const paragraphs = el('div', {}); |
| 478 | (story.paragraphs && story.paragraphs.length ? story.paragraphs : ['']).forEach((paragraph) => paragraphs.append(paragraphField(paragraph))); |
| 479 | const add = el('button', { class: 'quiet', type: 'button' }, ['Alinea toevoegen']); |
| 480 | add.addEventListener('click', () => paragraphs.append(paragraphField(''))); |
| 481 | const fieldset = el('fieldset', { 'data-position': String(position) }, [ |
| 482 | el('legend', {}, ['Verhaal ' + ROMAN[position - 1]]), |
| 483 | el('label', {}, ['Titel', title]), |
| 484 | paragraphs, |
| 485 | add, |
| 486 | ]); |
| 487 | if (onDelete) { |
| 488 | const remove = el('button', { class: 'danger', type: 'button' }, ['Dit verhaal verwijderen']); |
| 489 | remove.addEventListener('click', onDelete); |
| 490 | fieldset.append(remove); |
| 491 | } |
| 492 | return fieldset; |
| 493 | } |
| 494 | |
| 495 | function readStories(form) { |
| 496 | return [...form.querySelectorAll('fieldset')].map((fieldset) => ({ |
| 497 | title: fieldset.querySelector('[data-title]').value, |
| 498 | paragraphs: [...fieldset.querySelectorAll('textarea')].map((area) => area.value), |
| 499 | })); |
| 500 | } |
| 501 | |
| 502 | async function paintEditor(date) { |
| 503 | const creating = !date; |
| 504 | let day = { title: '', stories: [{}, {}, {}] }; |
| 505 | if (!creating) day = await api('GET', '/days/' + date); |
| 506 | const byPosition = {}; |
| 507 | (day.stories || []).forEach((story) => { byPosition[story.position] = story; }); |
| 508 | const title = el('input', { type: 'text', maxlength: '200', required: 'required' }); |
| 509 | title.value = day.title || ''; |
| 510 | const dateInput = el('input', { type: 'date', required: 'required' }); |
| 511 | if (creating) dateInput.value = ''; |
| 512 | else { dateInput.value = date; dateInput.readOnly = true; } |
| 513 | const error = el('p', { class: 'form-error' }); |
| 514 | const form = el('form', { class: 'editor' }, [ |
| 515 | el('h1', {}, [creating ? 'Nieuwe dag' : 'Dag bewerken']), |
| 516 | el('label', {}, ['Datum', dateInput]), |
| 517 | el('label', {}, ['Titel van de dag', title]), |
| 518 | ]); |
| 519 | for (let position = 1; position <= 3; position += 1) { |
| 520 | const existing = byPosition[position]; |
| 521 | form.append(storyField(position, existing || { title: '', paragraphs: [''] }, !creating && existing ? async () => { |
| 522 | if (!window.confirm('Dit verhaal verwijderen? De dag wordt onvolledig.')) return; |
| 523 | try { |
| 524 | await api('DELETE', '/days/' + date + '/stories/' + position); |
| 525 | await render(); |
| 526 | } catch (failure) { error.textContent = failure.message; } |
| 527 | } : null)); |
| 528 | } |
| 529 | const save = el('button', { class: 'primary', type: 'submit' }, ['Dag opslaan']); |
| 530 | form.append(error, save); |
| 531 | if (!creating) { |
| 532 | const remove = el('button', { class: 'danger', type: 'button' }, ['Hele dag verwijderen']); |
| 533 | remove.addEventListener('click', async () => { |
| 534 | if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return; |
| 535 | try { |
| 536 | await api('DELETE', '/days/' + date); |
| 537 | navigateHash('#/beheer'); |
| 538 | } catch (failure) { error.textContent = failure.message; } |
| 539 | }); |
| 540 | form.append(remove); |
| 541 | } |
| 542 | form.addEventListener('submit', async (event) => { |
| 543 | event.preventDefault(); |
| 544 | error.textContent = ''; |
| 545 | save.disabled = true; |
| 546 | const payload = { title: title.value, stories: readStories(form) }; |
| 547 | try { |
| 548 | if (creating) { |
| 549 | const created = await api('POST', '/days', { date: dateInput.value, ...payload }); |
| 550 | navigateHash('#/beheer/' + created.date); |
| 551 | } else { |
| 552 | await api('PUT', '/days/' + date, payload); |
| 553 | toast('Opgeslagen.'); |
| 554 | await render(); |
| 555 | } |
| 556 | } catch (failure) { |
| 557 | error.textContent = failure.message; |
| 558 | save.disabled = false; |
| 559 | } |
| 560 | }); |
| 561 | app.replaceChildren(form); |
| 562 | } |
| 563 | |
| 564 | async function paintBeheer() { |
| 565 | const [days, people] = await Promise.all([api('GET', '/days'), api('GET', '/users')]); |
| 566 | const users = el('div', { class: 'user-list' }); |
| 567 | people.users.forEach((person) => { |
| 568 | const self = person.id === state.me.id; |
| 569 | const action = el('button', { |
| 570 | type: 'button', |
| 571 | class: self ? 'quiet' : (person.admin ? 'danger' : 'primary'), |
| 572 | }, [self ? 'Jij' : (person.admin ? 'Maak lezer' : 'Maak beheerder')]); |
| 573 | action.disabled = self; |
| 574 | if (!self) { |
| 575 | action.addEventListener('click', async () => { |
| 576 | if (person.admin && !window.confirm(person.name + ' is daarna alleen nog lezer. Doorgaan?')) return; |
| 577 | try { |
| 578 | await api('PUT', '/users/' + encodeURIComponent(person.id), { admin: !person.admin }); |
| 579 | toast(person.admin ? person.name + ' is nu lezer.' : person.name + ' is nu beheerder.'); |
| 580 | await render(); |
| 581 | } catch (failure) { toast(failure.message); } |
| 582 | }); |
| 583 | } |
| 584 | users.append(el('div', { class: 'user-row' }, [ |
| 585 | el('div', {}, [ |
| 586 | el('strong', {}, [person.name]), |
| 587 | el('small', {}, [person.id]), |
| 588 | el('span', { class: 'user-role' }, [person.admin ? 'Beheerder' : 'Lezer']), |
| 589 | ]), |
| 590 | action, |
| 591 | ])); |
| 592 | }); |
| 593 | const list = el('div', {}); |
| 594 | days.days.forEach((day) => { |
| 595 | list.append(el('div', { class: 'admin-day' }, [ |
| 596 | el('a', { href: '#/beheer/' + day.date }, [ |
| 597 | el('strong', {}, [day.title]), |
| 598 | document.createElement('br'), |
| 599 | el('small', {}, [formatDate(day.date) + (day.complete ? '' : ' · onvolledig')]), |
| 600 | ]), |
| 601 | el('a', { class: 'button quiet', href: '#/dag/' + day.date }, ['Lezen']), |
| 602 | ])); |
| 603 | }); |
| 604 | if (!days.days.length) list.append(el('p', { class: 'empty' }, ['Nog geen dagen.'])); |
| 605 | app.replaceChildren(el('section', { class: 'panel' }, [ |
| 606 | el('h1', {}, ['Beheer']), |
| 607 | el('h2', {}, ['Gebruikers']), |
| 608 | el('p', { class: 'lede' }, ['Maak iemand anders beheerder, of haal die rol weer weg. Je eigen rol blijft staan.']), |
| 609 | users, |
| 610 | el('h2', {}, ['Dagen']), |
| 611 | el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag']), |
| 612 | list, |
| 613 | ])); |
| 614 | } |
| 615 | |
| 616 | function tokenPanel(title, token) { |
| 617 | const field = el('textarea', { readonly: 'readonly', rows: '3' }); |
| 618 | field.value = token; |
| 619 | const copy = el('button', { class: 'quiet', type: 'button' }, ['Kopieer']); |
| 620 | copy.addEventListener('click', async () => { |
| 621 | field.select(); |
| 622 | try { await navigator.clipboard.writeText(field.value); toast('Gekopieerd.'); } |
| 623 | catch (failure) { toast('Selecteer de sleutel en kopieer hem handmatig.'); } |
| 624 | }); |
| 625 | return el('div', { class: 'token-once' }, [el('strong', {}, [title]), field, copy]); |
| 626 | } |
| 627 | |
| 628 | function paintKeys(keys) { |
| 629 | const name = el('input', { type: 'text', maxlength: '80', required: 'required' }); |
| 630 | const error = el('p', { class: 'form-error' }); |
| 631 | const form = el('form', {}, [ |
| 632 | el('label', {}, ['Naam van de sleutel', name]), |
| 633 | el('button', { class: 'primary', type: 'submit' }, ['Sleutel aanmaken']), |
| 634 | error, |
| 635 | ]); |
| 636 | form.addEventListener('submit', async (event) => { |
| 637 | event.preventDefault(); |
| 638 | error.textContent = ''; |
| 639 | try { |
| 640 | const result = await api('POST', '/keys', { name: name.value }); |
| 641 | state.freshKey = result.key; |
| 642 | state.revealedKey = null; |
| 643 | await render(); |
| 644 | } catch (failure) { error.textContent = failure.message; } |
| 645 | }); |
| 646 | const section = el('section', { class: 'keys' }, [el('h1', {}, ['API-sleutels']), form]); |
| 647 | if (state.revealedKey && state.revealedKey.token) { |
| 648 | section.append(tokenPanel('Sleutel van ' + state.revealedKey.name, state.revealedKey.token)); |
| 649 | } else if (state.freshKey && state.freshKey.token) { |
| 650 | section.append(tokenPanel('Nieuwe sleutel. Tik er later opnieuw op om hem te zien.', state.freshKey.token)); |
| 651 | } |
| 652 | const list = el('div', {}); |
| 653 | keys.forEach((key) => { |
| 654 | const open = el('button', { type: 'button', class: 'key-open' }, [ |
| 655 | el('span', { class: key.revoked ? 'revoked' : '' }, [key.name]), |
| 656 | el('span', {}, [key.prefix + '…']), |
| 657 | el('span', {}, [key.revoked ? 'Ingetrokken' : 'Actief']), |
| 658 | ]); |
| 659 | open.addEventListener('click', async () => { |
| 660 | try { |
| 661 | const result = await api('GET', '/keys/' + key.id); |
| 662 | state.freshKey = null; |
| 663 | state.revealedKey = result.key; |
| 664 | await render(); |
| 665 | } catch (failure) { toast(failure.message); } |
| 666 | }); |
| 667 | const revoke = el('button', { class: 'danger', type: 'button' }, ['Intrekken']); |
| 668 | revoke.disabled = key.revoked != null; |
| 669 | revoke.addEventListener('click', async () => { |
| 670 | if (!window.confirm('Deze API-sleutel intrekken? Bestaande scripts kunnen dan niet meer schrijven.')) return; |
| 671 | try { await api('DELETE', '/keys/' + key.id); await render(); } |
| 672 | catch (failure) { toast(failure.message); } |
| 673 | }); |
| 674 | list.append(el('div', { class: 'key-row' }, [open, revoke])); |
| 675 | }); |
| 676 | if (!keys.length) list.append(el('p', { class: 'empty' }, ['Nog geen sleutels.'])); |
| 677 | section.append(el('h2', {}, ['Bestaande sleutels']), el('p', { class: 'lede' }, ['Tik op een sleutel om de volledige sleutel opnieuw te zien.']), list); |
| 678 | app.replaceChildren(section); |
| 679 | } |
| 680 | |
| 681 | async function render() { |
| 682 | const token = ++renderToken; |
| 683 | const path = pathNow(); |
| 684 | const traversal = historyTraversal; |
| 685 | historyTraversal = false; |
| 686 | if (path !== '/sleutels') { |
| 687 | state.freshKey = null; |
| 688 | state.revealedKey = null; |
| 689 | } |
| 690 | closeMenu(); |
| 691 | highlight(path); |
| 692 | document.title = 'Verhalenboek'; |
| 693 | let settled = false; |
| 694 | const finishScroll = () => { |
| 695 | if (settled || token !== renderToken) return; |
| 696 | settled = true; |
| 697 | settleScroll(path, traversal); |
| 698 | }; |
| 699 | try { |
| 700 | const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/); |
| 701 | if (path === '/' || path === '' || weekMatch) { |
| 702 | const friendsPromise = api('GET', '/friend-reads').catch(() => ({ days: {} })); |
| 703 | const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null)); |
| 704 | if (token !== renderToken) return; |
| 705 | paintOverview(data); |
| 706 | friendsPromise.then((friends) => { |
| 707 | if (token !== renderToken) return; |
| 708 | paintFriendReads((friends && friends.days) || {}); |
| 709 | }); |
| 710 | } else if (path === '/instellingen') { |
| 711 | paintSettings(); |
| 712 | } else if (path === '/beheer') { |
| 713 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 714 | await paintBeheer(); |
| 715 | } else if (path === '/beheer/nieuw') { |
| 716 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 717 | await paintEditor(null); |
| 718 | } else if (/^\/beheer\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 719 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 720 | await paintEditor(path.slice('/beheer/'.length)); |
| 721 | } else if (path === '/sleutels') { |
| 722 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 723 | const data = await api('GET', '/keys'); |
| 724 | if (token !== renderToken) return; |
| 725 | paintKeys(data.keys); |
| 726 | } else if (isDayRoute(path)) { |
| 727 | const date = path.slice(5); |
| 728 | const day = await api('GET', '/days/' + date); |
| 729 | if (token !== renderToken) return; |
| 730 | paintDay(day); |
| 731 | document.title = day.title + ' · Verhalenboek'; |
| 732 | // Vóór de lees-POST, anders schildert de browser de nieuwe dag nog onderaan. |
| 733 | finishScroll(); |
| 734 | if (!day.read) { |
| 735 | try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ } |
| 736 | } |
| 737 | } else { |
| 738 | app.replaceChildren(el('p', { class: 'empty' }, ['Deze pagina bestaat niet.']), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 739 | } |
| 740 | } catch (error) { |
| 741 | if (token !== renderToken) return; |
| 742 | if (error.status === 401) { window.location.href = 'index.php'; return; } |
| 743 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 744 | } finally { |
| 745 | finishScroll(); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | async function boot() { |
| 750 | bindReadMenu(); |
| 751 | try { |
| 752 | const me = await api('GET', '/me'); |
| 753 | state.me = me.user; |
| 754 | state.csrf = me.csrf; |
| 755 | state.local = !!me.local; |
| 756 | applyPrefs(me.user); |
| 757 | } catch (error) { |
| 758 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message])); |
| 759 | return; |
| 760 | } |
| 761 | if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; |
| 762 | window.addEventListener('popstate', () => { historyTraversal = true; }); |
| 763 | window.addEventListener('hashchange', () => { render(); }); |
| 764 | document.addEventListener('click', (event) => { |
| 765 | if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; |
| 766 | const link = event.target instanceof Element ? event.target.closest('a[href]') : null; |
| 767 | if (!link || !(link.getAttribute('href') || '').startsWith('#')) return; |
| 768 | saveScrollPosition(); |
| 769 | }, true); |
| 770 | let scrollSaveTimer = 0; |
| 771 | window.addEventListener('scroll', () => { |
| 772 | clearTimeout(scrollSaveTimer); |
| 773 | scrollSaveTimer = setTimeout(saveScrollPosition, 120); |
| 774 | }, { passive: true }); |
| 775 | window.addEventListener('pagehide', saveScrollPosition); |
| 776 | if (!location.hash) location.replace('#/'); |
| 777 | else render(); |
| 778 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { |
| 779 | if (state.me && state.me.theme === 'system') applyPrefs(state.me); |
| 780 | }); |
| 781 | } |
projects-timfalken-com verhalenboek