| 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 links = []; |
| 208 | if (week.hasPrevious) links.push(el('a', { class: 'button quiet week-prev', href: '#/week/' + week.previous }, ['← Vorige week'])); |
| 209 | if (week.hasNext) links.push(el('a', { class: 'button quiet week-next', href: '#/week/' + week.next }, ['Volgende week →'])); |
| 210 | const nodes = [el('h1', { class: 'week-label' }, [week.label])]; |
| 211 | if (links.length) nodes.push(el('nav', { class: 'week-nav', 'aria-label': 'Weken' }, links)); |
| 212 | nodes.push(wrap); |
| 213 | if (visible.length) { |
| 214 | const list = el('ol', { class: 'day-list' }); |
| 215 | visible.forEach((day) => { |
| 216 | const link = el('a', { class: 'day-link ' + (day.read ? 'read' : 'unread'), href: '#/dag/' + day.date }, [ |
| 217 | el('span', { class: 'day-date' }, [formatDate(day.date)]), |
| 218 | el('span', { class: 'day-state' }, [day.read ? 'Gelezen' : 'Ongelezen']), |
| 219 | el('span', { class: 'day-title' }, [day.title]), |
| 220 | ]); |
| 221 | if (!day.complete) link.append(el('span', { class: 'badge' }, ['Onvolledig'])); |
| 222 | bindDayLink(link, day); |
| 223 | list.append(el('li', {}, [link])); |
| 224 | }); |
| 225 | nodes.push(list); |
| 226 | app.replaceChildren(...nodes); |
| 227 | const firstUnread = list.querySelector('.unread'); |
| 228 | if (firstUnread) firstUnread.scrollIntoView({ block: 'nearest' }); |
| 229 | } else { |
| 230 | if (days.length) nodes.push(el('p', { class: 'empty' }, ['Geen dagen in deze week.'])); |
| 231 | app.replaceChildren(...nodes); |
| 232 | } |
| 233 | document.title = week.label + ' · Verhalenboek'; |
| 234 | } |
| 235 | |
| 236 | function paintDay(day) { |
| 237 | const head = el('header', { class: 'day-head' }, [ |
| 238 | el('p', { class: 'day-kicker' }, [formatDate(day.date)]), |
| 239 | el('h1', {}, [day.title]), |
| 240 | ]); |
| 241 | const top = el('div', { class: 'pager' }); |
| 242 | if (day.previous) top.append(el('a', { class: 'button quiet', href: '#/dag/' + day.previous }, ['← Vorige dag'])); |
| 243 | const stories = day.stories.map((story) => el('article', { class: 'story' }, [ |
| 244 | el('h2', {}, [el('span', {}, [ROMAN[(story.position || 1) - 1] || String(story.position)]), story.title]), |
| 245 | ...story.paragraphs.map((paragraph) => el('p', {}, [paragraph])), |
| 246 | ])); |
| 247 | if (!day.complete) stories.unshift(el('p', { class: 'form-error' }, ['Deze dag is onvolledig.'])); |
| 248 | const bottom = el('div', { class: 'pager bottom' }); |
| 249 | if (day.next) bottom.append(el('a', { class: 'button primary continue', href: '#/dag/' + day.next }, ['Volgende dag →'])); |
| 250 | else bottom.append(el('a', { class: 'button quiet', href: '#/' }, ['Terug naar het overzicht'])); |
| 251 | app.replaceChildren(head, top, ...stories, bottom); |
| 252 | } |
| 253 | |
| 254 | function choice(name, value, label, current) { |
| 255 | const input = el('input', { type: 'radio', name, value }); |
| 256 | input.checked = current === value; |
| 257 | return el('label', {}, [input, label]); |
| 258 | } |
| 259 | |
| 260 | function paintSettings() { |
| 261 | const theme = el('fieldset', {}, [ |
| 262 | el('legend', {}, ['Weergave']), |
| 263 | el('div', { class: 'choice' }, [ |
| 264 | choice('theme', 'system', 'Systeem', state.me.theme), |
| 265 | choice('theme', 'light', 'Licht', state.me.theme), |
| 266 | choice('theme', 'dark', 'Donker', state.me.theme), |
| 267 | ]), |
| 268 | ]); |
| 269 | const font = el('fieldset', {}, [ |
| 270 | el('legend', {}, ['Lettertype']), |
| 271 | el('div', { class: 'choice' }, [ |
| 272 | choice('font', 'serif', 'Serif', state.me.font), |
| 273 | choice('font', 'sans', 'Schreefloos', state.me.font), |
| 274 | choice('font', 'rounded', 'Rond', state.me.font), |
| 275 | ]), |
| 276 | ]); |
| 277 | const preview = el('p', { class: 'lede' }, ['Zo lees je een verhaal. De regen tikte zacht op het dak, en de bladzijde bleef openliggen.']); |
| 278 | const error = el('p', { class: 'form-error' }); |
| 279 | async function persist() { |
| 280 | const nextTheme = theme.querySelector('input:checked').value; |
| 281 | const nextFont = font.querySelector('input:checked').value; |
| 282 | const previous = { theme: state.me.theme, font: state.me.font }; |
| 283 | state.me = { ...state.me, theme: nextTheme, font: nextFont }; |
| 284 | applyPrefs(state.me); |
| 285 | try { |
| 286 | const result = await api('PUT', '/me/settings', { theme: nextTheme, font: nextFont }); |
| 287 | state.me = result.user; |
| 288 | applyPrefs(state.me); |
| 289 | error.textContent = ''; |
| 290 | } catch (failure) { |
| 291 | state.me = { ...state.me, ...previous }; |
| 292 | applyPrefs(state.me); |
| 293 | theme.querySelector('input[value="' + previous.theme + '"]').checked = true; |
| 294 | font.querySelector('input[value="' + previous.font + '"]').checked = true; |
| 295 | error.textContent = failure.message; |
| 296 | } |
| 297 | } |
| 298 | theme.addEventListener('change', persist); |
| 299 | font.addEventListener('change', persist); |
| 300 | const actions = el('div', { class: 'row-actions' }, [ |
| 301 | el('button', { class: 'quiet', type: 'button' }, ['Exporteer mijn gegevens (JSON)']), |
| 302 | el('button', { class: 'danger', type: 'button' }, ['Uitloggen']), |
| 303 | ]); |
| 304 | actions.children[0].addEventListener('click', () => { window.location.href = 'api.php/me/export'; }); |
| 305 | actions.children[1].addEventListener('click', async () => { |
| 306 | try { |
| 307 | await api('POST', '/session/logout'); |
| 308 | window.location.href = 'index.php'; |
| 309 | } catch (failure) { toast(failure.message); } |
| 310 | }); |
| 311 | const section = el('section', { class: 'settings' }, [ |
| 312 | el('h1', {}, ['Instellingen']), |
| 313 | el('p', { class: 'continue-note' }, ['Ingelogd als ' + state.me.name + (state.me.admin ? ' · beheerder' : '')]), |
| 314 | theme, font, preview, error, actions, |
| 315 | ]); |
| 316 | if (state.local) { |
| 317 | const other = state.me.name === 'test_user_2' ? 'test_user_1' : 'test_user_2'; |
| 318 | const swap = el('button', { class: 'quiet', type: 'button' }, ['Wissel naar ' + other]); |
| 319 | swap.addEventListener('click', async () => { |
| 320 | try { |
| 321 | await api('POST', '/session/switch', { user: other }); |
| 322 | window.location.reload(); |
| 323 | } catch (failure) { toast(failure.message); } |
| 324 | }); |
| 325 | section.append(swap); |
| 326 | } |
| 327 | app.replaceChildren(section); |
| 328 | } |
| 329 | |
| 330 | function paragraphField(value) { |
| 331 | const area = el('textarea', { rows: '4' }); |
| 332 | area.value = value || ''; |
| 333 | const remove = el('button', { class: 'quiet', type: 'button' }, ['Alinea verwijderen']); |
| 334 | const block = el('div', { class: 'paragraph-actions' }, [area, remove]); |
| 335 | remove.addEventListener('click', () => { |
| 336 | const boxes = block.parentElement.querySelectorAll('textarea'); |
| 337 | if (boxes.length <= 1) { area.value = ''; return; } |
| 338 | block.remove(); |
| 339 | }); |
| 340 | return block; |
| 341 | } |
| 342 | |
| 343 | function storyField(position, story, onDelete) { |
| 344 | const title = el('input', { type: 'text', maxlength: '200', 'data-title': '1', required: 'required' }); |
| 345 | title.value = story.title || ''; |
| 346 | const paragraphs = el('div', {}); |
| 347 | (story.paragraphs && story.paragraphs.length ? story.paragraphs : ['']).forEach((paragraph) => paragraphs.append(paragraphField(paragraph))); |
| 348 | const add = el('button', { class: 'quiet', type: 'button' }, ['Alinea toevoegen']); |
| 349 | add.addEventListener('click', () => paragraphs.append(paragraphField(''))); |
| 350 | const fieldset = el('fieldset', { 'data-position': String(position) }, [ |
| 351 | el('legend', {}, ['Verhaal ' + ROMAN[position - 1]]), |
| 352 | el('label', {}, ['Titel', title]), |
| 353 | paragraphs, |
| 354 | add, |
| 355 | ]); |
| 356 | if (onDelete) { |
| 357 | const remove = el('button', { class: 'danger', type: 'button' }, ['Dit verhaal verwijderen']); |
| 358 | remove.addEventListener('click', onDelete); |
| 359 | fieldset.append(remove); |
| 360 | } |
| 361 | return fieldset; |
| 362 | } |
| 363 | |
| 364 | function readStories(form) { |
| 365 | return [...form.querySelectorAll('fieldset')].map((fieldset) => ({ |
| 366 | title: fieldset.querySelector('[data-title]').value, |
| 367 | paragraphs: [...fieldset.querySelectorAll('textarea')].map((area) => area.value), |
| 368 | })); |
| 369 | } |
| 370 | |
| 371 | async function paintEditor(date) { |
| 372 | const creating = !date; |
| 373 | let day = { title: '', stories: [{}, {}, {}] }; |
| 374 | if (!creating) day = await api('GET', '/days/' + date); |
| 375 | const byPosition = {}; |
| 376 | (day.stories || []).forEach((story) => { byPosition[story.position] = story; }); |
| 377 | const title = el('input', { type: 'text', maxlength: '200', required: 'required' }); |
| 378 | title.value = day.title || ''; |
| 379 | const dateInput = el('input', { type: 'date', required: 'required' }); |
| 380 | if (creating) dateInput.value = ''; |
| 381 | else { dateInput.value = date; dateInput.readOnly = true; } |
| 382 | const error = el('p', { class: 'form-error' }); |
| 383 | const form = el('form', { class: 'editor' }, [ |
| 384 | el('h1', {}, [creating ? 'Nieuwe dag' : 'Dag bewerken']), |
| 385 | el('label', {}, ['Datum', dateInput]), |
| 386 | el('label', {}, ['Titel van de dag', title]), |
| 387 | ]); |
| 388 | for (let position = 1; position <= 3; position += 1) { |
| 389 | const existing = byPosition[position]; |
| 390 | form.append(storyField(position, existing || { title: '', paragraphs: [''] }, !creating && existing ? async () => { |
| 391 | if (!window.confirm('Dit verhaal verwijderen? De dag wordt onvolledig.')) return; |
| 392 | try { |
| 393 | await api('DELETE', '/days/' + date + '/stories/' + position); |
| 394 | await render(); |
| 395 | } catch (failure) { error.textContent = failure.message; } |
| 396 | } : null)); |
| 397 | } |
| 398 | const save = el('button', { class: 'primary', type: 'submit' }, ['Dag opslaan']); |
| 399 | form.append(error, save); |
| 400 | if (!creating) { |
| 401 | const remove = el('button', { class: 'danger', type: 'button' }, ['Hele dag verwijderen']); |
| 402 | remove.addEventListener('click', async () => { |
| 403 | if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return; |
| 404 | try { |
| 405 | await api('DELETE', '/days/' + date); |
| 406 | location.hash = '#/beheer'; |
| 407 | } catch (failure) { error.textContent = failure.message; } |
| 408 | }); |
| 409 | form.append(remove); |
| 410 | } |
| 411 | form.addEventListener('submit', async (event) => { |
| 412 | event.preventDefault(); |
| 413 | error.textContent = ''; |
| 414 | save.disabled = true; |
| 415 | const payload = { title: title.value, stories: readStories(form) }; |
| 416 | try { |
| 417 | if (creating) { |
| 418 | const created = await api('POST', '/days', { date: dateInput.value, ...payload }); |
| 419 | location.hash = '#/beheer/' + created.date; |
| 420 | } else { |
| 421 | await api('PUT', '/days/' + date, payload); |
| 422 | toast('Opgeslagen.'); |
| 423 | await render(); |
| 424 | } |
| 425 | } catch (failure) { |
| 426 | error.textContent = failure.message; |
| 427 | save.disabled = false; |
| 428 | } |
| 429 | }); |
| 430 | app.replaceChildren(form); |
| 431 | } |
| 432 | |
| 433 | async function paintBeheer() { |
| 434 | const [days, people] = await Promise.all([api('GET', '/days'), api('GET', '/users')]); |
| 435 | const users = el('div', { class: 'user-list' }); |
| 436 | people.users.forEach((person) => { |
| 437 | const self = person.id === state.me.id; |
| 438 | const action = el('button', { |
| 439 | type: 'button', |
| 440 | class: self ? 'quiet' : (person.admin ? 'danger' : 'primary'), |
| 441 | }, [self ? 'Jij' : (person.admin ? 'Maak lezer' : 'Maak beheerder')]); |
| 442 | action.disabled = self; |
| 443 | if (!self) { |
| 444 | action.addEventListener('click', async () => { |
| 445 | if (person.admin && !window.confirm(person.name + ' is daarna alleen nog lezer. Doorgaan?')) return; |
| 446 | try { |
| 447 | await api('PUT', '/users/' + encodeURIComponent(person.id), { admin: !person.admin }); |
| 448 | toast(person.admin ? person.name + ' is nu lezer.' : person.name + ' is nu beheerder.'); |
| 449 | await render(); |
| 450 | } catch (failure) { toast(failure.message); } |
| 451 | }); |
| 452 | } |
| 453 | users.append(el('div', { class: 'user-row' }, [ |
| 454 | el('div', {}, [ |
| 455 | el('strong', {}, [person.name]), |
| 456 | el('small', {}, [person.id]), |
| 457 | el('span', { class: 'user-role' }, [person.admin ? 'Beheerder' : 'Lezer']), |
| 458 | ]), |
| 459 | action, |
| 460 | ])); |
| 461 | }); |
| 462 | const list = el('div', {}); |
| 463 | days.days.forEach((day) => { |
| 464 | list.append(el('div', { class: 'admin-day' }, [ |
| 465 | el('a', { href: '#/beheer/' + day.date }, [ |
| 466 | el('strong', {}, [day.title]), |
| 467 | document.createElement('br'), |
| 468 | el('small', {}, [formatDate(day.date) + (day.complete ? '' : ' · onvolledig')]), |
| 469 | ]), |
| 470 | el('a', { class: 'button quiet', href: '#/dag/' + day.date }, ['Lezen']), |
| 471 | ])); |
| 472 | }); |
| 473 | if (!days.days.length) list.append(el('p', { class: 'empty' }, ['Nog geen dagen.'])); |
| 474 | app.replaceChildren(el('section', { class: 'panel' }, [ |
| 475 | el('h1', {}, ['Beheer']), |
| 476 | el('h2', {}, ['Gebruikers']), |
| 477 | el('p', { class: 'lede' }, ['Maak iemand anders beheerder, of haal die rol weer weg. Je eigen rol blijft staan.']), |
| 478 | users, |
| 479 | el('h2', {}, ['Dagen']), |
| 480 | el('a', { class: 'button primary', href: '#/beheer/nieuw' }, ['Nieuwe dag']), |
| 481 | list, |
| 482 | ])); |
| 483 | } |
| 484 | |
| 485 | function tokenPanel(title, token) { |
| 486 | const field = el('textarea', { readonly: 'readonly', rows: '3' }); |
| 487 | field.value = token; |
| 488 | const copy = el('button', { class: 'quiet', type: 'button' }, ['Kopieer']); |
| 489 | copy.addEventListener('click', async () => { |
| 490 | field.select(); |
| 491 | try { await navigator.clipboard.writeText(field.value); toast('Gekopieerd.'); } |
| 492 | catch (failure) { toast('Selecteer de sleutel en kopieer hem handmatig.'); } |
| 493 | }); |
| 494 | return el('div', { class: 'token-once' }, [el('strong', {}, [title]), field, copy]); |
| 495 | } |
| 496 | |
| 497 | function paintKeys(keys) { |
| 498 | const name = el('input', { type: 'text', maxlength: '80', required: 'required' }); |
| 499 | const error = el('p', { class: 'form-error' }); |
| 500 | const form = el('form', {}, [ |
| 501 | el('label', {}, ['Naam van de sleutel', name]), |
| 502 | el('button', { class: 'primary', type: 'submit' }, ['Sleutel aanmaken']), |
| 503 | error, |
| 504 | ]); |
| 505 | form.addEventListener('submit', async (event) => { |
| 506 | event.preventDefault(); |
| 507 | error.textContent = ''; |
| 508 | try { |
| 509 | const result = await api('POST', '/keys', { name: name.value }); |
| 510 | state.freshKey = result.key; |
| 511 | state.revealedKey = null; |
| 512 | await render(); |
| 513 | } catch (failure) { error.textContent = failure.message; } |
| 514 | }); |
| 515 | const section = el('section', { class: 'keys' }, [el('h1', {}, ['API-sleutels']), form]); |
| 516 | if (state.revealedKey && state.revealedKey.token) { |
| 517 | section.append(tokenPanel('Sleutel van ' + state.revealedKey.name, state.revealedKey.token)); |
| 518 | } else if (state.freshKey && state.freshKey.token) { |
| 519 | section.append(tokenPanel('Nieuwe sleutel. Tik er later opnieuw op om hem te zien.', state.freshKey.token)); |
| 520 | } |
| 521 | const list = el('div', {}); |
| 522 | keys.forEach((key) => { |
| 523 | const open = el('button', { type: 'button', class: 'key-open' }, [ |
| 524 | el('span', { class: key.revoked ? 'revoked' : '' }, [key.name]), |
| 525 | el('span', {}, [key.prefix + '…']), |
| 526 | el('span', {}, [key.revoked ? 'Ingetrokken' : 'Actief']), |
| 527 | ]); |
| 528 | open.addEventListener('click', async () => { |
| 529 | try { |
| 530 | const result = await api('GET', '/keys/' + key.id); |
| 531 | state.freshKey = null; |
| 532 | state.revealedKey = result.key; |
| 533 | await render(); |
| 534 | } catch (failure) { toast(failure.message); } |
| 535 | }); |
| 536 | const revoke = el('button', { class: 'danger', type: 'button' }, ['Intrekken']); |
| 537 | revoke.disabled = key.revoked != null; |
| 538 | revoke.addEventListener('click', async () => { |
| 539 | if (!window.confirm('Deze API-sleutel intrekken? Bestaande scripts kunnen dan niet meer schrijven.')) return; |
| 540 | try { await api('DELETE', '/keys/' + key.id); await render(); } |
| 541 | catch (failure) { toast(failure.message); } |
| 542 | }); |
| 543 | list.append(el('div', { class: 'key-row' }, [open, revoke])); |
| 544 | }); |
| 545 | if (!keys.length) list.append(el('p', { class: 'empty' }, ['Nog geen sleutels.'])); |
| 546 | section.append(el('h2', {}, ['Bestaande sleutels']), el('p', { class: 'lede' }, ['Tik op een sleutel om de volledige sleutel opnieuw te zien.']), list); |
| 547 | app.replaceChildren(section); |
| 548 | } |
| 549 | |
| 550 | async function render() { |
| 551 | const token = ++renderToken; |
| 552 | const path = pathNow(); |
| 553 | if (path !== '/sleutels') { |
| 554 | state.freshKey = null; |
| 555 | state.revealedKey = null; |
| 556 | } |
| 557 | closeMenu(); |
| 558 | highlight(path); |
| 559 | document.title = 'Verhalenboek'; |
| 560 | try { |
| 561 | const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/); |
| 562 | if (path === '/' || path === '' || weekMatch) { |
| 563 | const data = await api('GET', overviewQuery(weekMatch ? weekMatch[1] : null)); |
| 564 | if (token !== renderToken) return; |
| 565 | paintOverview(data); |
| 566 | } else if (path === '/instellingen') { |
| 567 | paintSettings(); |
| 568 | } else if (path === '/beheer') { |
| 569 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 570 | await paintBeheer(); |
| 571 | } else if (path === '/beheer/nieuw') { |
| 572 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 573 | await paintEditor(null); |
| 574 | } else if (/^\/beheer\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 575 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 576 | await paintEditor(path.slice('/beheer/'.length)); |
| 577 | } else if (path === '/sleutels') { |
| 578 | if (!state.me.admin) { app.replaceChildren(el('p', { class: 'form-error' }, ['Alleen een beheerder mag dit.'])); return; } |
| 579 | const data = await api('GET', '/keys'); |
| 580 | if (token !== renderToken) return; |
| 581 | paintKeys(data.keys); |
| 582 | } else if (/^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path)) { |
| 583 | const date = path.slice(5); |
| 584 | const day = await api('GET', '/days/' + date); |
| 585 | if (token !== renderToken) return; |
| 586 | paintDay(day); |
| 587 | document.title = day.title + ' · Verhalenboek'; |
| 588 | if (!day.read) { |
| 589 | try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ } |
| 590 | } |
| 591 | } else { |
| 592 | app.replaceChildren(el('p', { class: 'empty' }, ['Deze pagina bestaat niet.']), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 593 | } |
| 594 | } catch (error) { |
| 595 | if (token !== renderToken) return; |
| 596 | if (error.status === 401) { window.location.href = 'index.php'; return; } |
| 597 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht'])); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | async function boot() { |
| 602 | bindReadMenu(); |
| 603 | try { |
| 604 | const me = await api('GET', '/me'); |
| 605 | state.me = me.user; |
| 606 | state.csrf = me.csrf; |
| 607 | state.local = !!me.local; |
| 608 | applyPrefs(me.user); |
| 609 | } catch (error) { |
| 610 | app.replaceChildren(el('p', { class: 'form-error' }, [error.message])); |
| 611 | return; |
| 612 | } |
| 613 | window.addEventListener('hashchange', () => { render(); }); |
| 614 | if (!location.hash) location.replace('#/'); |
| 615 | else render(); |
| 616 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { |
| 617 | if (state.me && state.me.theme === 'system') applyPrefs(state.me); |
| 618 | }); |
| 619 | } |
projects-timfalken-com verhalenboek