source: Klonkt/src/views/shell.ejs@ b8bbe77

main
Last change on this file since b8bbe77 was b8bbe77, checked in by Robin Genis <roboburr@…>, 2 months ago

debug(ios): temporary on-screen readout of env/inset/standalone/screen/masthead pad

  • Property mode set to 100644
File size: 34.5 KB
Line 
1<%
2// ── Helpers used inside this template ─────────────────────────────
3function _e(s) {
4 return String(s == null ? '' : s)
5 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
6 .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
7}
8
9const safeSite = site || {};
10const safeUrlBase = (typeof siteUrlBase !== 'undefined' && siteUrlBase) ? siteUrlBase : '';
11const safeAccent = safeSite.accent && /^#[0-9a-fA-F]{6}$/.test(safeSite.accent) ? safeSite.accent : '#e8b04b';
12const lang = safeSite.language || 'nl';
13const ogLocale = safeSite.og_locale || (lang === 'nl' ? 'nl_NL' : (lang.length === 2 ? lang + '_' + lang.toUpperCase() : 'en_US'));
14const homePath = safeUrlBase + '/';
15const isPostPage = bodyClass && bodyClass.indexOf('on-post') >= 0;
16const isHomePage = bodyClass && bodyClass.indexOf('on-home') >= 0;
17const isSpecialPg = bodyClass && bodyClass.indexOf('on-special') >= 0;
18const isAdminPage = bodyClass && bodyClass.indexOf('on-admin') >= 0;
19
20// ── <title> via site.title_template ──────────────────────────────
21// Template: '{title} — {site}'. If pageTitle equals site.title (homepage) we
22// just use the site title alone, otherwise apply the template.
23const _siteTitle = safeSite.title || 'Klonkt';
24const _rawTitle = pageTitle || _siteTitle;
25const _tpl = safeSite.title_template || '{title} — {site}';
26const _finalTitle = (_rawTitle === _siteTitle)
27 ? _siteTitle
28 : _tpl.replace('{title}', _rawTitle).replace('{site}', _siteTitle);
29
30// ── Robots: noindex on listing pages and on per-post override ─────
31let _shouldIndex = safeSite.robots_index !== 0;
32if (typeof post !== 'undefined' && post && post.noindex) _shouldIndex = false;
33// Listing pages (search/tag/type/archive) shouldn't be indexed (dupe content)
34if (currentPath) {
35 if (/^\/(?:search|tag|type|archive|users|account|admin)(?:$|\/)/.test(currentPath)) {
36 _shouldIndex = false;
37 }
38}
39// Special-flagged views from routes opt out too
40if (isSpecialPg && (currentPath === '/search' || /^\/(tag|type|archive|users)\//.test(currentPath))) {
41 _shouldIndex = false;
42}
43
44// ── Canonical URL (only when we have one configured) ─────────────
45let _canonical = null;
46if (safeSite.canonical) {
47 const _base = safeSite.canonical.replace(/\/+$/, '');
48 let _path = '/';
49 if (typeof post !== 'undefined' && post && post.slug) _path = '/' + post.slug;
50 else if (currentPath) _path = currentPath;
51 _canonical = _base + _path;
52}
53
54// ── Social bits (OG/Twitter) ──────────────────────────────────────
55const _socialTitle = (typeof post !== 'undefined' && post && post.title) ? post.title : _siteTitle;
56const _socialDescr = (typeof socialDescr !== 'undefined' && socialDescr)
57 ? socialDescr
58 : (safeSite.default_description || safeSite.description || '');
59// og:image — custom (post/site) first; otherwise the auto-generated themed card
60// (/og/<slug>.png), so every site has a branded social preview by default.
61let _socialImage = '', _ogGenerated = false;
62if (typeof socialImage !== 'undefined' && socialImage) _socialImage = socialImage;
63else if (safeSite.og_image_default) _socialImage = safeSite.og_image_default;
64else if (safeSite.default_cover) _socialImage = safeSite.default_cover;
65else if (safeSite.slug && typeof ogOrigin !== 'undefined' && ogOrigin) {
66 _socialImage = ogOrigin + '/og/' + encodeURIComponent(safeSite.slug) + '.png';
67 _ogGenerated = true;
68}
69const _ogType = isPostPage ? 'article' : 'website';
70
71// ── JSON-LD ───────────────────────────────────────────────────────
72const _publisher = {
73 '@type': safeSite.schema_type === 'Organization' ? 'Organization' : 'Person',
74 name: safeSite.publisher_name || _siteTitle,
75 url: safeSite.publisher_url || (_canonical ? _canonical.split(/(?<=^[^/]*\/\/[^/]+)\//)[0] + '/' : null),
76};
77if (safeSite.publisher_logo) {
78 _publisher.logo = { '@type': 'ImageObject', url: safeSite.publisher_logo };
79}
80let _jsonLd = null;
81if (typeof post !== 'undefined' && post && post.slug) {
82 _jsonLd = {
83 '@context': 'https://schema.org',
84 '@type': (post.type === 'foto' || post.type === 'video') ? 'CreativeWork' : 'Article',
85 headline: post.title || _siteTitle,
86 description: _socialDescr,
87 datePublished: post.published_at || post.created_at || new Date().toISOString(),
88 dateModified: post.updated_at || post.published_at || new Date().toISOString(),
89 publisher: _publisher,
90 };
91 if (_socialImage) _jsonLd.image = _socialImage;
92 if (post.author_username) _jsonLd.author = { '@type': 'Person', name: post.author_username };
93 if (Array.isArray(post.tags) && post.tags.length) _jsonLd.keywords = post.tags.join(', ');
94} else if (isHomePage) {
95 _jsonLd = {
96 '@context': 'https://schema.org',
97 '@type': 'WebSite',
98 name: _siteTitle,
99 description: safeSite.description || safeSite.default_description || '',
100 publisher: _publisher,
101 };
102}
103%><!DOCTYPE html>
104<html lang="<%= _e(lang) %>" data-palette="<%= _e((typeof palette !== 'undefined' && palette) ? palette : (safeSite.palette || 'klonkt')) %>">
105<head>
106<meta charset="utf-8">
107<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
108<meta name="color-scheme" content="dark light">
109
110<title><%= _finalTitle %></title>
111<meta name="description" content="<%= _e(_socialDescr) %>">
112<meta name="theme-color" content="<%= _e(safeAccent) %>">
113<meta name="robots" content="<%= _shouldIndex ? 'index,follow' : 'noindex,nofollow' %>">
114<% if (safeSite.author) { %><meta name="author" content="<%= _e(safeSite.author) %>"><% } %>
115<% if (_canonical) { %><link rel="canonical" href="<%= _e(_canonical) %>"><% } %>
116
117<!-- Search-engine verification -->
118<% if (safeSite.google_verification) { %><meta name="google-site-verification" content="<%= _e(safeSite.google_verification) %>"><% } %>
119<% if (safeSite.bing_verification) { %><meta name="msvalidate.01" content="<%= _e(safeSite.bing_verification) %>"><% } %>
120<% if (safeSite.pinterest_verification) { %><meta name="p:domain_verify" content="<%= _e(safeSite.pinterest_verification) %>"><% } %>
121<% if (safeSite.yandex_verification) { %><meta name="yandex-verification" content="<%= _e(safeSite.yandex_verification) %>"><% } %>
122
123<!-- Feed autodiscovery -->
124<% if (site) { %>
125<link rel="alternate" type="application/rss+xml" title="<%= _e(_siteTitle) %> — RSS" href="<%= _e(safeUrlBase + '/feed.xml') %>">
126<link rel="alternate" type="application/atom+xml" title="<%= _e(_siteTitle) %> — Atom" href="<%= _e(safeUrlBase + '/atom.xml') %>">
127<% } %>
128
129<!-- PWA -->
130<link rel="manifest" href="<%= _e(safeUrlBase + '/manifest.webmanifest') %>">
131<meta name="mobile-web-app-capable" content="yes">
132<meta name="apple-mobile-web-app-capable" content="yes">
133<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
134<meta name="apple-mobile-web-app-title" content="<%= _e(_siteTitle.slice(0, 16)) %>">
135<link rel="apple-touch-icon" href="<%= _e(safeSite.profile_photo || '/favicon.ico') %>">
136<link rel="icon" type="image/svg+xml" href="/favicon.svg?v=sf">
137<link rel="alternate icon" href="/favicon.ico?v=sf">
138
139<!-- OpenGraph -->
140<meta property="og:type" content="<%= _ogType %>">
141<meta property="og:title" content="<%= _e(_socialTitle) %>">
142<meta property="og:description" content="<%= _e(_socialDescr) %>">
143<meta property="og:site_name" content="<%= _e(_siteTitle) %>">
144<meta property="og:locale" content="<%= _e(ogLocale) %>">
145<% if (_socialImage) { %>
146<meta property="og:image" content="<%= _e(_socialImage) %>">
147<meta property="og:image:alt" content="<%= _e(_socialTitle) %>">
148<% if (_ogGenerated) { %>
149<meta property="og:image:width" content="1200">
150<meta property="og:image:height" content="630">
151<meta property="og:image:type" content="image/png">
152<% } %>
153<% } %>
154<% if (_canonical) { %><meta property="og:url" content="<%= _e(_canonical) %>"><% } %>
155<%
156// Fediverse/social PLAYER card for posts with audio: instead of shipping the raw
157// mp3, point at our embeddable player (/embed?post=slug) so Mastodon shows an
158// inline player that streams via the gated /audio/stream (no downloadable file).
159const _postAudio = !!(typeof post !== 'undefined' && post
160 && typeof postHasPlayableAudio !== 'undefined' && postHasPlayableAudio
161 && typeof premiumUnlocked !== 'undefined' && premiumUnlocked);
162const _embedUrl = _postAudio
163 ? ((typeof ogOrigin !== 'undefined' && ogOrigin ? ogOrigin : '') + safeUrlBase + '/embed?post=' + encodeURIComponent(post.slug))
164 : '';
165%>
166<% if (_postAudio) { %>
167<meta property="og:video" content="<%= _e(_embedUrl) %>">
168<meta property="og:video:secure_url" content="<%= _e(_embedUrl) %>">
169<meta property="og:video:type" content="text/html">
170<meta property="og:video:width" content="480">
171<meta property="og:video:height" content="480">
172<% } %>
173<% if (typeof post !== 'undefined' && post && post.published_at) { %>
174<meta property="article:published_time" content="<%= _e(post.published_at) %>">
175<% if (post.author_username) { %><meta property="article:author" content="<%= _e(post.author_username) %>"><% } %>
176<% } %>
177<% if (safeSite.facebook_app_id) { %><meta property="fb:app_id" content="<%= _e(safeSite.facebook_app_id) %>"><% } %>
178
179<!-- Twitter Cards -->
180<meta name="twitter:card" content="<%= _postAudio ? 'player' : (_socialImage ? 'summary_large_image' : 'summary') %>">
181<% if (_postAudio) { %>
182<meta name="twitter:player" content="<%= _e(_embedUrl) %>">
183<meta name="twitter:player:width" content="480">
184<meta name="twitter:player:height" content="480">
185<% } %>
186<meta name="twitter:title" content="<%= _e(_socialTitle) %>">
187<meta name="twitter:description" content="<%= _e(_socialDescr) %>">
188<% if (_socialImage) { %><meta name="twitter:image" content="<%= _e(_socialImage) %>"><% } %>
189<% if (safeSite.twitter) { %><meta name="twitter:creator" content="<%= _e(safeSite.twitter) %>"><meta name="twitter:site" content="<%= _e(safeSite.twitter) %>"><% } %>
190
191<% if (_jsonLd) { %>
192<script type="application/ld+json"><%- JSON.stringify(_jsonLd) %></script>
193<% } %>
194
195<!-- Self-hosted fonts (privacy-first) -->
196<link rel="preload" href="/assets/fonts/literata-latin-opsz-normal.woff2" as="font" type="font/woff2" crossorigin>
197<link rel="preload" href="/assets/fonts/fraunces-latin-full-normal.woff2" as="font" type="font/woff2" crossorigin>
198
199<!-- v9 stylesheet (full palette system) -->
200<link rel="stylesheet" href="/assets/css/style.css?v=54">
201<script>
202/* iOS safe-area, built by hand. env(safe-area-inset-top) resolves to 0 on this iOS in
203 BOTH Safari and the installed PWA (standalone), even with viewport-fit=cover, so the
204 masthead can't clear the camera. We measure env directly and, when it comes back empty
205 on a notched iPhone, fall back to a fixed inset (a bit larger in standalone for the
206 Dynamic Island). We set --ios-safe-top AND force the masthead padding inline — the
207 latter survives a stale cached stylesheet that lacks the var. Re-applied after htmx
208 chrome swaps (the top-nav is out-of-band swapped on navigation). */
209(function(){
210 var ua = navigator.userAgent || '';
211 var isIOS = /iP(hone|od|ad)/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
212 if (!isIOS) return;
213 var standalone = (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || navigator.standalone === true;
214 function apply(){
215 if (!document.body) return;
216 var p = document.createElement('div');
217 p.style.cssText = 'position:fixed;top:0;left:0;width:0;height:0;padding-top:env(safe-area-inset-top,0px);visibility:hidden;pointer-events:none';
218 document.body.appendChild(p);
219 var rawEnv = parseFloat(getComputedStyle(p).paddingTop) || 0;
220 p.remove();
221 var i = rawEnv;
222 if (i < 20 && Math.max(screen.width, screen.height) >= 812) i = standalone ? 59 : 47;
223 document.documentElement.style.setProperty('--ios-safe-top', i + 'px');
224 var mh = document.querySelector('.masthead');
225 if (mh) mh.style.paddingTop = 'calc(.55rem + ' + i + 'px)';
226 /* TEMP DEBUG — remove after diagnosing the iOS PWA safe-area. Tap to dismiss. */
227 var d = document.getElementById('ios-dbg');
228 if (!d) { d = document.createElement('div'); d.id = 'ios-dbg'; d.onclick = function(){ d.remove(); };
229 d.style.cssText = 'position:fixed;left:6px;bottom:96px;z-index:2147483647;background:rgba(0,0,0,.86);color:#0f0;font:11px/1.4 monospace;padding:7px 9px;border-radius:6px;white-space:pre;max-width:92vw';
230 document.body.appendChild(d); }
231 d.textContent = 'env=' + rawEnv + ' final=' + i + '\nstandalone=' + standalone + '\nscreen=' + screen.width + 'x' + screen.height + ' dpr=' + window.devicePixelRatio + '\nmasthead pad=' + (mh ? getComputedStyle(mh).paddingTop : 'NOT FOUND');
232 }
233 if (document.body) apply(); else document.addEventListener('DOMContentLoaded', apply);
234 document.addEventListener('htmx:afterSettle', apply);
235 window.addEventListener('orientationchange', function(){ setTimeout(apply, 250); });
236})();
237</script>
238
239<!-- Audio player styles: loaded on every page so the mini-player works
240 anywhere (admin previews, post embeds, etc). The player itself is
241 a singleton — see the script tag near </body>. -->
242<link rel="stylesheet" href="/assets/css/audio.css?v=11">
243<!-- Eigen custom media-embeds (YouTube/SoundCloud/Spotify) in huisstijl. -->
244<link rel="stylesheet" href="/assets/css/embed.css?v=8">
245
246<%- include('partials/shared-styles') %>
247
248<!-- v1 P55 — Inline the saved site accent. The base stylesheet only sets a
249 fallback (#c2410c orange) and palette blocks don't define --accent at
250 all, so without this override the saved accent never reaches the page.
251 :root + [data-palette] hits both unscoped and palette-scoped variants;
252 source-order wins on equal specificity, and this comes after style.css. -->
253<style id="pcms-site-accent">
254 :root,
255 [data-palette] {
256 --accent: <%= _e(safeAccent) %>;
257 --accent-soft: color-mix(in srgb, <%= _e(safeAccent) %> 80%, white);
258 --accent-tint: color-mix(in srgb, <%= _e(safeAccent) %> 12%, transparent);
259 }
260</style>
261
262<!-- Per-site custom CSS injection -->
263<% if (safeSite.custom_css) { %>
264<style id="pcms-custom-css"><%- safeSite.custom_css %></style>
265<% } %>
266
267<!-- Apply theme ASAP, before paint. Precedence (first match wins):
268 1. localStorage override (visitor toggled earlier on this browser)
269 2. Site default (theme_override + palette) — what new visitors see
270 3. Device prefers-color-scheme (only if site default is empty/auto)
271 4. 'dark' as last-ditch fallback
272 Note: PALETTE never has a localStorage layer anymore. There's no UI for
273 visitors to pick a palette, so any cached pcms-palette is stale data
274 from old code paths and gets cleaned up here. Site default always wins
275 for palette. -->
276<script>
277 (function() {
278 try {
279 var siteDefault = '<%= safeSite.theme_override || "" %>';
280 var sitePalette = '<%= (typeof palette !== 'undefined' && palette) ? palette : (safeSite.palette || 'klonkt') %>';
281
282 // One-time cleanup: drop the orphan pcms-palette key set by P43-P57
283 // bootstrap. After this it never re-appears because nothing writes it.
284 try { localStorage.removeItem('pcms-palette'); } catch(_) {}
285
286 // Theme: localStorage > site override > device pref > dark
287 var storedTheme = null;
288 try { storedTheme = localStorage.getItem('pcms-theme'); } catch(_) {}
289 var deviceDark = window.matchMedia &&
290 window.matchMedia('(prefers-color-scheme: dark)').matches;
291 var t = storedTheme
292 || siteDefault
293 || (deviceDark ? 'dark' : 'light');
294
295 // Palette: site default only.
296 document.documentElement.setAttribute('data-theme', t);
297 document.documentElement.setAttribute('data-palette', sitePalette);
298 } catch(e) {
299 document.documentElement.setAttribute('data-theme', 'dark');
300 }
301 })();
302</script>
303
304<!-- HTMX — bundled locally from node_modules at boot, zero third-party requests -->
305<script src="/assets/js/htmx.min.js"></script>
306
307<!-- Per-site custom <head> HTML (analytics, verification, etc.) -->
308<% if (safeSite.custom_head_html) { %>
309<%- safeSite.custom_head_html %>
310<% } %>
311</head>
312
313<body class="<%= bodyClass || 'on-home' %> has-bottom-tab" data-feed-view="<%= _e(safeSite.feed_view_default || 'timeline') %>" data-grid-cols="3" data-site-base="<%= _e((typeof siteUrlBase !== 'undefined' && siteUrlBase) ? siteUrlBase : '') %>">
314
315<% if (typeof isViewer !== 'undefined' && isViewer) { %>
316 <div class="viewer-banner" role="status">
317 <span class="viewer-banner-ico" aria-hidden="true">👁️</span>
318 <span class="viewer-banner-text"><strong>Kijker-modus</strong> — je kunt alles bekijken, maar niets wijzigen.</span>
319 </div>
320 <style>
321 .viewer-banner {
322 position: sticky; top: 0; z-index: 60;
323 display: flex; align-items: center; justify-content: center; gap: 0.5rem;
324 padding: 0.5rem 1rem;
325 background: linear-gradient(90deg,
326 color-mix(in srgb, var(--accent) 88%, #000) 0%,
327 var(--accent) 100%);
328 color: #fff;
329 font-size: 0.85rem; line-height: 1.3;
330 box-shadow: 0 1px 6px color-mix(in srgb, var(--accent) 45%, transparent);
331 }
332 .viewer-banner-ico { font-size: 1rem; }
333 .viewer-banner-text strong { font-weight: 700; }
334 </style>
335<% } %>
336
337<%# Site-chrome (topnav + profielkop + view-switcher) in één vaste slot #pcms-chrome.
338 Bij htmx-navigatie wordt dit slot out-of-band ververst (zie chrome.ejs +
339 render.js), zodat de kop ALTIJD bij de nieuwe pagina/artiest hoort terwijl de
340 audioplayer (los in document.body) blijft leven → geen verspringen. Op de
341 hub-landing is het slot leeg: de hero is daar de header. %>
342<%- include('partials/chrome') %>
343
344<%# Geen hx-history-elt: htmx' eigen history staat uit (zie de link-boost).
345 Back/forward wordt door onze popstate-listener gedaan, die de partial
346 her-fetcht (incl. correcte OOB-chrome). Met hx-history-elt + htmx-history
347 aan dumpte htmx de partial ongefilterd hier → dubbele kop. %>
348<main id="pcms-main" class="pcms-main">
349 <div id="pcms-loading" class="pcms-loading" aria-hidden="true"></div>
350 <%- pageContent %>
351</main>
352
353<%- include('partials/footer') %>
354
355<!-- Mobile bottom-tab navigation (auto-hidden ≥768px). Toont overal — óók op de
356 hub-landing (zodat mobiel altijd Home/Zoek/Inloggen heeft) — behalve op de
357 auth-focusschermen. -->
358<% if (!(typeof bodyClass === 'string' && bodyClass.indexOf('on-auth') >= 0)) { %>
359<%- include('partials/bottom-tab') %>
360<% } %>
361
362<!-- Mobile profile sheet (auto-hidden ≥768px; only rendered when logged in) -->
363<% if (user) { %>
364<%- include('partials/profile-sheet') %>
365<% } %>
366
367<!-- Audio player: load on every page (admin + public) so window.pcmsAudioPlayer
368 is always available. The PCMS_SITE_TRACKS bootstrap is still gated on
369 enable_audio_player since it's a public-page concept (auto-discovered
370 tracks from rendered post embeds).
371
372 ?v=N — cache-buster: bump bij elke audio-player.js wijziging zodat
373 Cloudflare (max-age=1y) niet de oude versie blijft serveren. -->
374<script src="/assets/js/audio-player.js?v=30"></script>
375<!-- Eigen custom media-embeds (YouTube/SoundCloud/Spotify) via de echte
376 player-API's + gedeelde mutual-exclusion registry met de site-speler. -->
377<script src="/assets/js/embed-player.js?v=16" defer></script>
378<% if (site && site.enable_audio_player && audioTracks && audioTracks.length > 0) { %>
379 <script>window.PCMS_SITE_TRACKS = <%- JSON.stringify(audioTracks) %>;</script>
380<% } %>
381
382<!-- Install-app button: detects platform + shows install instructions modal -->
383<script src="/assets/js/install-app.js?v=2" defer></script>
384
385<!-- Service Worker registration -->
386<script>
387 if ('serviceWorker' in navigator) {
388 navigator.serviceWorker.register('/sw.js').catch(() => {});
389 }
390</script>
391
392<!-- HTMX navigation: keep body class in sync with the swapped page.
393 The server emits HX-Trigger-After-Settle: { pcmsNav: { bodyClass } } via
394 renderPage() in middleware/render.js. Without this listener the body
395 class stays whatever the initial page-load set, so the profile-header
396 never collapses/expands when navigating home → post → home via HTMX. -->
397<script>
398(function() {
399 // De page-context body-classes. Bij pcmsNav strippen we ze allemaal en zetten
400 // we opnieuw wat de server stuurde. 'on-auth' staat erbij zodat het login-
401 // focusscherm óók via htmx z'n styling krijgt (geen chrome, geen tab, audio op 0).
402 var PAGE_CLASSES = ['on-home','on-post','on-special','on-archive','on-search','on-admin','on-auth',
403 'on-shows','on-downloads','on-download','on-epk','on-linkbio','on-newsletter',
404 'on-tag','on-type','on-user','on-cirkel','on-hub','on-chat'];
405
406 document.body.addEventListener('pcmsNav', function(ev) {
407 var d = ev.detail || {};
408 // Per-site accent + palette bijwerken (head wordt niet mee-geswapt bij htmx-nav,
409 // dus zonder dit erft een artiest de kleuren van de vorige pagina).
410 if (d.accent && /^#[0-9a-fA-F]{6}$/.test(d.accent)) {
411 var sa = document.getElementById('pcms-site-accent');
412 if (sa) {
413 sa.textContent =
414 ':root,[data-palette]{--accent:' + d.accent +
415 ';--accent-soft:color-mix(in srgb,' + d.accent + ' 80%,white)' +
416 ';--accent-tint:color-mix(in srgb,' + d.accent + ' 12%,transparent);}';
417 }
418 }
419 if (d.palette && /^[a-z0-9-]+$/i.test(d.palette)) {
420 document.documentElement.setAttribute('data-palette', d.palette);
421 }
422
423 var next = d.bodyClass;
424 if (!next) return;
425 // De server kan meerdere page-classes sturen ("on-special on-auth"). Strip
426 // alle bekende en zet ALLE meegestuurde page-classes terug (niet alleen de
427 // eerste) — anders mist 'on-auth' bij htmx-nav en blijft het login-scherm
428 // de chrome/tab van de vorige pagina houden.
429 var matched = String(next).split(/\s+/).filter(function(c) {
430 return PAGE_CLASSES.indexOf(c) >= 0;
431 });
432 if (!matched.length) return;
433 PAGE_CLASSES.forEach(function(c) { document.body.classList.remove(c); });
434 matched.forEach(function(c) { document.body.classList.add(c); });
435 });
436
437 // (Back/forward wordt afgehandeld door de popstate-listener in de link-boost
438 // hieronder — die her-fetcht de partial via htmx.ajax, wat de OOB-chrome +
439 // de pcmsNav-trigger (accent/palette/bodyClass) correct toepast. De vroegere
440 // htmx:historyRestore-handler is vervallen nu htmx-history uitstaat.)
441})();
442</script>
443
444<!-- View switcher + grid-cols persistence (event delegation: works for switcher
445 elements rendered later by HTMX, e.g. when navigating back to home). -->
446<script>
447(function() {
448 var body = document.body;
449 // Restore feed view + grid cols from localStorage (overrides server default)
450 try {
451 var v = localStorage.getItem('pcms-feed-view');
452 if (v === 'timeline' || v === 'grid') body.dataset.feedView = v;
453 var c = parseInt(localStorage.getItem('pcms-grid-cols'), 10);
454 if (c === 2 || c === 3 || c === 4) body.dataset.gridCols = String(c);
455 } catch (e) {}
456
457 function syncAria() {
458 // Alleen op een feed-pagina hoort Tijdlijn/Grid 'actief' (wit) te zijn; op
459 // agenda/downloads/post/etc. beide grijs. Inline feed-check (FEED_PAGE_CLASSES
460 // staat verderop, maar deze functie draait al bij init).
461 var _feedC = ['on-home','on-tag','on-type','on-user','on-cirkel'];
462 var _onFeed = _feedC.some(function(c){ return body.classList.contains(c); });
463 document.querySelectorAll('.view-switch-btn').forEach(function(b) {
464 b.setAttribute('aria-selected', (_onFeed && b.dataset.view === body.dataset.feedView) ? 'true' : 'false');
465 });
466 document.querySelectorAll('.grid-cols-btn').forEach(function(b) {
467 b.classList.toggle('is-active', b.dataset.cols === body.dataset.gridCols);
468 });
469 }
470 syncAria();
471 // Re-sync after HTMX brings in new content (e.g. navigating back to home).
472 // pcmsNav vuurt ná de body-class-update (zie de pcmsNav-listener hierboven), dus
473 // dáár weet syncAria de juiste pagina-class — los van de afterSettle-timing.
474 // Een vertraagde herhaling wint eventuele resterende races (OOB-chrome-swap).
475 document.body.addEventListener('htmx:afterSettle', function(){ syncAria(); setTimeout(syncAria, 60); });
476 document.body.addEventListener('pcmsNav', function(){ syncAria(); setTimeout(syncAria, 60); });
477
478 // Pages where the body actually has a feed to toggle. On these the
479 // click stays put — it just flips body[data-feed-view] and CSS does
480 // the rest. Anywhere else (post detail, account, search, auth) we
481 // navigate to home in the chosen view, so the switcher is never
482 // a dead control.
483 // NB: 'on-archive' staat hier bewust NIET tussen — op het archief is er geen
484 // in-place timeline/grid-toggle; een klik op de switcher springt terug naar de
485 // feed in de gekozen weergave (zie de !isFeedPage()-tak hieronder).
486 var FEED_PAGE_CLASSES = ['on-home', 'on-tag', 'on-type', 'on-user', 'on-cirkel'];
487 function isFeedPage() {
488 for (var i = 0; i < FEED_PAGE_CLASSES.length; i++) {
489 if (body.classList.contains(FEED_PAGE_CLASSES[i])) return true;
490 }
491 return false;
492 }
493
494 // Event delegation — single listener handles current and future buttons.
495 document.addEventListener('click', function(e) {
496 var sw = e.target.closest('.view-switch-btn');
497 if (sw) {
498 var view = sw.dataset.view;
499 body.dataset.feedView = view;
500 try { localStorage.setItem('pcms-feed-view', view); } catch(_) {}
501 syncAria();
502 // On non-feed pages the switcher acts as a navigation: take the
503 // user back to home in the chosen view. Use HTMX if available so
504 // the page transition matches the rest of the site's nav.
505 if (!isFeedPage()) {
506 // Naar de SITE-home in de gekozen view (siteUrlBase), niet de globale '/'
507 // — in hub is '/' de hub-overview, niet de tijdlijn van deze artiest.
508 var base = body.dataset.siteBase || '';
509 if (window.htmx) {
510 window.htmx.ajax('GET', base + '/?partial=1', { target: '#pcms-main', swap: 'innerHTML' });
511 history.pushState({}, '', base + '/');
512 } else {
513 location.href = base + '/';
514 }
515 }
516 return;
517 }
518 var gc = e.target.closest('.grid-cols-btn');
519 if (gc) {
520 body.dataset.gridCols = gc.dataset.cols;
521 try { localStorage.setItem('pcms-grid-cols', gc.dataset.cols); } catch(_) {}
522 syncAria();
523 }
524 });
525})();
526</script>
527
528<!-- Globale link-boost: alle interne navigatie-links lopen via htmx in #pcms-main,
529 zodat de audioplayer (los in document.body) blijft spelen i.p.v. te verspringen
530 bij een full page-load. Werkt overal — Beheer, Account, posts, sites — zonder
531 elke link los htmx te maken. Links die écht een volledige load nodig hebben
532 (uitloggen/auth, downloads, feeds, media, assets, bestanden) worden overgeslagen,
533 net als links die al hun eigen hx-* hebben. -->
534<script>
535(function () {
536 if (!window.htmx) return;
537 // htmx' EIGEN history-afhandeling volledig uitzetten. We doen back/forward zelf
538 // via de popstate-listener hieronder (htmx.ajax → verwerkt de OOB-chrome netjes).
539 // Lieten we htmx z'n gang gaan, dan herstelde 'ie #pcms-main door de partial
540 // (inclusief de <div id=pcms-chrome hx-swap-oob>) ONGEFILTERD in #pcms-main te
541 // dumpen → een tweede, geneste kop = de pagina dubbel. Eén mechanisme nu.
542 try { window.htmx.config.historyEnabled = false; } catch (_) {}
543
544 function fullLoad(a, url) {
545 if (a.hasAttribute('download') || a.hasAttribute('data-full-load')) return true;
546 if (a.hasAttribute('hx-get') || a.hasAttribute('hx-post') || a.hasAttribute('hx-boost')) return true;
547 if (a.target && a.target !== '_self') return true;
548 if (a.getAttribute('rel') === 'external') return true;
549 var p = url.pathname;
550 // Sessie/redirect-acties → volledige navigatie (cookies, Google-redirect).
551 // Maar de auth-FORMULIERpagina's (/auth/admin, /auth/login, /auth/register,
552 // /auth/reset…) mogen wél via htmx, zodat de audiospeler blijft doorspelen
553 // i.p.v. te herstarten/verspringen bij een volledige page-load.
554 if (/^\/(logout|oauth)(?:\/|$)/.test(p)) return true;
555 if (/^\/auth\/(logout|google)(?:\/|$)/.test(p)) return true;
556 // Feeds, PWA, service-worker, statics, media-streams, downloads.
557 if (/^\/(feed|atom|sitemap|manifest|robots|sw\.js|assets|media|audio|uploads)(?:\/|\.|$)/.test(p)) return true;
558 if (/\.[a-z0-9]{2,5}$/i.test(p)) return true; // bestandsextensie → laat de browser 't halen
559 return false;
560 }
561
562 var lastPath = location.pathname + location.search;
563 var navTimer = null;
564
565 // Eén plek voor alle programmatische navigatie-swaps. Annuleert eerst een nog
566 // lopende request op #pcms-main (anti-race: bij snel klikken/terug-gaan kan een
567 // trage oude response anders een nieuwe pagina overschrijven → "kale content").
568 function doNav(dest) {
569 try { window.htmx.trigger('#pcms-main', 'htmx:abort'); } catch (_) {}
570 window.htmx.ajax('GET', dest, { target: '#pcms-main', swap: 'innerHTML' });
571 }
572
573 document.addEventListener('click', function (e) {
574 if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
575 var a = e.target.closest('a[href]');
576 if (!a) return;
577 var href = a.getAttribute('href');
578 if (!href || href.charAt(0) === '#') return;
579 var url; try { url = new URL(a.href, location.href); } catch (_) { return; }
580 if (url.origin !== location.origin) return;
581 if (fullLoad(a, url)) return;
582 e.preventDefault();
583 var dest = url.pathname + url.search;
584 if (dest !== lastPath) history.pushState({ b: 1 }, '', dest);
585 lastPath = dest;
586 if (navTimer) { clearTimeout(navTimer); navTimer = null; }
587 doNav(dest);
588 try { window.scrollTo(0, 0); } catch (_) {}
589 });
590
591 window.addEventListener('popstate', function () {
592 var here = location.pathname + location.search;
593 if (here === lastPath) return;
594 lastPath = here;
595 // Debounce: bij heel snel/herhaald terug-vooruit niet elke tussenpagina ophalen,
596 // alleen de LAATSTE bestemming. Voorkomt overlappende swaps ("kale content").
597 if (navTimer) clearTimeout(navTimer);
598 navTimer = setTimeout(function () {
599 navTimer = null;
600 doNav(location.pathname + location.search);
601 }, 90);
602 });
603
604 // Links MÉT eigen hx-get + hx-push-url (post-card/post-tile/topnav/…) lopen NIET
605 // via de boost hierboven, en hx-push-url is een no-op nu htmx-history uitstaat.
606 // Doe daarom de adresbalk-update hier zelf zodra htmx swapt. Programmatische
607 // htmx.ajax-calls (boost/popstate) hebben geen elt met hx-push-url → geen dubbel.
608 document.body.addEventListener('htmx:beforeRequest', function (evt) {
609 try {
610 var elt = evt.detail && evt.detail.elt; // het TRIGGERENDE element (de link)
611 if (!elt || !elt.closest) return;
612 var node = elt.closest('[hx-push-url]');
613 if (!node) return;
614 var u = node.getAttribute('hx-push-url');
615 if (!u || u === 'false') return;
616 if (u !== (location.pathname + location.search)) history.pushState({ b: 1 }, '', u);
617 lastPath = u;
618 } catch (_) {}
619 });
620
621 // Spring naar boven na ELKE navigatie-swap van #pcms-main. De boost hierboven
622 // scrollt al, maar links met hun eigen hx-get (post-nav Newer/Older, post-kaarten)
623 // lopen NIET via de boost → zonder dit blijf je op de oude scrollpositie hangen
624 // bij het openen van een gerelateerde/volgende post. Alleen #pcms-main, zodat
625 // in-page swaps (comments e.d.) en de OOB-chrome-swap niet meescrollen.
626 document.body.addEventListener('htmx:afterSwap', function (evt) {
627 var t = evt.detail && evt.detail.target;
628 if (t && t.id === 'pcms-main') { try { window.scrollTo(0, 0); } catch (_) {} }
629 });
630})();
631</script>
632
633<!-- Mobiel toetsenbord vs. site-layout: zet body.kb-open zodra het toetsenbord
634 open is (visual viewport fors korter dan het venster) ÉN er een invoerveld
635 focus heeft. CSS verbergt dan de vaste onderbalken (bottom-tab + mini-speler)
636 zodat ze niet over het invoerveld zweven. -->
637<script>
638(function () {
639 var vv = window.visualViewport;
640 if (!vv) return;
641 function isField(el) {
642 if (!el) return false;
643 var t = el.tagName;
644 return t === 'INPUT' || t === 'TEXTAREA' || el.isContentEditable;
645 }
646 function update() {
647 var open = (window.innerHeight - vv.height) > 150 && isField(document.activeElement);
648 document.body.classList.toggle('kb-open', open);
649 }
650 vv.addEventListener('resize', update);
651 vv.addEventListener('scroll', update);
652 document.addEventListener('focusin', function () { setTimeout(update, 60); });
653 document.addEventListener('focusout', function () { setTimeout(update, 60); });
654})();
655</script>
656
657<!-- Afbeeldingen lastiger op te slaan: rechtsklik-menu + slepen blokkeren op <img>.
658 Frictie, geen echte beveiliging (DevTools/screenshot blijven kunnen). -->
659<script>
660(function () {
661 document.addEventListener('contextmenu', function (e) {
662 if (e.target && e.target.tagName === 'IMG') e.preventDefault();
663 });
664 document.addEventListener('dragstart', function (e) {
665 if (e.target && e.target.tagName === 'IMG') e.preventDefault();
666 });
667})();
668</script>
669
670<!-- Auto-resize: elk <textarea> groeit mee met de inhoud i.p.v. intern te scrollen
671 (scroll-binnen-scroll is verwarrend). Site-breed; ook na htmx-swaps. -->
672<script>
673(function () {
674 function autoSize(ta) {
675 if (!ta || ta.tagName !== 'TEXTAREA') return;
676 ta.style.overflowY = 'hidden';
677 ta.style.height = 'auto';
678 ta.style.height = ta.scrollHeight + 'px';
679 }
680 function sizeAll(root) {
681 (root || document).querySelectorAll('textarea').forEach(autoSize);
682 }
683 document.addEventListener('input', function (e) { autoSize(e.target); });
684 document.addEventListener('focusin', function (e) { autoSize(e.target); });
685 // Init + opnieuw na htmx-navigatie/partials.
686 sizeAll();
687 document.body.addEventListener('htmx:afterSettle', function () { sizeAll(); });
688 window.addEventListener('load', function () { sizeAll(); });
689})();
690</script>
691
692<!-- PWA install prompt — show button when browser fires beforeinstallprompt -->
693<script>
694(function() {
695 var btn = document.getElementById('pwa-install-btn');
696 if (!btn) return;
697 var deferred = null;
698 window.addEventListener('beforeinstallprompt', function(e) {
699 e.preventDefault();
700 deferred = e;
701 btn.hidden = false;
702 });
703 btn.addEventListener('click', async function() {
704 if (!deferred) return;
705 btn.hidden = true;
706 deferred.prompt();
707 try { await deferred.userChoice; } catch(e) {}
708 deferred = null;
709 });
710 window.addEventListener('appinstalled', function() {
711 btn.hidden = true;
712 deferred = null;
713 });
714})();
715</script>
716
717<!-- Per-site custom footer HTML -->
718<% if (safeSite.custom_foot_html) { %>
719<%- safeSite.custom_foot_html %>
720<% } %>
721
722</body>
723</html>
Note: See TracBrowser for help on using the repository browser.