| 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 el(tag, attrs, children) { |
| 25 | const node = document.createElement(tag); |
| 26 | Object.entries(attrs || {}).forEach(([key, value]) => { |
| 27 | if (value == null || value === false) return; |
| 28 | if (key === 'class') node.className = value; |
| 29 | else node.setAttribute(key, value === true ? '' : value); |
| 30 | }); |
| 31 | (children || []).forEach((child) => node.append(child instanceof Node ? child : document.createTextNode(String(child)))); |
| 32 | return node; |
| 33 | } |
| 34 | |
| 35 | function toast(message) { |
| 36 | const node = document.querySelector('#toast'); |
| 37 | node.textContent = message; |
| 38 | node.dataset.show = '1'; |
| 39 | clearTimeout(toast.timer); |
| 40 | toast.timer = setTimeout(() => { node.dataset.show = '0'; }, 4200); |
| 41 | } |
| 42 | |
| 43 | async function api(method, path, body) { |
| 44 | const headers = { Accept: 'application/json' }; |
| 45 | if (body !== undefined) headers['Content-Type'] = 'application/json'; |
| 46 | if (method !== 'GET' && state.csrf) headers['X-CSRF-Token'] = state.csrf; |
| 47 | const response = await fetch('api.php' + path, { |
| 48 | method, |
| 49 | headers, |
| 50 | body: body !== undefined ? JSON.stringify(body) : undefined, |
| 51 | }); |
| 52 | let data = null; |
| 53 | try { data = await response.json(); } catch (error) { data = null; } |
| 54 | if (!response.ok) { |
| 55 | const failure = new Error((data && data.error) || 'Er ging iets mis.'); |
| 56 | failure.status = response.status; |
| 57 | throw failure; |
| 58 | } |
| 59 | return data; |
| 60 | } |
| 61 | |
| 62 | function applyPrefs(user) { |
| 63 | document.documentElement.dataset.theme = user.theme || 'system'; |
| 64 | document.documentElement.dataset.font = user.font || 'serif'; |
| 65 | const dark = user.theme === 'dark' || (user.theme !== 'light' && window.matchMedia('(prefers-color-scheme: dark)').matches); |
| 66 | const meta = document.querySelector('meta[name="theme-color"]'); |
| 67 | if (meta) meta.content = dark ? '#141210' : '#f4efe6'; |
| 68 | } |
| 69 | |
| 70 | function highlight(path) { |
| 71 | document.querySelectorAll('[data-nav]').forEach((link) => { |
| 72 | const nav = link.getAttribute('data-nav'); |
| 73 | let current = path === nav; |
| 74 | if (nav === '/') current = path === '/' || path.startsWith('/week/'); |
| 75 | if (nav === '/beheer') current = path.startsWith('/beheer'); |
| 76 | if (current) link.setAttribute('aria-current', 'page'); |
| 77 | else link.removeAttribute('aria-current'); |
| 78 | }); |
| 79 | } |
| 80 | |
| 81 | function localToday() { |
| 82 | const now = new Date(); |
| 83 | const month = String(now.getMonth() + 1).padStart(2, '0'); |
| 84 | const day = String(now.getDate()).padStart(2, '0'); |
| 85 | return now.getFullYear() + '-' + month + '-' + day; |
| 86 | } |
| 87 | |
| 88 | function overviewQuery(explicitWeek) { |
| 89 | const params = new URLSearchParams(); |
| 90 | if (explicitWeek) params.set('week', explicitWeek); |
| 91 | else params.set('today', localToday()); |
| 92 | return '/days?' + params.toString(); |
| 93 | } |
| 94 | |
| 95 | function closeMenu() { |
| 96 | const menu = document.querySelector('#read-menu'); |
| 97 | if (!menu || menu.hidden) return; |
| 98 | menu.hidden = true; |
| 99 | if (menuAnchor && menuAnchor.isConnected) menuAnchor.focus(); |
| 100 | menuAnchor = null; |
| 101 | } |
| 102 | |
| 103 | function openMenu(x, y, day, anchor) { |
| 104 | const menu = document.querySelector('#read-menu'); |
| 105 | menu.hidden = false; |
| 106 | menu.dataset.date = day.date; |
| 107 | menu.querySelector('[data-caption]').textContent = formatDate(day.date) + ' · ' + day.title; |
| 108 | const button = menu.querySelector('button'); |
| 109 | button.textContent = day.read ? 'Markeer als ongelezen' : 'Markeer als gelezen'; |
| 110 | button.dataset.makeRead = day.read ? '0' : '1'; |
| 111 | menu.style.left = '0px'; |
| 112 | menu.style.top = '0px'; |
| 113 | const rect = menu.getBoundingClientRect(); |
| 114 | menu.style.left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8)) + 'px'; |
| 115 | menu.style.top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8)) + 'px'; |
| 116 | menuAnchor = anchor; |
| 117 | ignoreCloseUntil = Date.now() + 450; |
| 118 | button.focus(); |
| 119 | } |
| 120 | |
| 121 | function bindReadMenu() { |
| 122 | const menu = document.querySelector('#read-menu'); |
| 123 | menu.querySelector('button').addEventListener('click', async () => { |
| 124 | const date = menu.dataset.date; |
| 125 | const makeRead = menu.querySelector('button').dataset.makeRead === '1'; |
| 126 | closeMenu(); |
| 127 | try { |
| 128 | await api(makeRead ? 'POST' : 'DELETE', '/days/' + date + '/read'); |
| 129 | await render(); |
| 130 | } catch (error) { |
| 131 | toast(error.message); |
| 132 | } |
| 133 | }); |
| 134 | document.addEventListener('click', (event) => { |
| 135 | if (menu.hidden || Date.now() < ignoreCloseUntil || menu.contains(event.target)) return; |
| 136 | closeMenu(); |
| 137 | }); |
| 138 | document.addEventListener('keydown', (event) => { |
| 139 | if (event.key === 'Escape') closeMenu(); |
| 140 | }); |
| 141 | window.addEventListener('scroll', () => closeMenu(), true); |
| 142 | } |
| 143 | |
| 144 | function bindDayLink(link, day) { |
| 145 | let timer = null; |
| 146 | let startX = 0; |
| 147 | let startY = 0; |
| 148 | let suppressClick = false; |
| 149 | const cancel = () => { |
| 150 | if (timer) clearTimeout(timer); |
| 151 | timer = null; |
| 152 | link.classList.remove('is-holding'); |
| 153 | }; |
| 154 | link.addEventListener('contextmenu', (event) => { |
| 155 | event.preventDefault(); |
| 156 | cancel(); |
| 157 | suppressClick = true; |
| 158 | openMenu(event.clientX, event.clientY, day, link); |
| 159 | }); |
| 160 | link.addEventListener('pointerdown', (event) => { |
| 161 | if (event.pointerType === 'mouse' || event.button !== 0) return; |
| 162 | startX = event.clientX; |
| 163 | startY = event.clientY; |
| 164 | suppressClick = false; |
| 165 | link.classList.add('is-holding'); |
| 166 | timer = setTimeout(() => { |
| 167 | timer = null; |
| 168 | suppressClick = true; |
| 169 | openMenu(startX, startY, day, link); |
| 170 | }, 550); |
| 171 | }); |
| 172 | link.addEventListener('pointermove', (event) => { |
| 173 | if (timer && Math.hypot(event.clientX - startX, event.clientY - startY) > 12) cancel(); |
| 174 | }); |
| 175 | link.addEventListener('pointerup', cancel); |
| 176 | link.addEventListener('pointercancel', cancel); |
| 177 | link.addEventListener('selectstart', (event) => event.preventDefault()); |
| 178 | link.addEventListener('dragstart', (event) => event.preventDefault()); |
| 179 | link.addEventListener('click', (event) => { |
| 180 | if (!suppressClick) return; |
| 181 | event.preventDefault(); |
| 182 | suppressClick = false; |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | function unreadLabel(count) { |
| 187 | if (count === 1) return '1 dag ongelezen'; |
| 188 | return count + ' dagen ongelezen'; |
| 189 | } |
| 190 | |
| 191 | function paintOverview(data) { |
| 192 | const days = data.days || []; |
| 193 | const visible = data.weekDays || []; |
| 194 | const week = data.week; |
| 195 | const unread = days.filter((day) => !day.read); |
| 196 | const wrap = el('div', { class: 'continue-wrap' }); |
| 197 | if (!days.length) { |
| 198 | wrap.append(el('p', { class: 'empty' }, [state.me.admin ? 'Er staan nog geen dagen in het boek.' : 'Er staan nog geen verhalen klaar.'])); |
| 199 | if (state.me.admin) wrap.append(el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag'])); |
| 200 | } else if (unread.length) { |
| 201 | wrap.append(el('a', { class: 'button primary continue', href: '#/dag/' + unread[0].date }, ['Verderlezen'])); |
| 202 | wrap.append(el('p', { class: 'continue-note' }, [unreadLabel(unread.length)])); |
| 203 | } else { |
| 204 | const done = el('button', { class: 'button continue', type: 'button', disabled: 'disabled' }, ['Alles gelezen']); |
| 205 | wrap.append(done); |
| 206 | } |
| 207 | const nav = el('nav', { class: 'week-nav', 'aria-label': 'Weken' }, [ |
| 208 | el('a', { class: 'button quiet', href: '#/week/' + week.previous }, ['← Vorige week']), |
| 209 | el('a', { class: 'button quiet', href: '#/week/' + week.next }, ['Volgende week →']), |
| 210 | ]); |
| 211 | const nodes = [el('h1', { class: 'week-label' }, [week.label]), nav, wrap]; |
| 212 | if (visible.length) { |
| 213 | const list = el('ol', { class: 'day-list' }); |
| 214 | visible.forEach((day) => { |
| 215 | const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date }, [ |
| 216 | el('span', { class: 'day-date' }, [formatDate(day.date)]), |
| 217 | el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']), |
| 218 | el('span', { class: 'day-title' }, [day.title]), |
| 219 | ]); |
| 220 | if (!day.complete) link.append(el('span', { class: 'badge' }, ['Onvolledig'])); |
| 221 | bindDayLink(link, day); |
| 222 | list.append(el('li', {}, [link])); |
| 223 | }); |
| 224 | nodes.push(list); |
| 225 | app.replaceChildren(...nodes); |
| 226 | const firstUnread = list.querySelector('.unread'); |
| 227 | if (firstUnread) firstUnread.scrollIntoView({ block: 'nearest' }); |
| 228 | } else { |
| 229 | if (days.length) nodes.push(el('p', { class: 'empty' }, ['Geen dagen in deze week.'])); |
| 230 | app.replaceChildren(...nodes); |
| 231 | } |
| 232 | document.title = week.label + ' · Verhalenboek'; |
| 233 | } |
| 234 | |
| 235 | function paintDay(day) { |
| 236 | const head = el('header', { class: 'day-head' }, [ |
| 237 | el('p', { class: 'day-kicker' }, [formatDate(day.date)]), |
| 238 | el('h1', {}, [day.title]), |
| 239 | ]); |
| 240 | const top = el('div', { class: 'pager' }); |
| 241 | if (day.previous) top.append(el('a', { class: 'button quiet', href: '#/dag/' + day.previous }, ['← Vorige dag'])); |
| 242 | const stories = day.stories.map((story) => el('article', { class: 'story' }, [ |
| 243 | el('h2', {}, [el('span', {}, [ROMAN[(story.position || 1) - 1] || String(story.position)]), story.title]), |
| 244 | ...story.paragraphs.map((paragraph) => el('p', {}, [paragraph])), |
| 245 | ])); |
| 246 | if (!day.complete) stories.unshift(el('p', { class: 'form-error' }, ['Deze dag is onvolledig.'])); |
| 247 | const bottom = el('div', { class: 'pager bottom' }); |
| 248 | if (day.next) bottom.append(el('a', { class: 'button primary continue', href: '#/dag/' + day.next }, ['Volgende dag →'])); |
| 249 | else bottom.append(el('a', { class: 'button quiet', href: '#/' }, ['Terug naar het overzicht'])); |
| 250 | app.replaceChildren(head, top, ...stories, bottom); |
| 251 | } |
| 252 | |
| 253 | function choice(name, value, label, current) { |
| 254 | const input = el('input', { type: 'radio', name, value }); |
| 255 | input.checked = current === value; |
| 256 | return el('label', {}, [input, label]); |
| 257 | } |
| 258 | |
| 259 | function paintSettings() { |
| 260 | const theme = el('fieldset', {}, [ |
| 261 | el('legend', {}, ['Weergave']), |
| 262 | el('div', { class: 'choice' }, [ |
| 263 | choice('theme', 'system', 'Systeem', state.me.theme), |
| 264 | choice('theme', 'light', 'Licht', state.me.theme), |
| 265 | choice('theme', 'dark', 'Donker', state.me.theme), |
| 266 | ]), |
| 267 | ]); |
| 268 | const font = el('fieldset', {}, [ |
| 269 | el('legend', {}, ['Lettertype']), |
| 270 | el('div', { class: 'choice' }, [ |
| 271 | choice('font', 'serif', 'Serif', state.me.font), |
| 272 | choice('font', 'sans', 'Schreefloos', state.me.font), |
| 273 | choice('font', 'rounded', 'Rond', state.me.font), |
| 274 | ]), |
| 275 | ]); |
| 276 | const preview = el('p', { class: 'lede' }, ['Zo lees je een verhaal. De regen tikte zacht op het dak, en de bladzijde bleef openliggen.']); |
| 277 | const error = el('p', { class: 'form-error' }); |
| 278 | async function persist() { |
| 279 | const nextTheme = theme.querySelector('input:checked').value; |
| 280 | const nextFont = font.querySelector('input:checked').value; |
| 281 | const previous = { theme: state.me.theme, font: state.me.font }; |
| 282 | state.me = { ...state.me, theme: nextTheme, font: nextFont }; |
| 283 | applyPrefs(state.me); |
| 284 | try { |
| 285 | const result = await api('PUT', '/me/settings', { theme: nextTheme, font: nextFont }); |
| 286 | state.me = result.user; |
| 287 | applyPrefs(state.me); |
| 288 | error.textContent = ''; |
| 289 | } catch (failure) { |
| 290 | state.me = { ...state.me, ...previous }; |
| 291 | applyPrefs(state.me); |
| 292 | theme.querySelector('input[value="' + previous.theme + '"]').checked = true; |
| 293 | font.querySelector('input[value="' + previous.font + '"]').checked = true; |
| 294 | error.textContent = failure.message; |
| 295 | } |
| 296 | } |
| 297 | theme.addEventListener('change', persist); |
| 298 | font.addEventListener('change', persist); |
| 299 | const actions = el('div', { class: 'row-actions' }, [ |
| 300 | el('button', { class: 'quiet', type: 'button' }, ['Exporteer mijn gegevens (JSON)']), |
| 301 | el('button', { class: 'danger', type: 'button' }, ['Uitloggen']), |
| 302 | ]); |
| 303 | actions.children[0].addEventListener('click', () => { window.location.href = 'api.php/me/export'; }); |
| 304 | actions.children[1].addEventListener('click', async () => { |
| 305 | try { |
| 306 | await api('POST', '/session/logout'); |
| 307 | window.location.href = 'index.php'; |
| 308 | } catch (failure) { toast(failure.message); } |
| 309 | }); |
| 310 | const section = el('section', { class: 'settings' }, [ |
| 311 | el('h1', {}, ['Instellingen']), |
| 312 | el('p', { class: 'continue-note' }, ['Ingelogd als ' + state.me.name + (state.me.admin ? ' · beheerder' : '')]), |
| 313 | theme, font, preview, error, actions, |
| 314 | ]); |
| 315 | if (state.local) { |
| 316 | const other = state.me.name === 'test_user_2' ? 'test_user_1' : 'test_user_2'; |
| 317 | const swap = el('button', { class: 'quiet', type: 'button' }, ['Wissel naar ' + other]); |
| 318 | swap.addEventListener('click', async () => { |
| 319 | try { |
| 320 | await api('POST', '/session/switch', { user: other }); |
| 321 | window.location.reload(); |
| 322 | } catch (failure) { toast(failure.message); } |
| 323 | }); |
| 324 | section.append(swap); |
| 325 | } |
| 326 | app.replaceChildren(section); |
| 327 | } |
| 328 | |
| 329 | function paragraphField(value) { |
| 330 | const area = el('textarea', { rows: '4' }); |
| 331 | area.value = value || ''; |
| 332 | const remove = el('button', { class: 'quiet', type: 'button' }, ['Alinea verwijderen']); |
| 333 | const block = el('div', { class: 'paragraph-actions' }, [area, remove]); |
| 334 | remove.addEventListener('click', () => { |
| 335 | const boxes = block.parentElement.querySelectorAll('textarea'); |
| 336 | if (boxes.length <= 1) { area.value = ''; return; } |
| 337 | block.remove(); |
| 338 | }); |
| 339 | return block; |
| 340 | } |
| 341 | |
| 342 | function storyField(position, story, onDelete) { |
| 343 | const title = el('input', { type: 'text', maxlength: '200', 'data-title': '1', required: 'required' }); |
| 344 | title.value = story.title || ''; |
| 345 | const paragraphs = el('div', {}); |
| 346 | (story.paragraphs && story.paragraphs.length ? story.paragraphs : ['']).forEach((paragraph) => paragraphs.append(paragraphField(paragraph))); |
| 347 | const add = el('button', { class: 'quiet', type: 'button' }, ['Alinea toevoegen']); |
| 348 | add.addEventListener('click', () => paragraphs.append(paragraphField(''))); |
| 349 | const fieldset = el('fieldset', { 'data-position': String(position) }, [ |
| 350 | el('legend', {}, ['Verhaal ' + ROMAN[position - 1]]), |
| 351 | el('label', {}, ['Titel', title]), |
| 352 | paragraphs, |
| 353 | add, |
| 354 | ]); |
| 355 | if (onDelete) { |
| 356 | const remove = el('button', { class: 'danger', type: 'button' }, ['Dit verhaal verwijderen']); |
| 357 | remove.addEventListener('click', onDelete); |
| 358 | fieldset.append(remove); |
| 359 | } |
| 360 | return fieldset; |
| 361 | } |
| 362 | |
| 363 | function readStories(form) { |
| 364 | return [...form.querySelectorAll('fieldset')].map((fieldset) => ({ |
| 365 | title: fieldset.querySelector('[data-title]').value, |
| 366 | paragraphs: [...fieldset.querySelectorAll('textarea')].map((area) => area.value), |
| 367 | })); |
| 368 | } |
| 369 | |
| 370 | async function paintEditor(date) { |
| 371 | const creating = !date; |
| 372 | let day = { title: '', stories: [{}, {}, {}] }; |
| 373 | if (!creating) day = await api('GET', '/days/' + date); |
| 374 | const byPosition = {}; |
| 375 | (day.stories || []).forEach((story) => { byPosition[story.position] = story; }); |
| 376 | const title = el('input', { type: 'text', maxlength: '200', required: 'required' }); |
| 377 | title.value = day.title || ''; |
| 378 | const dateInput = el('input', { type: 'date', required: 'required' }); |
| 379 | if (creating) dateInput.value = ''; |
| 380 | else { dateInput.value = date; dateInput.readOnly = true; } |
| 381 | const error = el('p', { class: 'form-error' }); |
| 382 | const form = el('form', { class: 'editor' }, [ |
| 383 | el('h1', {}, [creating ? 'Nieuwe dag' : 'Dag bewerken']), |
| 384 | el('label', {}, ['Datum', dateInput]), |
| 385 | el('label', {}, ['Titel van de dag', title]), |
| 386 | ]); |
| 387 | for (let position = 1; position <= 3; position += 1) { |
| 388 | const existing = byPosition[position]; |
| 389 | form.append(storyField(position, existing || { title: '', paragraphs: [''] }, !creating && existing ? async () => { |
| 390 | if (!window.confirm('Dit verhaal verwijderen? De dag wordt onvolledig.')) return; |
| 391 | try { |
| 392 | await api('DELETE', '/days/' + date + '/stories/' + position); |
| 393 | await render(); |
| 394 | } catch (failure) { error.textContent = failure.message; } |
| 395 | } : null)); |
| 396 | } |
| 397 | const save = el('button', { class: 'primary', type: 'submit' }, ['Dag opslaan']); |
| 398 | form.append(error, save); |
| 399 | if (!creating) { |
| 400 | const remove = el('button', { class: 'danger', type: 'button' }, ['Hele dag verwijderen']); |
| 401 | remove.addEventListener('click', async () => { |
| 402 | if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return; |
| 403 | try { |
| 404 | await api('DELETE', '/days/' + date); |
| 405 | location.hash = '#/beheer'; |
| 406 | } catch (failure) { error.textContent = failure.message; } |
| 407 | }); |
| 408 | form.append(remove); |
| 409 | } |
| 410 | form.addEventListener('submit', async (event) => { |
| 411 | event.preventDefault(); |
| 412 | error.textContent = ''; |
| 413 | save.disabled = true; |
| 414 | const payload = { title: title.value, stories: readStories(form) }; |
| 415 | try { |
| 416 | if (creating) { |
| 417 | const created = await api('POST', '/days', { date: dateInput.value, ...payload }); |
| 418 | location.hash = '#/beheer/' + created.date; |
| 419 | } else { |
| 420 | await api('PUT', '/days/' + date, payload); |
| 421 | toast('Opgeslagen.'); |
| 422 | await render(); |
| 423 | } |
| 424 | } catch (failure) { |
| 425 | error.textContent = failure.message; |
| 426 | save.disabled = false; |
| 427 | } |
| 428 | }); |
| 429 | app.replaceChildren(form); |
| 430 | } |
| 431 | |
| 432 | async function paintBeheer() { |
| 433 | const [days, people] = await Promise.all([api('GET', '/days'), api('GET', '/users')]); |
| 434 | const users = el('div', { class: 'user-list' }); |
| 435 | people.users.forEach((person) => { |
| 436 | const self = person.id === state.me.id; |
| 437 | const action = el('button', { |
| 438 | type: 'button', |
| 439 | class: self ? 'quiet' : (person.admin ? 'danger' : 'primary'), |
| 440 | }, [self ? 'Jij' : (person.admin ? 'Maak lezer' : 'Maak beheerder')]); |
| 441 | action.disabled = self; |
| 442 | if (!self) { |
| 443 | action.addEventListener('click', async () => { |
| 444 | if (person.admin && !window.confirm(person.name + ' is daarna alleen nog lezer. Doorgaan?')) return; |
| 445 | try { |
| 446 | await api('PUT', '/users/' + encodeURIComponent(person.id), { admin: !person.admin }); |
| 447 | toast(person.admin ? person.name + ' is nu lezer.' : person.name + ' is nu beheerder.'); |
| 448 | await render(); |
| 449 | } catch (failure) { toast(failure.message); } |
| 450 | }); |
| 451 | } |
| 452 | users.append(el('div', { class: 'user-row' }, [ |
| 453 | el('div', {}, [ |
| 454 | el('strong', {}, [person.name]), |
| 455 | el('small', {}, [person.id]), |
| 456 | el('span', { class: 'user-role' }, [person.admin ? 'Beheerder' : 'Lezer']), |
| 457 | ]), |
| 458 | action, |
| 459 | ])); |
| 460 | }); |
| 461 | const list = el('div', {}); |
| 462 | days.days.forEach((day) => { |
| 463 | list.append(el('div', { class: 'admin-day' }, [ |
| 464 | el('a', { href: '#/beheer/' + day.date }, [ |
| 465 | el('strong', {}, [day.title]), |
| 466 | document.createElement('br'), |
| 467 | el('small', {}, [formatDate(day.date) + (day.complete ? '' : ' · onvolledig')]), |
| 468 | ]), |
| 469 | el('a', { class: 'button quiet', href: '#/dag/' + day.date }, ['Lezen']), |
| 470 | ])); |
| 471 | }); |
| 472 | if (!days.days.length) list.append(el('p', { class: 'empty' }, ['Nog geen dagen.'])); |
| 473 | app.replaceChildren(el('section', { class: 'panel' }, [ |
| 474 | el('h1', {}, ['Beheer']), |
| 475 | el('h2', {}, ['Gebruikers']), |
| 476 | el('p', { class: 'lede' }, ['Maak iemand anders beheerder, of haal die rol weer weg. Je eigen rol blijft staan.']), |
| 477 | users, |
| 478 | el('h2', {}, ['Dagen']), |
| 479 | el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag']), |
| 480 | list, |
| 481 | ])); |
| 482 | } |
| 483 | |
| 484 | function tokenPanel(title, token) { |
| 485 | const field = el('textarea', { readonly: 'readonly', rows: '3' }); |
| 486 | field.value = token; |
| 487 | const copy = el('button', { class: 'quiet', type: 'button' }, ['Kopieer']); |
| 488 | copy.addEventListener('click', async () => { |
| 489 | field.select(); |
| 490 | try { await navigator.clipboard.writeText(field.value); toast('Gekopieerd.'); } |
| 491 | catch (failure) { toast('Selecteer de sleutel en kopieer hem handmatig.'); } |
| 492 | }); |
| 493 | return el('div', { class: 'token-once' }, [el('strong', {}, [title]), field, copy]); |
| 494 | } |
| 495 | |
| 496 | function paintKeys(keys) { |
| 497 | const name = el('input', { type: 'text', maxlength: '80', required: 'required' }); |
| 498 | const error = el('p', { class: 'form-error' }); |
| 499 | const form = el('form', {}, [ |
| 500 | el('label', {}, ['Naam van de sleutel', name]), |
| 501 | el('button', { class: 'primary', type: 'submit' }, ['Sleutel aanmaken']), |
| 502 | error, |
| 503 | ]); |
| 504 | form.addEventListener('submit', async (event) => { |
| 505 | event.preventDefault(); |
| 506 | error.textContent = ''; |
| 507 | try { |
| 508 | const result = await api('POST', '/keys', { name: name.value }); |
| 509 | state.freshKey = result.key; |
| 510 | state.revealedKey = null; |
| 511 | await render(); |
| 512 | } catch (failure) { error.textContent = failure.message; } |
| 513 | }); |
| 514 | const section = el('section', { class: 'keys' }, [el('h1', {}, ['API-sleutels']), form]); |
| 515 | if (state.revealedKey && state.revealedKey.token) { |
| 516 | section.append(tokenPanel('Sleutel van ' + state.revealedKey.name, state.revealedKey.token)); |
| 517 | } else if (state.freshKey && state.freshKey.token) { |
| 518 | section.append(tokenPanel('Nieuwe sleutel. Tik er later opnieuw op om hem te zien.', state.freshKey.token)); |
| 519 | } |
| 520 | const list = el('div', {}); |
| 521 | keys.forEach((key) => { |
| 522 | const open = el('button', { type: 'button', class: 'key-open' }, [ |
| 523 | el('span', { class: key.revoked ? 'revoked' : '' }, [key.name]), |
| 524 | el('span', {}, [key.prefix + '…']), |
| 525 | el('span', {}, [key.revoked ? 'Ingetrokken' : 'Actief']), |
| 526 | ]); |
| 527 | open.addEventListener('click', async () => { |
| 528 | try { |
| 529 | const result = await api('GET', '/keys/' + key.id); |
| 530 | state.freshKey = null; |
| 531 | state.revealedKey = result.key; |
| 532 | await render(); |
| 533 | } catch (failure) { toast(failure.message); } |
| 534 | }); |
| 535 | const revoke = el('button', { class: 'danger', type: 'button' }, ['Intrekken']); |
| 536 | revoke.disabled = key.revoked != null; |
| 537 | revoke.addEventListener('click', async () => { |
| 538 | if (!window.confirm('Deze API-sleutel intrekken? Bestaande scripts kunnen dan niet meer schrijven.')) return; |
| 539 | try { await api('DELETE', '/keys/' + key.id); await render(); } |
| 540 | catch (failure) { toast(failure.message); } |
| 541 | }); |
| 542 | list.append(el('div', { class: 'key-row' }, [open, revoke])); |
| 543 | }); |
| 544 | if (!keys.length) list.append(el('p', { class: 'empty' }, ['Nog geen sleutels.'])); |
| 545 | section.append(el('h2', {}, ['Bestaande sleutels']), el('p', { class: 'lede' }, ['Tik op een sleutel om de volledige sleutel opnieuw te zien.']), list); |
| 546 | app.replaceChildren(section); |
| 547 | } |
| 548 | |
| 549 | async function render() { |
| 550 | const token = ++renderToken; |
| 551 | const path = pathNow(); |
| 552 | if (path !== '/sleutels') { |
| 553 | state.freshKey = null; |
| 554 | state.revealedKey = null; |
| 555 | } |
| 556 | closeMenu(); |
| 557 | highlight(path); |
| 558 | document.title = 'Verhalenboek'; |
| 559 | try { |
| 560 | const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/); |
| 561 | if (path === '/' || path === '' || weekMatch) { |
| 562 | const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null)); |
| 563 | if (token !== renderToken) return; |
| 564 | paintOverview(data); |
| 565 | } else if (path === '/instellingen') { |
| 566 | paintSettings(); |
| 567 | } else if (path === '/beheer') { |
| 568 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 569 | await paintBeheer(); |
| 570 | } else if (path === '/beheer/nieuw') { |
| 571 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 572 | await paintEditor(null); |
| 573 | } else if (/^\/beheer\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 574 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 575 | await paintEditor(path.slice('/beheer/'.length)); |
| 576 | } else if (path === '/sleutels') { |
| 577 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 578 | const data = await api('GET', '/keys'); |
| 579 | if (token !== renderToken) return; |
| 580 | paintKeys(data.keys); |
| 581 | } else if (/^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 582 | const date = path.slice(5); |
| 583 | const day = await api('GET', '/days/' + date); |
| 584 | if (token !== renderToken) return; |
| 585 | paintDay(day); |
| 586 | document.title = day.title + ' · Verhalenboek'; |
| 587 | if (!day.read) { |
| 588 | try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ } |
| 589 | } |
| 590 | } else { |
| 591 | app.replaceChildren(el('p', { class: 'empty' }, ['Deze pagina bestaat niet.']), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 592 | } |
| 593 | } catch (error) { |
| 594 | if (token !== renderToken) return; |
| 595 | if (error.status === 401) { window.location.href = 'index.php'; return; } |
| 596 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | async function boot() { |
| 601 | bindReadMenu(); |
| 602 | try { |
| 603 | const me = await api('GET', '/me'); |
| 604 | state.me = me.user; |
| 605 | state.csrf = me.csrf; |
| 606 | state.local = !!me.local; |
| 607 | applyPrefs(me.user); |
| 608 | } catch (error) { |
| 609 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message])); |
| 610 | return; |
| 611 | } |
| 612 | window.addEventListener('hashchange', () => { render(); }); |
| 613 | if (!location.hash) location.replace('#/'); |
| 614 | else render(); |
| 615 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { |
| 616 | if (state.me && state.me.theme === 'system') applyPrefs(state.me); |
| 617 | }); |
| 618 | } |
projects-timfalken-com verhalenboek