| 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, wikiQuery: '', showWiki: false }; |
| 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 | function wikiReading(path) { |
| 29 | if (path === '/wiki' || path === '/wiki/nieuw' || path.startsWith('/wiki/nieuw/') || path.startsWith('/wiki/bewerken/') || path.startsWith('/wiki/categorie/')) return null; |
| 30 | const match = path.match(/^\/wiki\/([a-z0-9]+(?:-[a-z0-9]+)*)(?:\/([a-z0-9]+(?:-[a-z0-9]+)*))?$/); |
| 31 | if (!match) return null; |
| 32 | return { slug: match[1], anchor: match[2] || null }; |
| 33 | } |
| 34 | |
| 35 | // Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per |
| 36 | // geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag |
| 37 | // bovenaan en geven terug/vooruit de opgeslagen plek terug. |
| 38 | let historyTraversal = false; |
| 39 | let scrollGeneration = 0; |
| 40 | |
| 41 | function savedScrollY() { |
| 42 | const entry = history.state; |
| 43 | if (!entry || typeof entry !== 'object' || typeof entry.scrollY !== 'number') return null; |
| 44 | return entry.scrollY; |
| 45 | } |
| 46 | |
| 47 | function saveScrollPosition() { |
| 48 | const y = window.scrollY || document.documentElement.scrollTop || 0; |
| 49 | const entry = history.state && typeof history.state === 'object' ? history.state : {}; |
| 50 | if (entry.scrollY === y) return; |
| 51 | try { history.replaceState({ ...entry, scrollY: y }, ''); } |
| 52 | catch (error) { /* een volle geschiedenis mag het lezen niet blokkeren */ } |
| 53 | } |
| 54 | |
| 55 | function scrollToPosition(y) { |
| 56 | const root = document.documentElement; |
| 57 | const body = document.body; |
| 58 | // De stylesheet zet scroll-behavior op smooth. Een kale scrollTo leest dat |
| 59 | // en glijdt vanaf de onderkant omhoog; de nieuwe dag moet meteen bovenaan staan. |
| 60 | root.style.scrollBehavior = 'auto'; |
| 61 | if (body) body.style.scrollBehavior = 'auto'; |
| 62 | root.style.overflowAnchor = 'none'; |
| 63 | if (body) body.style.overflowAnchor = 'none'; |
| 64 | try { |
| 65 | window.scrollTo({ top: y, left: 0, behavior: 'instant' }); |
| 66 | } catch (error) { |
| 67 | window.scrollTo(0, y); |
| 68 | } |
| 69 | if (root.scrollTop !== y) root.scrollTop = y; |
| 70 | if (body && body.scrollTop !== y) body.scrollTop = y; |
| 71 | requestAnimationFrame(() => { |
| 72 | root.style.scrollBehavior = ''; |
| 73 | if (body) body.style.scrollBehavior = ''; |
| 74 | root.style.overflowAnchor = ''; |
| 75 | if (body) body.style.overflowAnchor = ''; |
| 76 | }); |
| 77 | } |
| 78 | |
| 79 | function settleScroll(path, traversal) { |
| 80 | let y = null; |
| 81 | if (traversal) y = savedScrollY(); |
| 82 | const reading = wikiReading(path); |
| 83 | if (y === null && reading && reading.anchor) { |
| 84 | const node = document.getElementById('wiki-' + reading.anchor); |
| 85 | if (node) { |
| 86 | const top = node.getBoundingClientRect().top + (window.scrollY || document.documentElement.scrollTop || 0) - 12; |
| 87 | y = Math.max(0, Math.round(top)); |
| 88 | } else y = 0; |
| 89 | } |
| 90 | if (y === null && (isDayRoute(path) || path === '/wiki' || path.startsWith('/wiki/'))) y = 0; |
| 91 | if (y === null) { |
| 92 | // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen, |
| 93 | // zodat terug/vooruit die plek terugzet. |
| 94 | saveScrollPosition(); |
| 95 | return; |
| 96 | } |
| 97 | const generation = ++scrollGeneration; |
| 98 | scrollToPosition(y); |
| 99 | saveScrollPosition(); |
| 100 | requestAnimationFrame(() => { |
| 101 | if (generation !== scrollGeneration || pathNow() !== path) return; |
| 102 | scrollToPosition(y); |
| 103 | saveScrollPosition(); |
| 104 | }); |
| 105 | } |
| 106 | |
| 107 | function navigateHash(hash) { |
| 108 | saveScrollPosition(); |
| 109 | location.hash = hash; |
| 110 | } |
| 111 | |
| 112 | function el(tag, attrs, children) { |
| 113 | const node = document.createElement(tag); |
| 114 | Object.entries(attrs || {}).forEach(([key, value]) => { |
| 115 | if (value == null || value === false) return; |
| 116 | if (key === 'class') node.className = value; |
| 117 | else node.setAttribute(key, value === true ? '' : value); |
| 118 | }); |
| 119 | (children || []).forEach((child) => node.append(child instanceof Node ? child : document.createTextNode(String(child)))); |
| 120 | return node; |
| 121 | } |
| 122 | |
| 123 | function toast(message) { |
| 124 | const node = document.querySelector('#toast'); |
| 125 | node.textContent = message; |
| 126 | node.dataset.show = '1'; |
| 127 | clearTimeout(toast.timer); |
| 128 | toast.timer = setTimeout(() => { node.dataset.show = '0'; }, 4200); |
| 129 | } |
| 130 | |
| 131 | async function api(method, path, body) { |
| 132 | const headers = { Accept: 'application/json' }; |
| 133 | if (body !== undefined) headers['Content-Type'] = 'application/json'; |
| 134 | if (method !== 'GET' && state.csrf) headers['X-CSRF-Token'] = state.csrf; |
| 135 | const response = await fetch('api.php' + path, { |
| 136 | method, |
| 137 | headers, |
| 138 | body: body !== undefined ? JSON.stringify(body) : undefined, |
| 139 | }); |
| 140 | let data = null; |
| 141 | try { data = await response.json(); } catch (error) { data = null; } |
| 142 | if (!response.ok) { |
| 143 | const failure = new Error((data && data.error) || 'Er ging iets mis.'); |
| 144 | failure.status = response.status; |
| 145 | throw failure; |
| 146 | } |
| 147 | return data; |
| 148 | } |
| 149 | |
| 150 | function applyPrefs(user) { |
| 151 | document.documentElement.dataset.theme = user.theme || 'system'; |
| 152 | document.documentElement.dataset.font = user.font || 'serif'; |
| 153 | const dark = user.theme === 'dark' || (user.theme !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); |
| 154 | const meta = document.querySelector('meta[name="theme-color"]'); |
| 155 | if (meta) meta.content = dark ? '#141210' : '#f4efe6'; |
| 156 | } |
| 157 | |
| 158 | function highlight(path) { |
| 159 | document.querySelectorAll('[data-nav]').forEach((link) => { |
| 160 | const nav = link.getAttribute('data-nav'); |
| 161 | let current = path === nav; |
| 162 | if (nav === '/') current = path === '/' || path.startsWith('/week/'); |
| 163 | if (nav === '/wiki') current = path === '/wiki' || path.startsWith('/wiki/'); |
| 164 | if (nav === '/beheer') current = path.startsWith('/beheer'); |
| 165 | if (current) link.setAttribute('aria-current', 'page'); |
| 166 | else link.removeAttribute('aria-current'); |
| 167 | }); |
| 168 | } |
| 169 | |
| 170 | function localToday() { |
| 171 | const now = new Date(); |
| 172 | const month = String(now.getMonth() + 1).padStart(2, '0'); |
| 173 | const day = String(now.getDate()).padStart(2, '0'); |
| 174 | return now.getFullYear() + '-' + month + '-' + day; |
| 175 | } |
| 176 | |
| 177 | function overviewQuery(explicitWeek) { |
| 178 | const params = new URLSearchParams(); |
| 179 | if (explicitWeek) params.set('week', explicitWeek); |
| 180 | else params.set('today', localToday()); |
| 181 | return '/days?' + params.toString(); |
| 182 | } |
| 183 | |
| 184 | function closeMenu() { |
| 185 | const menu = document.querySelector('#read-menu'); |
| 186 | if (!menu || menu.hidden) return; |
| 187 | menu.hidden = true; |
| 188 | if (menuAnchor && menuAnchor.isConnected) menuAnchor.focus(); |
| 189 | menuAnchor = null; |
| 190 | } |
| 191 | |
| 192 | function openMenu(x, y, day, anchor) { |
| 193 | const menu = document.querySelector('#read-menu'); |
| 194 | menu.hidden = false; |
| 195 | menu.dataset.date = day.date; |
| 196 | menu.querySelector('[data-caption]').textContent = formatDate(day.date) + ' · ' + day.title; |
| 197 | const button = menu.querySelector('button'); |
| 198 | button.textContent = day.read ? 'Markeer als ongelezen' : 'Markeer als gelezen'; |
| 199 | button.dataset.makeRead = day.read ? '0' : '1'; |
| 200 | menu.style.left = '0px'; |
| 201 | menu.style.top = '0px'; |
| 202 | const rect = menu.getBoundingClientRect(); |
| 203 | menu.style.left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8)) + 'px'; |
| 204 | menu.style.top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8)) + 'px'; |
| 205 | menuAnchor = anchor; |
| 206 | ignoreCloseUntil = Date.now() + 450; |
| 207 | button.focus(); |
| 208 | } |
| 209 | |
| 210 | function bindReadMenu() { |
| 211 | const menu = document.querySelector('#read-menu'); |
| 212 | menu.querySelector('button').addEventListener('click', async () => { |
| 213 | const date = menu.dataset.date; |
| 214 | const makeRead = menu.querySelector('button').dataset.makeRead === '1'; |
| 215 | closeMenu(); |
| 216 | try { |
| 217 | await api(makeRead ? 'POST' : 'DELETE', '/days/' + date + '/read'); |
| 218 | await render(); |
| 219 | } catch (error) { |
| 220 | toast(error.message); |
| 221 | } |
| 222 | }); |
| 223 | document.addEventListener('click', (event) => { |
| 224 | if (menu.hidden || Date.now() < ignoreCloseUntil || menu.contains(event.target)) return; |
| 225 | closeMenu(); |
| 226 | }); |
| 227 | document.addEventListener('keydown', (event) => { |
| 228 | if (event.key === 'Escape') closeMenu(); |
| 229 | }); |
| 230 | window.addEventListener('scroll', () => closeMenu(), true); |
| 231 | } |
| 232 | |
| 233 | function bindDayLink(link, day) { |
| 234 | let timer = null; |
| 235 | let startX = 0; |
| 236 | let startY = 0; |
| 237 | let suppressClick = false; |
| 238 | const cancel = () => { |
| 239 | if (timer) clearTimeout(timer); |
| 240 | timer = null; |
| 241 | link.classList.remove('is-holding'); |
| 242 | }; |
| 243 | link.addEventListener('contextmenu', (event) => { |
| 244 | event.preventDefault(); |
| 245 | cancel(); |
| 246 | suppressClick = true; |
| 247 | openMenu(event.clientX, event.clientY, day, link); |
| 248 | }); |
| 249 | link.addEventListener('pointerdown', (event) => { |
| 250 | if (event.pointerType === 'mouse' || event.button !== 0) return; |
| 251 | startX = event.clientX; |
| 252 | startY = event.clientY; |
| 253 | suppressClick = false; |
| 254 | link.classList.add('is-holding'); |
| 255 | timer = setTimeout(() => { |
| 256 | timer = null; |
| 257 | suppressClick = true; |
| 258 | openMenu(startX, startY, day, link); |
| 259 | }, 550); |
| 260 | }); |
| 261 | link.addEventListener('pointermove', (event) => { |
| 262 | if (timer && Math.hypot(event.clientX - startX, event.clientY - startY) > 12) cancel(); |
| 263 | }); |
| 264 | link.addEventListener('pointerup', cancel); |
| 265 | link.addEventListener('pointercancel', cancel); |
| 266 | link.addEventListener('selectstart', (event) => event.preventDefault()); |
| 267 | link.addEventListener('dragstart', (event) => event.preventDefault()); |
| 268 | link.addEventListener('click', (event) => { |
| 269 | if (!suppressClick) return; |
| 270 | event.preventDefault(); |
| 271 | suppressClick = false; |
| 272 | }); |
| 273 | } |
| 274 | |
| 275 | function unreadLabel(count) { |
| 276 | if (count === 1) return '1 dag ongelezen'; |
| 277 | return count + ' dagen ongelezen'; |
| 278 | } |
| 279 | |
| 280 | function friendInitial(name) { |
| 281 | const trimmed = String(name || '').trim(); |
| 282 | const first = Array.from(trimmed)[0] || '?'; |
| 283 | return first.toLocaleUpperCase('nl'); |
| 284 | } |
| 285 | |
| 286 | function friendColor(id) { |
| 287 | const palette = ['#8a624f', '#6d7a62', '#5f6e78', '#7a6558', '#6a5d78', '#8d5346']; |
| 288 | const key = String(id || ''); |
| 289 | let hash = 0; |
| 290 | for (let index = 0; index < key.length; index += 1) hash = (hash * 33 + key.charCodeAt(index)) >>> 0; |
| 291 | return palette[hash % palette.length]; |
| 292 | } |
| 293 | |
| 294 | function friendDot(friend) { |
| 295 | const label = friend.name || 'Vriend'; |
| 296 | const dot = el('span', { class: 'friend-dot', title: label }); |
| 297 | dot.style.background = friendColor(friend.id || label); |
| 298 | dot.setAttribute('aria-hidden', 'true'); |
| 299 | if (friend.avatar_url) { |
| 300 | const img = el('img', { |
| 301 | src: friend.avatar_url, |
| 302 | alt: '', |
| 303 | width: '18', |
| 304 | height: '18', |
| 305 | referrerpolicy: 'no-referrer', |
| 306 | }); |
| 307 | img.addEventListener('error', () => { |
| 308 | img.remove(); |
| 309 | dot.textContent = friendInitial(label); |
| 310 | }); |
| 311 | dot.append(img); |
| 312 | } else { |
| 313 | dot.textContent = friendInitial(label); |
| 314 | } |
| 315 | return dot; |
| 316 | } |
| 317 | |
| 318 | function friendReadsLabel(readers) { |
| 319 | const names = readers.map((friend) => friend.name).filter((name) => name); |
| 320 | if (names.length === 1) return 'Gelezen door ' + names[0]; |
| 321 | return 'Gelezen door ' + names.join(', '); |
| 322 | } |
| 323 | |
| 324 | function paintFriendReads(byDay) { |
| 325 | document.querySelectorAll('.day-link').forEach((link) => { |
| 326 | const existing = link.querySelector('.friend-reads'); |
| 327 | if (existing) existing.remove(); |
| 328 | link.classList.remove('has-friends'); |
| 329 | const date = link.getAttribute('data-date'); |
| 330 | const readers = date && byDay && byDay[date] ? byDay[date] : []; |
| 331 | if (!readers.length) return; |
| 332 | const row = el('span', { class: 'friend-reads', 'aria-label': friendReadsLabel(readers) }, readers.slice(0, 5).map(friendDot)); |
| 333 | link.classList.add('has-friends'); |
| 334 | link.append(row); |
| 335 | }); |
| 336 | } |
| 337 | |
| 338 | function paintOverview(data) { |
| 339 | const days = data.days || []; |
| 340 | const visible = data.weekDays || []; |
| 341 | const week = data.week; |
| 342 | const unread = days.filter((day) => !day.read); |
| 343 | const wrap = el('div', { class: 'continue-wrap' }); |
| 344 | if (!days.length) { |
| 345 | wrap.append(el('p', { class: 'empty' }, [state.me.admin ? 'Er staan nog geen dagen in het boek.' : 'Er staan nog geen verhalen klaar.'])); |
| 346 | if (state.me.admin) wrap.append(el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag'])); |
| 347 | } else if (unread.length) { |
| 348 | wrap.append(el('a', { class: 'button primary continue', href: '#/dag/' + unread[0].date }, ['Verderlezen'])); |
| 349 | wrap.append(el('p', { class: 'continue-note' }, [unreadLabel(unread.length)])); |
| 350 | } else { |
| 351 | const done = el('button', { class: 'button continue', type: 'button', disabled: 'disabled' }, ['Alles gelezen']); |
| 352 | wrap.append(done); |
| 353 | } |
| 354 | const links = []; |
| 355 | if (week.hasPrevious) links.push(el('a', { class: 'button quiet week-prev', href: '#/week/' + week.previous }, ['← Vorige week'])); |
| 356 | if (week.hasNext) links.push(el('a', { class: 'button quiet week-next', href: '#/week/' + week.next }, ['Volgende week →'])); |
| 357 | const nodes = [el('h1', { class: 'week-label' }, [week.label])]; |
| 358 | if (links.length) nodes.push(el('nav', { class: 'week-nav', 'aria-label': 'Weken' }, links)); |
| 359 | nodes.push(wrap); |
| 360 | if (visible.length) { |
| 361 | const list = el('ol', { class: 'day-list' }); |
| 362 | visible.forEach((day) => { |
| 363 | const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date, 'data-date': day.date }, [ |
| 364 | el('span', { class: 'day-date' }, [formatDate(day.date)]), |
| 365 | el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']), |
| 366 | el('span', { class: 'day-title' }, [day.title]), |
| 367 | ]); |
| 368 | if (!day.complete) link.append(el('span', { class: 'badge' }, ['Onvolledig'])); |
| 369 | bindDayLink(link, day); |
| 370 | list.append(el('li', {}, [link])); |
| 371 | }); |
| 372 | nodes.push(list); |
| 373 | app.replaceChildren(...nodes); |
| 374 | const firstUnread = list.querySelector('.unread'); |
| 375 | if (firstUnread) firstUnread.scrollIntoView({ block: 'nearest' }); |
| 376 | } else { |
| 377 | if (days.length) nodes.push(el('p', { class: 'empty' }, ['Geen dagen in deze week.'])); |
| 378 | app.replaceChildren(...nodes); |
| 379 | } |
| 380 | document.title = week.label + ' · Verhalenboek'; |
| 381 | } |
| 382 | |
| 383 | function paintDay(day) { |
| 384 | const head = el('header', { class: 'day-head' }, [ |
| 385 | el('p', { class: 'day-kicker' }, [formatDate(day.date)]), |
| 386 | el('h1', {}, [day.title]), |
| 387 | ]); |
| 388 | const top = el('div', { class: 'pager' }); |
| 389 | if (day.previous) top.append(el('a', { class: 'button quiet', href: '#/dag/' + day.previous }, ['← Vorige dag'])); |
| 390 | const stories = day.stories.map((story) => el('article', { class: 'story' }, [ |
| 391 | el('h2', {}, [el('span', {}, [ROMAN[(story.position || 1) - 1] || String(story.position)]), story.title]), |
| 392 | ...story.paragraphs.map((paragraph) => el('p', {}, [paragraph])), |
| 393 | ])); |
| 394 | if (!day.complete) stories.unshift(el('p', { class: 'form-error' }, ['Deze dag is onvolledig.'])); |
| 395 | const bottom = el('div', { class: 'pager bottom' }); |
| 396 | if (day.next) bottom.append(el('a', { class: 'button primary continue', href: '#/dag/' + day.next }, ['Volgende dag →'])); |
| 397 | else bottom.append(el('a', { class: 'button quiet', href: '#/' }, ['Terug naar het overzicht'])); |
| 398 | app.replaceChildren(head, top, ...stories, bottom); |
| 399 | } |
| 400 | |
| 401 | function choice(name, value, label, current) { |
| 402 | const input = el('input', { type: 'radio', name, value }); |
| 403 | input.checked = current === value; |
| 404 | return el('label', {}, [input, label]); |
| 405 | } |
| 406 | |
| 407 | function paintSettings() { |
| 408 | const theme = el('fieldset', {}, [ |
| 409 | el('legend', {}, ['Weergave']), |
| 410 | el('div', { class: 'choice' }, [ |
| 411 | choice('theme', 'system', 'Systeem', state.me.theme), |
| 412 | choice('theme', 'light', 'Licht', state.me.theme), |
| 413 | choice('theme', 'dark', 'Donker', state.me.theme), |
| 414 | ]), |
| 415 | ]); |
| 416 | const font = el('fieldset', {}, [ |
| 417 | el('legend', {}, ['Lettertype']), |
| 418 | el('div', { class: 'choice' }, [ |
| 419 | choice('font', 'serif', 'Serif', state.me.font), |
| 420 | choice('font', 'sans', 'Schreefloos', state.me.font), |
| 421 | choice('font', 'rounded', 'Rond', state.me.font), |
| 422 | ]), |
| 423 | ]); |
| 424 | const preview = el('p', { class: 'lede' }, ['Zo lees je een verhaal. De regen tikte zacht op het dak, en de bladzijde bleef openliggen.']); |
| 425 | const error = el('p', { class: 'form-error' }); |
| 426 | async function persist() { |
| 427 | const nextTheme = theme.querySelector('input:checked').value; |
| 428 | const nextFont = font.querySelector('input:checked').value; |
| 429 | const previous = { theme: state.me.theme, font: state.me.font }; |
| 430 | state.me = { ...state.me, theme: nextTheme, font: nextFont }; |
| 431 | applyPrefs(state.me); |
| 432 | try { |
| 433 | const result = await api('PUT', '/me/settings', { theme: nextTheme, font: nextFont }); |
| 434 | state.me = result.user; |
| 435 | applyPrefs(state.me); |
| 436 | error.textContent = ''; |
| 437 | } catch (failure) { |
| 438 | state.me = { ...state.me, ...previous }; |
| 439 | applyPrefs(state.me); |
| 440 | theme.querySelector('input[value="' + previous.theme + '"]').checked = true; |
| 441 | font.querySelector('input[value="' + previous.font + '"]').checked = true; |
| 442 | error.textContent = failure.message; |
| 443 | } |
| 444 | } |
| 445 | theme.addEventListener('change', persist); |
| 446 | font.addEventListener('change', persist); |
| 447 | const actions = el('div', { class: 'row-actions' }, [ |
| 448 | el('button', { class: 'quiet', type: 'button' }, ['Exporteer mijn gegevens (JSON)']), |
| 449 | el('button', { class: 'danger', type: 'button' }, ['Uitloggen']), |
| 450 | ]); |
| 451 | actions.children[0].addEventListener('click', () => { window.location.href = 'api.php/me/export'; }); |
| 452 | actions.children[1].addEventListener('click', async () => { |
| 453 | try { |
| 454 | await api('POST', '/session/logout'); |
| 455 | window.location.href = 'index.php'; |
| 456 | } catch (failure) { toast(failure.message); } |
| 457 | }); |
| 458 | const section = el('section', { class: 'settings' }, [ |
| 459 | el('h1', {}, ['Instellingen']), |
| 460 | el('p', { class: 'continue-note' }, ['Ingelogd als ' + state.me.name + (state.me.admin ? ' · beheerder' : '')]), |
| 461 | theme, font, preview, error, actions, |
| 462 | ]); |
| 463 | if (state.local) { |
| 464 | const other = state.me.name === 'test_user_2' ? 'test_user_1' : 'test_user_2'; |
| 465 | const swap = el('button', { class: 'quiet', type: 'button' }, ['Wissel naar ' + other]); |
| 466 | swap.addEventListener('click', async () => { |
| 467 | try { |
| 468 | await api('POST', '/session/switch', { user: other }); |
| 469 | window.location.reload(); |
| 470 | } catch (failure) { toast(failure.message); } |
| 471 | }); |
| 472 | section.append(swap); |
| 473 | } |
| 474 | app.replaceChildren(section); |
| 475 | } |
| 476 | |
| 477 | function paragraphField(value) { |
| 478 | const area = el('textarea', { rows: '4' }); |
| 479 | area.value = value || ''; |
| 480 | const remove = el('button', { class: 'quiet', type: 'button' }, ['Alinea verwijderen']); |
| 481 | const block = el('div', { class: 'paragraph-actions' }, [area, remove]); |
| 482 | remove.addEventListener('click', () => { |
| 483 | const boxes = block.parentElement.querySelectorAll('textarea'); |
| 484 | if (boxes.length <= 1) { area.value = ''; return; } |
| 485 | block.remove(); |
| 486 | }); |
| 487 | return block; |
| 488 | } |
| 489 | |
| 490 | function storyField(position, story, onDelete) { |
| 491 | const title = el('input', { type: 'text', maxlength: '200', 'data-title': '1', required: 'required' }); |
| 492 | title.value = story.title || ''; |
| 493 | const paragraphs = el('div', {}); |
| 494 | (story.paragraphs && story.paragraphs.length ? story.paragraphs : ['']).forEach((paragraph) => paragraphs.append(paragraphField(paragraph))); |
| 495 | const add = el('button', { class: 'quiet', type: 'button' }, ['Alinea toevoegen']); |
| 496 | add.addEventListener('click', () => paragraphs.append(paragraphField(''))); |
| 497 | const fieldset = el('fieldset', { 'data-position': String(position) }, [ |
| 498 | el('legend', {}, ['Verhaal ' + ROMAN[position - 1]]), |
| 499 | el('label', {}, ['Titel', title]), |
| 500 | paragraphs, |
| 501 | add, |
| 502 | ]); |
| 503 | if (onDelete) { |
| 504 | const remove = el('button', { class: 'danger', type: 'button' }, ['Dit verhaal verwijderen']); |
| 505 | remove.addEventListener('click', onDelete); |
| 506 | fieldset.append(remove); |
| 507 | } |
| 508 | return fieldset; |
| 509 | } |
| 510 | |
| 511 | function readStories(form) { |
| 512 | return [...form.querySelectorAll('fieldset')].map((fieldset) => ({ |
| 513 | title: fieldset.querySelector('[data-title]').value, |
| 514 | paragraphs: [...fieldset.querySelectorAll('textarea')].map((area) => area.value), |
| 515 | })); |
| 516 | } |
| 517 | |
| 518 | async function paintEditor(date) { |
| 519 | const creating = !date; |
| 520 | let day = { title: '', stories: [{}, {}, {}] }; |
| 521 | if (!creating) day = await api('GET', '/days/' + date); |
| 522 | const byPosition = {}; |
| 523 | (day.stories || []).forEach((story) => { byPosition[story.position] = story; }); |
| 524 | const title = el('input', { type: 'text', maxlength: '200', required: 'required' }); |
| 525 | title.value = day.title || ''; |
| 526 | const dateInput = el('input', { type: 'date', required: 'required' }); |
| 527 | if (creating) dateInput.value = ''; |
| 528 | else { dateInput.value = date; dateInput.readOnly = true; } |
| 529 | const error = el('p', { class: 'form-error' }); |
| 530 | const form = el('form', { class: 'editor' }, [ |
| 531 | el('h1', {}, [creating ? 'Nieuwe dag' : 'Dag bewerken']), |
| 532 | el('label', {}, ['Datum', dateInput]), |
| 533 | el('label', {}, ['Titel van de dag', title]), |
| 534 | ]); |
| 535 | for (let position = 1; position <= 3; position += 1) { |
| 536 | const existing = byPosition[position]; |
| 537 | form.append(storyField(position, existing || { title: '', paragraphs: [''] }, !creating && existing ? async () => { |
| 538 | if (!window.confirm('Dit verhaal verwijderen? De dag wordt onvolledig.')) return; |
| 539 | try { |
| 540 | await api('DELETE', '/days/' + date + '/stories/' + position); |
| 541 | await render(); |
| 542 | } catch (failure) { error.textContent = failure.message; } |
| 543 | } : null)); |
| 544 | } |
| 545 | const save = el('button', { class: 'primary', type: 'submit' }, ['Dag opslaan']); |
| 546 | form.append(error, save); |
| 547 | if (!creating) { |
| 548 | const remove = el('button', { class: 'danger', type: 'button' }, ['Hele dag verwijderen']); |
| 549 | remove.addEventListener('click', async () => { |
| 550 | if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return; |
| 551 | try { |
| 552 | await api('DELETE', '/days/' + date); |
| 553 | navigateHash('#/beheer'); |
| 554 | } catch (failure) { error.textContent = failure.message; } |
| 555 | }); |
| 556 | form.append(remove); |
| 557 | } |
| 558 | form.addEventListener('submit', async (event) => { |
| 559 | event.preventDefault(); |
| 560 | error.textContent = ''; |
| 561 | save.disabled = true; |
| 562 | const payload = { title: title.value, stories: readStories(form) }; |
| 563 | try { |
| 564 | if (creating) { |
| 565 | const created = await api('POST', '/days', { date: dateInput.value, ...payload }); |
| 566 | navigateHash('#/beheer/' + created.date); |
| 567 | } else { |
| 568 | await api('PUT', '/days/' + date, payload); |
| 569 | toast('Opgeslagen.'); |
| 570 | await render(); |
| 571 | } |
| 572 | } catch (failure) { |
| 573 | error.textContent = failure.message; |
| 574 | save.disabled = false; |
| 575 | } |
| 576 | }); |
| 577 | app.replaceChildren(form); |
| 578 | } |
| 579 | |
| 580 | async function paintBeheer() { |
| 581 | const [days, people] = await Promise.all([api('GET', '/days'), api('GET', '/users')]); |
| 582 | const users = el('div', { class: 'user-list' }); |
| 583 | people.users.forEach((person) => { |
| 584 | const self = person.id === state.me.id; |
| 585 | const action = el('button', { |
| 586 | type: 'button', |
| 587 | class: self ? 'quiet' : (person.admin ? 'danger' : 'primary'), |
| 588 | }, [self ? 'Jij' : (person.admin ? 'Maak lezer' : 'Maak beheerder')]); |
| 589 | action.disabled = self; |
| 590 | if (!self) { |
| 591 | action.addEventListener('click', async () => { |
| 592 | if (person.admin && !window.confirm(person.name + ' is daarna alleen nog lezer. Doorgaan?')) return; |
| 593 | try { |
| 594 | await api('PUT', '/users/' + encodeURIComponent(person.id), { admin: !person.admin }); |
| 595 | toast(person.admin ? person.name + ' is nu lezer.' : person.name + ' is nu beheerder.'); |
| 596 | await render(); |
| 597 | } catch (failure) { toast(failure.message); } |
| 598 | }); |
| 599 | } |
| 600 | users.append(el('div', { class: 'user-row' }, [ |
| 601 | el('div', {}, [ |
| 602 | el('strong', {}, [person.name]), |
| 603 | el('small', {}, [person.id]), |
| 604 | el('span', { class: 'user-role' }, [person.admin ? 'Beheerder' : 'Lezer']), |
| 605 | ]), |
| 606 | action, |
| 607 | ])); |
| 608 | }); |
| 609 | const list = el('div', {}); |
| 610 | days.days.forEach((day) => { |
| 611 | list.append(el('div', { class: 'admin-day' }, [ |
| 612 | el('a', { href: '#/beheer/' + day.date }, [ |
| 613 | el('strong', {}, [day.title]), |
| 614 | document.createElement('br'), |
| 615 | el('small', {}, [formatDate(day.date) + (day.complete ? '' : ' · onvolledig')]), |
| 616 | ]), |
| 617 | el('a', { class: 'button quiet', href: '#/dag/' + day.date }, ['Lezen']), |
| 618 | ])); |
| 619 | }); |
| 620 | if (!days.days.length) list.append(el('p', { class: 'empty' }, ['Nog geen dagen.'])); |
| 621 | app.replaceChildren(el('section', { class: 'panel' }, [ |
| 622 | el('h1', {}, ['Beheer']), |
| 623 | el('h2', {}, ['Gebruikers']), |
| 624 | el('p', { class: 'lede' }, ['Maak iemand anders beheerder, of haal die rol weer weg. Je eigen rol blijft staan.']), |
| 625 | users, |
| 626 | el('h2', {}, ['Dagen']), |
| 627 | el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag']), |
| 628 | list, |
| 629 | ])); |
| 630 | } |
| 631 | |
| 632 | function tokenPanel(title, token) { |
| 633 | const field = el('textarea', { readonly: 'readonly', rows: '3' }); |
| 634 | field.value = token; |
| 635 | const copy = el('button', { class: 'quiet', type: 'button' }, ['Kopieer']); |
| 636 | copy.addEventListener('click', async () => { |
| 637 | field.select(); |
| 638 | try { await navigator.clipboard.writeText(field.value); toast('Gekopieerd.'); } |
| 639 | catch (failure) { toast('Selecteer de sleutel en kopieer hem handmatig.'); } |
| 640 | }); |
| 641 | return el('div', { class: 'token-once' }, [el('strong', {}, [title]), field, copy]); |
| 642 | } |
| 643 | |
| 644 | function paintKeys(keys) { |
| 645 | const name = el('input', { type: 'text', maxlength: '80', required: 'required' }); |
| 646 | const error = el('p', { class: 'form-error' }); |
| 647 | const form = el('form', {}, [ |
| 648 | el('label', {}, ['Naam van de sleutel', name]), |
| 649 | el('button', { class: 'primary', type: 'submit' }, ['Sleutel aanmaken']), |
| 650 | error, |
| 651 | ]); |
| 652 | form.addEventListener('submit', async (event) => { |
| 653 | event.preventDefault(); |
| 654 | error.textContent = ''; |
| 655 | try { |
| 656 | const result = await api('POST', '/keys', { name: name.value }); |
| 657 | state.freshKey = result.key; |
| 658 | state.revealedKey = null; |
| 659 | await render(); |
| 660 | } catch (failure) { error.textContent = failure.message; } |
| 661 | }); |
| 662 | const section = el('section', { class: 'keys' }, [el('h1', {}, ['API-sleutels']), form]); |
| 663 | if (state.revealedKey && state.revealedKey.token) { |
| 664 | section.append(tokenPanel('Sleutel van ' + state.revealedKey.name, state.revealedKey.token)); |
| 665 | } else if (state.freshKey && state.freshKey.token) { |
| 666 | section.append(tokenPanel('Nieuwe sleutel. Tik er later opnieuw op om hem te zien.', state.freshKey.token)); |
| 667 | } |
| 668 | const list = el('div', {}); |
| 669 | keys.forEach((key) => { |
| 670 | const open = el('button', { type: 'button', class: 'key-open' }, [ |
| 671 | el('span', { class: key.revoked ? 'revoked' : '' }, [key.name]), |
| 672 | el('span', {}, [key.prefix + '…']), |
| 673 | el('span', {}, [key.revoked ? 'Ingetrokken' : 'Actief']), |
| 674 | ]); |
| 675 | open.addEventListener('click', async () => { |
| 676 | try { |
| 677 | const result = await api('GET', '/keys/' + key.id); |
| 678 | state.freshKey = null; |
| 679 | state.revealedKey = result.key; |
| 680 | await render(); |
| 681 | } catch (failure) { toast(failure.message); } |
| 682 | }); |
| 683 | const revoke = el('button', { class: 'danger', type: 'button' }, ['Intrekken']); |
| 684 | revoke.disabled = key.revoked != null; |
| 685 | revoke.addEventListener('click', async () => { |
| 686 | if (!window.confirm('Deze API-sleutel intrekken? Bestaande scripts kunnen dan niet meer schrijven.')) return; |
| 687 | try { await api('DELETE', '/keys/' + key.id); await render(); } |
| 688 | catch (failure) { toast(failure.message); } |
| 689 | }); |
| 690 | list.append(el('div', { class: 'key-row' }, [open, revoke])); |
| 691 | }); |
| 692 | if (!keys.length) list.append(el('p', { class: 'empty' }, ['Nog geen sleutels.'])); |
| 693 | section.append(el('h2', {}, ['Bestaande sleutels']), el('p', { class: 'lede' }, ['Tik op een sleutel om de volledige sleutel opnieuw te zien.']), list); |
| 694 | app.replaceChildren(section); |
| 695 | } |
| 696 | |
| 697 | function wikiSlugOk(value) { |
| 698 | return typeof value === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value); |
| 699 | } |
| 700 | |
| 701 | function appendWikiInline(parent, part) { |
| 702 | if (!part || typeof part !== 'object') return; |
| 703 | if (part.type === 'link' && part.broken === false && wikiSlugOk(part.page) && (part.anchor == null || wikiSlugOk(part.anchor))) { |
| 704 | const href = part.anchor ? '#/wiki/' + part.page + '/' + part.anchor : '#/wiki/' + part.page; |
| 705 | parent.append(el('a', { href, class: 'wiki-link' }, [part.text || part.page])); |
| 706 | return; |
| 707 | } |
| 708 | if (part.type === 'link') { |
| 709 | const mark = el('span', { class: 'wiki-broken' }, [part.text || '']); |
| 710 | mark.append(el('span', { class: 'wiki-missing' }, ['ontbreekt'])); |
| 711 | parent.append(mark); |
| 712 | return; |
| 713 | } |
| 714 | parent.append(document.createTextNode(typeof part.text === 'string' ? part.text : '')); |
| 715 | } |
| 716 | |
| 717 | function wikiChapterNode(chapter, currentAnchor) { |
| 718 | const section = el('section', { |
| 719 | class: 'wiki-chapter' + (chapter.anchor === currentAnchor ? ' is-target' : ''), |
| 720 | id: 'wiki-' + chapter.anchor, |
| 721 | }); |
| 722 | if (chapter.title) section.append(el('h2', {}, [chapter.title])); |
| 723 | (chapter.blocks || []).forEach((block) => { |
| 724 | const paragraph = el('p', {}); |
| 725 | (block.inlines || []).forEach((part) => appendWikiInline(paragraph, part)); |
| 726 | section.append(paragraph); |
| 727 | }); |
| 728 | if (!chapter.title && !(chapter.blocks || []).length) section.append(el('p', {}, [''])); |
| 729 | return section; |
| 730 | } |
| 731 | |
| 732 | function paintWikiArticle(page, anchor) { |
| 733 | const section = el('article', { class: 'wiki-page' }, [ |
| 734 | el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]), |
| 735 | el('p', { class: 'eyebrow' }, [page.category.title]), |
| 736 | el('h1', {}, [page.title]), |
| 737 | ]); |
| 738 | if (page.chapters && page.chapters.length) { |
| 739 | const toc = el('nav', { class: 'wiki-toc', 'aria-label': 'Hoofdstukken' }); |
| 740 | page.chapters.forEach((chapter) => { |
| 741 | toc.append(el('a', { href: '#/wiki/' + page.slug + '/' + chapter.anchor }, [chapter.title || 'Inleiding'])); |
| 742 | }); |
| 743 | section.append(toc); |
| 744 | } |
| 745 | (page.chapters || []).forEach((chapter) => section.append(wikiChapterNode(chapter, anchor))); |
| 746 | if (state.me.admin) { |
| 747 | const remove = el('button', { class: 'danger', type: 'button' }, ['Pagina verwijderen']); |
| 748 | remove.addEventListener('click', async () => { |
| 749 | if (!window.confirm('Deze wikipagina verwijderen? Dit kan niet ongedaan worden.')) return; |
| 750 | try { |
| 751 | await api('DELETE', '/wiki/pages/' + page.slug); |
| 752 | navigateHash('#/wiki'); |
| 753 | } catch (failure) { toast(failure.message); } |
| 754 | }); |
| 755 | section.append(el('div', { class: 'wiki-actions' }, [ |
| 756 | el('a', { class: 'button primary', href: '#/wiki/bewerken/' + page.slug }, ['Bewerken']), |
| 757 | remove, |
| 758 | ])); |
| 759 | } |
| 760 | app.replaceChildren(section); |
| 761 | document.title = page.title + ' · Wiki · Verhalenboek'; |
| 762 | } |
| 763 | |
| 764 | async function paintWikiIndex() { |
| 765 | const data = await api('GET', '/wiki/categories'); |
| 766 | const query = el('input', { type: 'search', maxlength: '200', placeholder: 'Zoek op titel of tekst' }); |
| 767 | query.value = state.wikiQuery || ''; |
| 768 | const form = el('form', { class: 'wiki-search' }, [ |
| 769 | el('label', {}, ['Zoeken', query]), |
| 770 | el('button', { class: 'quiet', type: 'submit' }, ['Zoeken']), |
| 771 | ]); |
| 772 | form.addEventListener('submit', (event) => { |
| 773 | event.preventDefault(); |
| 774 | state.wikiQuery = query.value.trim(); |
| 775 | render(); |
| 776 | }); |
| 777 | const section = el('section', { class: 'panel' }, [ |
| 778 | el('h1', {}, ['Wiki']), |
| 779 | el('p', { class: 'lede' }, ['Achtergrond bij de verhalen, per categorie.']), |
| 780 | form, |
| 781 | ]); |
| 782 | if (state.me.admin) { |
| 783 | section.append(el('div', { class: 'wiki-actions' }, [ |
| 784 | el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']), |
| 785 | el('a', { class: 'button quiet', href: '#/wiki/nieuw' }, ['Nieuwe pagina']), |
| 786 | ])); |
| 787 | } |
| 788 | if (state.wikiQuery) { |
| 789 | const found = await api('GET', '/wiki/pages?q=' + encodeURIComponent(state.wikiQuery)); |
| 790 | const results = el('div', {}); |
| 791 | found.pages.forEach((page) => { |
| 792 | results.append(el('a', { class: 'wiki-result', href: '#/wiki/' + page.slug }, [ |
| 793 | el('strong', {}, [page.title]), |
| 794 | document.createElement('br'), |
| 795 | el('small', {}, [page.category.title]), |
| 796 | ])); |
| 797 | }); |
| 798 | if (!found.pages.length) results.append(el('p', { class: 'empty' }, ['Geen pagina\'s gevonden.'])); |
| 799 | section.append(el('h2', {}, ['Resultaten']), results); |
| 800 | } |
| 801 | if (!data.categories.length) section.append(el('p', { class: 'empty' }, ['Nog geen categorieën.'])); |
| 802 | data.categories.forEach((category) => { |
| 803 | const head = el('div', { class: 'wiki-cat-head' }, [el('h2', {}, [category.title])]); |
| 804 | if (state.me.admin) { |
| 805 | head.append(el('a', { class: 'button quiet', href: '#/wiki/categorie/' + category.slug }, ['Wijzig'])); |
| 806 | } |
| 807 | const block = el('section', { class: 'wiki-category' }, [head]); |
| 808 | if (!category.pages.length) block.append(el('p', { class: 'empty' }, ['Nog geen pagina\'s.'])); |
| 809 | category.pages.forEach((page) => { |
| 810 | block.append(el('a', { class: 'wiki-page-link', href: '#/wiki/' + page.slug }, [page.title])); |
| 811 | }); |
| 812 | if (state.me.admin) { |
| 813 | block.append(el('p', {}, [el('a', { href: '#/wiki/nieuw/' + category.slug }, ['Pagina in ' + category.title])])); |
| 814 | } |
| 815 | section.append(block); |
| 816 | }); |
| 817 | app.replaceChildren(section); |
| 818 | document.title = 'Wiki · Verhalenboek'; |
| 819 | } |
| 820 | |
| 821 | async function paintWikiCategoryForm(slug) { |
| 822 | const creating = !slug; |
| 823 | const existing = creating ? { title: '', slug: '' } : await api('GET', '/wiki/categories/' + slug); |
| 824 | const title = el('input', { type: 'text', maxlength: '80', required: 'required' }); |
| 825 | title.value = existing.title || ''; |
| 826 | const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' }); |
| 827 | slugInput.value = existing.slug || ''; |
| 828 | const error = el('p', { class: 'form-error' }); |
| 829 | const form = el('form', { class: 'editor' }, [ |
| 830 | el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]), |
| 831 | el('h1', {}, [creating ? 'Nieuwe categorie' : 'Categorie wijzigen']), |
| 832 | el('label', {}, ['Titel', title]), |
| 833 | el('label', {}, ['Slug', slugInput]), |
| 834 | el('p', { class: 'hint' }, ['Leeg laten maakt een slug van de titel. Alleen kleine letters, cijfers en streepjes.']), |
| 835 | error, |
| 836 | el('button', { class: 'primary', type: 'submit' }, ['Opslaan']), |
| 837 | ]); |
| 838 | form.addEventListener('submit', async (event) => { |
| 839 | event.preventDefault(); |
| 840 | error.textContent = ''; |
| 841 | const payload = { title: title.value }; |
| 842 | if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim(); |
| 843 | else if (!creating) payload.slug = ''; |
| 844 | try { |
| 845 | const saved = creating |
| 846 | ? await api('POST', '/wiki/categories', payload) |
| 847 | : await api('PUT', '/wiki/categories/' + slug, payload); |
| 848 | toast('Opgeslagen.'); |
| 849 | navigateHash('#/wiki'); |
| 850 | } catch (failure) { error.textContent = failure.message; } |
| 851 | }); |
| 852 | if (!creating) { |
| 853 | const remove = el('button', { class: 'danger', type: 'button' }, ['Categorie verwijderen']); |
| 854 | remove.addEventListener('click', async () => { |
| 855 | if (!window.confirm('Deze categorie verwijderen? Dat kan alleen als er geen pagina\'s meer in staan.')) return; |
| 856 | try { |
| 857 | await api('DELETE', '/wiki/categories/' + slug); |
| 858 | navigateHash('#/wiki'); |
| 859 | } catch (failure) { error.textContent = failure.message; } |
| 860 | }); |
| 861 | form.append(remove); |
| 862 | } |
| 863 | app.replaceChildren(form); |
| 864 | document.title = (creating ? 'Nieuwe categorie' : existing.title) + ' · Wiki · Verhalenboek'; |
| 865 | } |
| 866 | |
| 867 | async function paintWikiPageForm(slug, presetCategory) { |
| 868 | const creating = !slug; |
| 869 | const [listed, existing] = await Promise.all([ |
| 870 | api('GET', '/wiki/categories'), |
| 871 | creating ? Promise.resolve(null) : api('GET', '/wiki/pages/' + slug), |
| 872 | ]); |
| 873 | if (!listed.categories.length) { |
| 874 | app.replaceChildren(el('section', { class: 'panel' }, [ |
| 875 | el('p', { class: 'pager' }, [el('a', { href: '#/wiki' }, ['← Wiki'])]), |
| 876 | el('h1', {}, ['Nieuwe pagina']), |
| 877 | el('p', { class: 'empty' }, ['Maak eerst een categorie.']), |
| 878 | el('a', { class: 'button primary', href: '#/wiki/categorie/nieuw' }, ['Nieuwe categorie']), |
| 879 | ])); |
| 880 | return; |
| 881 | } |
| 882 | const title = el('input', { type: 'text', maxlength: '200', required: 'required' }); |
| 883 | title.value = existing ? existing.title : ''; |
| 884 | const slugInput = el('input', { type: 'text', maxlength: '80', spellcheck: 'false', autocapitalize: 'off' }); |
| 885 | slugInput.value = existing ? existing.slug : ''; |
| 886 | const chosen = existing ? existing.category.slug : presetCategory; |
| 887 | const select = el('select', { required: 'required' }); |
| 888 | listed.categories.forEach((category) => { |
| 889 | select.append(el('option', { |
| 890 | value: category.slug, |
| 891 | selected: category.slug === chosen ? 'selected' : null, |
| 892 | }, [category.title])); |
| 893 | }); |
| 894 | const content = el('textarea', { class: 'wiki-source', rows: '14' }); |
| 895 | content.value = existing ? existing.content : ''; |
| 896 | const error = el('p', { class: 'form-error' }); |
| 897 | const form = el('form', { class: 'editor' }, [ |
| 898 | el('p', { class: 'pager' }, [el('a', { href: creating ? '#/wiki' : '#/wiki/' + slug }, [creating ? '← Wiki' : '← Pagina'])]), |
| 899 | el('h1', {}, [creating ? 'Nieuwe pagina' : 'Pagina bewerken']), |
| 900 | el('label', {}, ['Categorie', select]), |
| 901 | el('label', {}, ['Titel', title]), |
| 902 | el('label', {}, ['Slug', slugInput]), |
| 903 | el('label', {}, ['Tekst', content]), |
| 904 | el('p', { class: 'hint' }, [ |
| 905 | 'Een hoofdstuk begint met ## en een titel op een eigen regel. Verwijzingen: [[pagina-slug]], [[#hoofdstuk]] en [[pagina-slug#hoofdstuk|tekst]]. Een kapotte verwijzing blijft zichtbaar en is geen link.', |
| 906 | ]), |
| 907 | error, |
| 908 | el('button', { class: 'primary', type: 'submit' }, ['Opslaan']), |
| 909 | ]); |
| 910 | form.addEventListener('submit', async (event) => { |
| 911 | event.preventDefault(); |
| 912 | error.textContent = ''; |
| 913 | const payload = { title: title.value, category: select.value, content: content.value }; |
| 914 | if (slugInput.value.trim() !== '') payload.slug = slugInput.value.trim(); |
| 915 | else if (!creating) payload.slug = ''; |
| 916 | try { |
| 917 | const saved = creating |
| 918 | ? await api('POST', '/wiki/pages', payload) |
| 919 | : await api('PUT', '/wiki/pages/' + slug, payload); |
| 920 | toast('Opgeslagen.'); |
| 921 | navigateHash('#/wiki/' + saved.slug); |
| 922 | } catch (failure) { error.textContent = failure.message; } |
| 923 | }); |
| 924 | app.replaceChildren(form); |
| 925 | document.title = (creating ? 'Nieuwe pagina' : 'Bewerken') + ' · Wiki · Verhalenboek'; |
| 926 | } |
| 927 | |
| 928 | function wikiDenied() { |
| 929 | app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit wijzigen.']), el('a', { href: '#/wiki' }, ['Naar de wiki'])); |
| 930 | } |
| 931 | |
| 932 | function syncWikiNav() { |
| 933 | const nav = document.querySelector('nav.nav'); |
| 934 | if (!nav) return; |
| 935 | const link = nav.querySelector('a[data-nav="/wiki"]'); |
| 936 | if (state.showWiki) { |
| 937 | if (link) return; |
| 938 | const created = el('a', { href: '#/wiki', 'data-nav': '/wiki' }, ['Wiki']); |
| 939 | const settings = nav.querySelector('a[data-nav="/instellingen"]'); |
| 940 | if (settings) settings.before(created); |
| 941 | else nav.append(created); |
| 942 | return; |
| 943 | } |
| 944 | if (link) link.remove(); |
| 945 | } |
| 946 | |
| 947 | async function render() { |
| 948 | const token = ++renderToken; |
| 949 | const path = pathNow(); |
| 950 | const traversal = historyTraversal; |
| 951 | historyTraversal = false; |
| 952 | if (path !== '/sleutels') { |
| 953 | state.freshKey = null; |
| 954 | state.revealedKey = null; |
| 955 | } |
| 956 | if (path !== '/wiki' && !path.startsWith('/wiki/')) state.wikiQuery = ''; |
| 957 | closeMenu(); |
| 958 | highlight(path); |
| 959 | document.title = 'Verhalenboek'; |
| 960 | let settled = false; |
| 961 | const finishScroll = () => { |
| 962 | if (settled || token !== renderToken) return; |
| 963 | settled = true; |
| 964 | settleScroll(path, traversal); |
| 965 | }; |
| 966 | try { |
| 967 | if ((path === '/wiki' || path.startsWith('/wiki/')) && !state.showWiki) { |
| 968 | navigateHash('#/'); |
| 969 | return; |
| 970 | } |
| 971 | const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/); |
| 972 | if (path === '/' || path === '' || weekMatch) { |
| 973 | const friendsPromise = api('GET', '/friend-reads').catch(() => ({ days: {} })); |
| 974 | const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null)); |
| 975 | if (token !== renderToken) return; |
| 976 | paintOverview(data); |
| 977 | friendsPromise.then((friends) => { |
| 978 | if (token !== renderToken) return; |
| 979 | paintFriendReads((friends && friends.days) || {}); |
| 980 | }); |
| 981 | } else if (path === '/wiki') { |
| 982 | await paintWikiIndex(); |
| 983 | } else if (path === '/wiki/categorie/nieuw') { |
| 984 | if (!state.me.admin) { wikiDenied(); return; } |
| 985 | await paintWikiCategoryForm(null); |
| 986 | } else if (/^\/wiki\/categorie\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) { |
| 987 | if (!state.me.admin) { wikiDenied(); return; } |
| 988 | await paintWikiCategoryForm(path.slice('/wiki/categorie/'.length)); |
| 989 | } else if (path === '/wiki/nieuw' || /^\/wiki\/nieuw\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) { |
| 990 | if (!state.me.admin) { wikiDenied(); return; } |
| 991 | const preset = path === '/wiki/nieuw' ? null : path.slice('/wiki/nieuw/'.length); |
| 992 | await paintWikiPageForm(null, preset); |
| 993 | } else if (/^\/wiki\/bewerken\/([a-z0-9]+(?:-[a-z0-9]+)*)$/.test(path)) { |
| 994 | if (!state.me.admin) { wikiDenied(); return; } |
| 995 | await paintWikiPageForm(path.slice('/wiki/bewerken/'.length), null); |
| 996 | } else if (wikiReading(path)) { |
| 997 | const reading = wikiReading(path); |
| 998 | const page = await api('GET', '/wiki/pages/' + reading.slug); |
| 999 | if (token !== renderToken) return; |
| 1000 | paintWikiArticle(page, reading.anchor); |
| 1001 | } else if (path === '/instellingen') { |
| 1002 | paintSettings(); |
| 1003 | } else if (path === '/beheer') { |
| 1004 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 1005 | await paintBeheer(); |
| 1006 | } else if (path === '/beheer/nieuw') { |
| 1007 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 1008 | await paintEditor(null); |
| 1009 | } else if (/^\/beheer\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 1010 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 1011 | await paintEditor(path.slice('/beheer/'.length)); |
| 1012 | } else if (path === '/sleutels') { |
| 1013 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 1014 | const data = await api('GET', '/keys'); |
| 1015 | if (token !== renderToken) return; |
| 1016 | paintKeys(data.keys); |
| 1017 | } else if (isDayRoute(path)) { |
| 1018 | const date = path.slice(5); |
| 1019 | const day = await api('GET', '/days/' + date); |
| 1020 | if (token !== renderToken) return; |
| 1021 | paintDay(day); |
| 1022 | document.title = day.title + ' · Verhalenboek'; |
| 1023 | // Vóór de lees-POST, anders schildert de browser de nieuwe dag nog onderaan. |
| 1024 | finishScroll(); |
| 1025 | if (!day.read) { |
| 1026 | try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ } |
| 1027 | } |
| 1028 | } else { |
| 1029 | app.replaceChildren(el('p', { class: 'empty' }, ['Deze pagina bestaat niet.']), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 1030 | } |
| 1031 | } catch (error) { |
| 1032 | if (token !== renderToken) return; |
| 1033 | if (error.status === 401) { window.location.href = 'index.php'; return; } |
| 1034 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 1035 | } finally { |
| 1036 | finishScroll(); |
| 1037 | } |
| 1038 | } |
| 1039 | |
| 1040 | async function boot() { |
| 1041 | bindReadMenu(); |
| 1042 | try { |
| 1043 | const me = await api('GET', '/me'); |
| 1044 | state.me = me.user; |
| 1045 | state.csrf = me.csrf; |
| 1046 | state.local = !!me.local; |
| 1047 | state.showWiki = !!me.wiki; |
| 1048 | applyPrefs(me.user); |
| 1049 | syncWikiNav(); |
| 1050 | } catch (error) { |
| 1051 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message])); |
| 1052 | return; |
| 1053 | } |
| 1054 | if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; |
| 1055 | window.addEventListener('popstate', () => { historyTraversal = true; }); |
| 1056 | window.addEventListener('hashchange', () => { render(); }); |
| 1057 | document.addEventListener('click', (event) => { |
| 1058 | if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; |
| 1059 | const link = event.target instanceof Element ? event.target.closest('a[href]') : null; |
| 1060 | if (!link || !(link.getAttribute('href') || '').startsWith('#')) return; |
| 1061 | saveScrollPosition(); |
| 1062 | }, true); |
| 1063 | let scrollSaveTimer = 0; |
| 1064 | window.addEventListener('scroll', () => { |
| 1065 | clearTimeout(scrollSaveTimer); |
| 1066 | scrollSaveTimer = setTimeout(saveScrollPosition, 120); |
| 1067 | }, { passive: true }); |
| 1068 | window.addEventListener('pagehide', saveScrollPosition); |
| 1069 | if (!location.hash) location.replace('#/'); |
| 1070 | else render(); |
| 1071 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { |
| 1072 | if (state.me && state.me.theme === 'system') applyPrefs(state.me); |
| 1073 | }); |
| 1074 | } |
projects-timfalken-com verhalenboek