BlueGit

projects-timfalken-com verhalenboek

fix: scroll naar boven bij wisselen van dag

Een dagwissel is een hash op hetzelfde document, dus de browser hield het
scrollpunt onderaan vast. Nieuwe dagen openen bovenaan; terug en vooruit
herstellen de opgeslagen plek, en weekpaginering blijft zoals die was.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa

Authored 2026-10-08 · 5 weeks ago

Hash
8dd1bc1f7fd2c632aab042560d99d23ceeabf211
Parent
3881be93
3 files changed +91 −4
web/assets/app.js +86 −3
@@ -21,6 +21,63 @@ function pathNow() {
21 21 return raw.startsWith('/') ? raw : '/' + raw;
22 22 }
23 23
24 function isDayRoute(path) {
25 return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path);
26 }
27
28 // Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per
29 // geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag
30 // bovenaan en geven terug/vooruit de opgeslagen plek terug.
31 let historyTraversal = false;
32 let scrollGeneration = 0;
33
34 function savedScrollY() {
35 const entry = history.state;
36 if (!entry || typeof entry !== 'object' || typeof entry.scrollY !== 'number') return null;
37 return entry.scrollY;
38 }
39
40 function saveScrollPosition() {
41 const y = window.scrollY || document.documentElement.scrollTop || 0;
42 const entry = history.state && typeof history.state === 'object' ? history.state : {};
43 if (entry.scrollY === y) return;
44 try { history.replaceState({ ...entry, scrollY: y }, ''); }
45 catch (error) { /* een volle geschiedenis mag het lezen niet blokkeren */ }
46 }
47
48 function scrollToPosition(y) {
49 const root = document.documentElement;
50 const previous = root.style.scrollBehavior;
51 root.style.scrollBehavior = 'auto';
52 window.scrollTo(0, y);
53 root.style.scrollBehavior = previous;
54 }
55
56 function settleScroll(path, traversal) {
57 let y = null;
58 if (traversal) y = savedScrollY();
59 if (y === null && isDayRoute(path)) y = 0;
60 if (y === null) {
61 // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen,
62 // zodat terug/vooruit die plek terugzet.
63 saveScrollPosition();
64 return;
65 }
66 const generation = ++scrollGeneration;
67 scrollToPosition(y);
68 saveScrollPosition();
69 requestAnimationFrame(() => {
70 if (generation !== scrollGeneration || pathNow() !== path) return;
71 scrollToPosition(y);
72 saveScrollPosition();
73 });
74 }
75
76 function navigateHash(hash) {
77 saveScrollPosition();
78 location.hash = hash;
79 }
80
24 81 function el(tag, attrs, children) {
25 82 const node = document.createElement(tag);
26 83 Object.entries(attrs || {}).forEach(([key, value]) => {
@@ -461,7 +518,7 @@ async function paintEditor(date) {
461 518 if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return;
462 519 try {
463 520 await api('DELETE', '/days/' + date);
464 location.hash = '#/beheer';
521 navigateHash('#/beheer');
465 522 } catch (failure) { error.textContent = failure.message; }
466 523 });
467 524 form.append(remove);
@@ -474,7 +531,7 @@ async function paintEditor(date) {
474 531 try {
475 532 if (creating) {
476 533 const created = await api('POST', '/days', { date: dateInput.value, ...payload });
477 location.hash = '#/beheer/' + created.date;
534 navigateHash('#/beheer/' + created.date);
478 535 } else {
479 536 await api('PUT', '/days/' + date, payload);
480 537 toast('Opgeslagen.');
@@ -608,6 +665,8 @@ function paintKeys(keys) {
608 665 async function render() {
609 666 const token = ++renderToken;
610 667 const path = pathNow();
668 const traversal = historyTraversal;
669 historyTraversal = false;
611 670 if (path !== '/sleutels') {
612 671 state.freshKey = null;
613 672 state.revealedKey = null;
@@ -615,6 +674,12 @@ async function render() {
615 674 closeMenu();
616 675 highlight(path);
617 676 document.title = 'Verhalenboek';
677 let settled = false;
678 const finishScroll = () => {
679 if (settled || token !== renderToken) return;
680 settled = true;
681 settleScroll(path, traversal);
682 };
618 683 try {
619 684 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
620 685 if (path === '/' || path === '' || weekMatch) {
@@ -642,12 +707,14 @@ async function render() {
642 707 const data = await api('GET', '/keys');
643 708 if (token !== renderToken) return;
644 709 paintKeys(data.keys);
645 } else if (/^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path)) {
710 } else if (isDayRoute(path)) {
646 711 const date = path.slice(5);
647 712 const day = await api('GET', '/days/' + date);
648 713 if (token !== renderToken) return;
649 714 paintDay(day);
650 715 document.title = day.title + ' · Verhalenboek';
716 // Vóór de lees-POST, anders schildert de browser de nieuwe dag nog onderaan.
717 finishScroll();
651 718 if (!day.read) {
652 719 try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ }
653 720 }
@@ -658,6 +725,8 @@ async function render() {
658 725 if (token !== renderToken) return;
659 726 if (error.status === 401) { window.location.href = 'index.php'; return; }
660 727 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht']));
728 } finally {
729 finishScroll();
661 730 }
662 731 }
663 732
@@ -673,7 +742,21 @@ async function boot() {
673 742 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]));
674 743 return;
675 744 }
745 if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
746 window.addEventListener('popstate', () => { historyTraversal = true; });
676 747 window.addEventListener('hashchange', () => { render(); });
748 document.addEventListener('click', (event) => {
749 if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
750 const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
751 if (!link || !(link.getAttribute('href') || '').startsWith('#')) return;
752 saveScrollPosition();
753 }, true);
754 let scrollSaveTimer = 0;
755 window.addEventListener('scroll', () => {
756 clearTimeout(scrollSaveTimer);
757 scrollSaveTimer = setTimeout(saveScrollPosition, 120);
758 }, { passive: true });
759 window.addEventListener('pagehide', saveScrollPosition);
677 760 if (!location.hash) location.replace('#/');
678 761 else render();
679 762 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
@@ -21,6 +21,63 @@ function pathNow() {
21 return raw.startsWith('/') ? raw : '/' + raw;
21 return raw.startsWith('/') ? raw : '/' + raw;
22}
22}
23
23
24function isDayRoute(path) {
25 return /^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path);
26}
27
28// Hash-navigatie blijft één document. De browser onthoudt het scrollpunt per
29// geschiedenisregel; bij handmatig herstel zetten we een nieuw geopende dag
30// bovenaan en geven terug/vooruit de opgeslagen plek terug.
31let historyTraversal = false;
32let scrollGeneration = 0;
33
34function savedScrollY() {
35 const entry = history.state;
36 if (!entry || typeof entry !== 'object' || typeof entry.scrollY !== 'number') return null;
37 return entry.scrollY;
38}
39
40function saveScrollPosition() {
41 const y = window.scrollY || document.documentElement.scrollTop || 0;
42 const entry = history.state && typeof history.state === 'object' ? history.state : {};
43 if (entry.scrollY === y) return;
44 try { history.replaceState({ ...entry, scrollY: y }, ''); }
45 catch (error) { /* een volle geschiedenis mag het lezen niet blokkeren */ }
46}
47
48function scrollToPosition(y) {
49 const root = document.documentElement;
50 const previous = root.style.scrollBehavior;
51 root.style.scrollBehavior = 'auto';
52 window.scrollTo(0, y);
53 root.style.scrollBehavior = previous;
54}
55
56function settleScroll(path, traversal) {
57 let y = null;
58 if (traversal) y = savedScrollY();
59 if (y === null && isDayRoute(path)) y = 0;
60 if (y === null) {
61 // Weekwissel en overige pagina's houden hun scrollpunt. Wel vastleggen,
62 // zodat terug/vooruit die plek terugzet.
63 saveScrollPosition();
64 return;
65 }
66 const generation = ++scrollGeneration;
67 scrollToPosition(y);
68 saveScrollPosition();
69 requestAnimationFrame(() => {
70 if (generation !== scrollGeneration || pathNow() !== path) return;
71 scrollToPosition(y);
72 saveScrollPosition();
73 });
74}
75
76function navigateHash(hash) {
77 saveScrollPosition();
78 location.hash = hash;
79}
80
24function el(tag, attrs, children) {
81function el(tag, attrs, children) {
25 const node = document.createElement(tag);
82 const node = document.createElement(tag);
26 Object.entries(attrs || {}).forEach(([key, value]) => {
83 Object.entries(attrs || {}).forEach(([key, value]) => {
@@ -461,7 +518,7 @@ async function paintEditor(date) {
461 if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return;
518 if (!window.confirm('Deze dag en de bijbehorende verhalen verwijderen? Dit kan niet ongedaan worden.')) return;
462 try {
519 try {
463 await api('DELETE', '/days/' + date);
520 await api('DELETE', '/days/' + date);
464 location.hash = '#/beheer';
521 navigateHash('#/beheer');
465 } catch (failure) { error.textContent = failure.message; }
522 } catch (failure) { error.textContent = failure.message; }
466 });
523 });
467 form.append(remove);
524 form.append(remove);
@@ -474,7 +531,7 @@ async function paintEditor(date) {
474 try {
531 try {
475 if (creating) {
532 if (creating) {
476 const created = await api('POST', '/days', { date: dateInput.value, ...payload });
533 const created = await api('POST', '/days', { date: dateInput.value, ...payload });
477 location.hash = '#/beheer/' + created.date;
534 navigateHash('#/beheer/' + created.date);
478 } else {
535 } else {
479 await api('PUT', '/days/' + date, payload);
536 await api('PUT', '/days/' + date, payload);
480 toast('Opgeslagen.');
537 toast('Opgeslagen.');
@@ -608,6 +665,8 @@ function paintKeys(keys) {
608async function render() {
665async function render() {
609 const token = ++renderToken;
666 const token = ++renderToken;
610 const path = pathNow();
667 const path = pathNow();
668 const traversal = historyTraversal;
669 historyTraversal = false;
611 if (path !== '/sleutels') {
670 if (path !== '/sleutels') {
612 state.freshKey = null;
671 state.freshKey = null;
613 state.revealedKey = null;
672 state.revealedKey = null;
@@ -615,6 +674,12 @@ async function render() {
615 closeMenu();
674 closeMenu();
616 highlight(path);
675 highlight(path);
617 document.title = 'Verhalenboek';
676 document.title = 'Verhalenboek';
677 let settled = false;
678 const finishScroll = () => {
679 if (settled || token !== renderToken) return;
680 settled = true;
681 settleScroll(path, traversal);
682 };
618 try {
683 try {
619 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
684 const weekMatch = path.match(/^\/week\/(\d{4}-\d{2}-\d{2})$/);
620 if (path === '/' || path === '' || weekMatch) {
685 if (path === '/' || path === '' || weekMatch) {
@@ -642,12 +707,14 @@ async function render() {
642 const data = await api('GET', '/keys');
707 const data = await api('GET', '/keys');
643 if (token !== renderToken) return;
708 if (token !== renderToken) return;
644 paintKeys(data.keys);
709 paintKeys(data.keys);
645 } else if (/^\/dag\/\d{4}-\d{2}-\d{2}$/.test(path)) {
710 } else if (isDayRoute(path)) {
646 const date = path.slice(5);
711 const date = path.slice(5);
647 const day = await api('GET', '/days/' + date);
712 const day = await api('GET', '/days/' + date);
648 if (token !== renderToken) return;
713 if (token !== renderToken) return;
649 paintDay(day);
714 paintDay(day);
650 document.title = day.title + ' · Verhalenboek';
715 document.title = day.title + ' · Verhalenboek';
716 // Vóór de lees-POST, anders schildert de browser de nieuwe dag nog onderaan.
717 finishScroll();
651 if (!day.read) {
718 if (!day.read) {
652 try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ }
719 try { await api('POST', '/days/' + date + '/read'); } catch (error) { /* de pagina blijft leesbaar */ }
653 }
720 }
@@ -658,6 +725,8 @@ async function render() {
658 if (token !== renderToken) return;
725 if (token !== renderToken) return;
659 if (error.status === 401) { window.location.href = 'index.php'; return; }
726 if (error.status === 401) { window.location.href = 'index.php'; return; }
660 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht']));
727 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]), el('a', { href: '#/' }, ['Naar het overzicht']));
728 } finally {
729 finishScroll();
661 }
730 }
662}
731}
663
732
@@ -673,7 +742,21 @@ async function boot() {
673 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]));
742 app.replaceChildren(el('p', { class: 'form-error' }, [error.message]));
674 return;
743 return;
675 }
744 }
745 if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
746 window.addEventListener('popstate', () => { historyTraversal = true; });
676 window.addEventListener('hashchange', () => { render(); });
747 window.addEventListener('hashchange', () => { render(); });
748 document.addEventListener('click', (event) => {
749 if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
750 const link = event.target instanceof Element ? event.target.closest('a[href]') : null;
751 if (!link || !(link.getAttribute('href') || '').startsWith('#')) return;
752 saveScrollPosition();
753 }, true);
754 let scrollSaveTimer = 0;
755 window.addEventListener('scroll', () => {
756 clearTimeout(scrollSaveTimer);
757 scrollSaveTimer = setTimeout(saveScrollPosition, 120);
758 }, { passive: true });
759 window.addEventListener('pagehide', saveScrollPosition);
677 if (!location.hash) location.replace('#/');
760 if (!location.hash) location.replace('#/');
678 else render();
761 else render();
679 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
762 window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
web/assets/pwa.js +4 −0
@@ -1,5 +1,9 @@
1 1 'use strict';
2 2
3 // Zelfde document bij een hash-wissel. Zonder dit zet de browser het oude
4 // scrollpunt terug, ook als de shell uit de service worker komt.
5 if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
6
3 7 function appScope() {
4 8 let path = window.location.pathname;
5 9 if (!path.endsWith('/')) {
@@ -1,5 +1,9 @@
1'use strict';
1'use strict';
2
2
3// Zelfde document bij een hash-wissel. Zonder dit zet de browser het oude
4// scrollpunt terug, ook als de shell uit de service worker komt.
5if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
6
3function appScope() {
7function appScope() {
4 let path = window.location.pathname;
8 let path = window.location.pathname;
5 if (!path.endsWith('/')) {
9 if (!path.endsWith('/')) {
web/lib/bootstrap.php +1 −1
@@ -247,7 +247,7 @@ function pwaHead(): void {
247 247 <meta name="apple-mobile-web-app-capable" content="yes">
248 248 <meta name="apple-mobile-web-app-title" content="Verhalenboek">
249 249 <meta name="apple-mobile-web-app-status-bar-style" content="default">
250 <script src="{$script}" defer></script>
250 <script src="{$script}"></script>
251 251
252 252 HTML;
253 253 }
@@ -247,7 +247,7 @@ function pwaHead(): void {
247<meta name="apple-mobile-web-app-capable" content="yes">
247<meta name="apple-mobile-web-app-capable" content="yes">
248<meta name="apple-mobile-web-app-title" content="Verhalenboek">
248<meta name="apple-mobile-web-app-title" content="Verhalenboek">
249<meta name="apple-mobile-web-app-status-bar-style" content="default">
249<meta name="apple-mobile-web-app-status-bar-style" content="default">
250<script src="{$script}" defer></script>
250<script src="{$script}"></script>
251
251
252HTML;
252HTML;
253}
253}