source: Klonkt/src/middleware/render.js@ 6be57b4

main
Last change on this file since 6be57b4 was a3e2f17, checked in by roboburr <roboburr@…>, 3 months ago

Fix: update per-site accent + palette on htmx navigation

The accent colour (style#pcms-site-accent) and palette (html[data-palette])
live in the shell <head>, which is not swapped during htmx nav. As a result
an artist inherited the colours of the previous page (e.g. De Kelderband
got the hub's purple instead of its own green). pcmsNav now sends
accent+palette along; the client updates the accent <style> and
data-palette. Applies to all htmx nav (boost + explicit links).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 7.9 KB
RevLine 
[7bc636b]1/**
2 * Render helper — THE pattern for the entire app.
3 *
4 * Two modes:
5 * 1. HTMX request → render just the page content (no shell)
6 * 2. Full page request → render content, then embed in shell
7 *
8 * Usage:
9 * renderPage(req, res, 'pages/home', { posts, ...data })
10 */
11
[83faa57]12import fs from 'fs';
[7bc636b]13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
[8cb1dc7]16import db from '../config/database.js';
[7bc636b]17import PermissionsService from '../services/PermissionsService.js';
[8afbdd6]18import { isViewer } from './auth.js';
[42081fb]19import { getSetting } from '../services/SettingsService.js';
[8aa85d0]20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
[7bc636b]21import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
22
23const __dirname = path.dirname(fileURLToPath(import.meta.url));
24const VIEWS_DIR = path.join(__dirname, '..', 'views');
25
[83faa57]26// App-versie (uit package.json) — getoond in de footer naast "Klonkt Beta".
27let APP_VERSION = '';
28try {
29 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
30} catch { /* geen versie beschikbaar */ }
31
[7bc636b]32const formatDate = (iso) => {
33 if (!iso) return '';
34 const d = new Date(iso);
35 const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
36 return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
37};
38
39const formatDateTime = (iso) => {
40 if (!iso) return '';
41 const d = new Date(iso);
42 return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
43};
44
45export async function renderPage(req, res, viewName, data = {}) {
46 // Decide: partial (HTMX) or full?
47 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
48
[8cb1dc7]49 // Bezit deze (niet-god) user een eigen site? Bepaalt of 'ie een "Beheer"-
50 // ingang ziet (artiest-zelfbeheer). god ziet beheer sowieso (op rol).
51 const _u = req.session?.user || null;
52 const userOwnsSite = !!(_u && _u.role !== 'god' &&
53 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
54
[baa2e59]55 // De avatar van de SITE-EIGENAAR (niet de kijker!) — voor de Klonkt-site-kop,
[ab544fd]56 // zodat de artiest z'n eigen account-foto als sitefoto kan gebruiken.
57 const _site = data.site || res.locals.site || null;
58 const siteOwnerAvatar = (_site && _site.owner_id)
59 ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
60 : null;
61
[8afbdd6]62 // Kijker-modus: alles bekijken mag, niets wijzigen. Views gebruiken canMutate
63 // om schrijf-knoppen (posten, opslaan, verwijderen) te verbergen/uit te zetten.
64 const _isViewer = isViewer(_u);
65
[a3169f5]66 // Wie ziet de "Beheer"-link? god/admin, een site-eigenaar (artiest-zelfbeheer),
67 // én een kijker (mag het Beheer alleen-lezen inzien). Eén bron van waarheid,
68 // gespiegeld in topnav/hub-nav/profielsheet — anders raakt de link verborgen
69 // voor wie 'm wél mag zien (kijker zag 'm eerst nergens).
70 const _role = _u ? _u.role : null;
71 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
72
[7bc636b]73 // Common locals
74 const locals = {
[8cb1dc7]75 user: _u,
76 userOwnsSite,
[a3169f5]77 canSeeBeheer,
[8afbdd6]78 isViewer: _isViewer,
79 canMutate: !_isViewer,
[1b4d5dd]80 isPremium: isPremiumInstance(),
81 premiumEnabled: premiumEnabled(),
[8aa85d0]82 premiumUnlocked: premiumUnlocked(),
[ab544fd]83 siteOwnerAvatar,
84 site: _site,
[7bc636b]85 audioTracks: data.audioTracks || res.locals.audioTracks || [],
86 siteUrlBase: res.locals.siteUrlBase || '',
[2cc887b]87 tenancy: res.locals.tenancy || 'solo',
[42081fb]88 hubTitle: getSetting('hub_title') || '',
[7bc636b]89 platforms_catalog: PLATFORMS_CATALOG,
90 permissions: PermissionsService,
91 formatDate,
92 formatDateTime,
[83faa57]93 pageTitle: data.pageTitle || (data.site && data.site.title) || 'Klonkt Beta',
94 appVersion: APP_VERSION,
[7bc636b]95 bodyClass: data.bodyClass || 'on-home',
96 socialDescr: data.socialDescr || '',
97 socialImage: data.socialImage || '',
98 cspNonce: () => '',
99 currentPath: req.path,
100 ...data,
101 };
102
103 try {
104 // Step 1: Render the page view to HTML
105 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
106 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
107
108 if (isPartial) {
[00d54bc]109 // HTMX: just send the content. Set HX-Trigger for body class swap.
110 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
111 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
112 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
113 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
114 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
[a3e2f17]115 // Per-site accent + palette zitten in de shell-<head> (style#pcms-site-accent
116 // + html[data-palette]) en worden NIET mee-geswapt bij htmx-nav. Stuur ze mee
117 // zodat de client ze bijwerkt — anders erft een artiest de kleuren van de
118 // vorige pagina (bv. hub-paars i.p.v. eigen groen). Zelfde afleiding als shell.ejs.
119 const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
120 ? _site.accent : '#c2410c';
121 const _navPalette = (_site && _site.palette) ? _site.palette : 'sage';
[00d54bc]122 const triggerJson = JSON.stringify({
[a3e2f17]123 pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
[7bc636b]124 pcmsPostSwap: data.post ? {
125 title: data.post.title,
126 slug: data.post.slug,
127 pageTitle: locals.pageTitle,
128 } : null,
[00d54bc]129 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
130 res.setHeader('HX-Trigger-After-Settle', triggerJson);
[3cd1aaa]131 // Site-chrome out-of-band mee-renderen, zodat de kop (topnav/profielkop/
132 // view-switcher) bij navigatie ALTIJD bij de nieuwe pagina/artiest hoort —
133 // terwijl de audioplayer (los in document.body) blijft leven (geen
134 // verspringen). htmx vervangt #pcms-chrome via hx-swap-oob. Niet kritisch:
135 // faalt 't, dan blijft de oude chrome staan (geen crash).
136 let oobChrome = '';
137 try {
138 oobChrome = await ejs.renderFile(
139 path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
140 { ...locals, oob: true },
141 { async: false },
142 );
143 } catch (e) { /* chrome-OOB overslaan */ }
144 return res.send(pageContent + oobChrome);
[7bc636b]145 }
146
147 // Full: wrap content in shell
148 locals.pageContent = pageContent;
149 res.render('shell', locals);
150 } catch (err) {
151 console.error('[renderPage] Error rendering', viewName, err);
152 if (process.env.NODE_ENV === 'production') {
153 return res.status(500).send('Internal Server Error');
154 }
155 // Dev: surface the underlying cause prominently. EJS rewrites err.message
156 // to include the file/line/code-context, so we also surface name+stack
157 // separately in case the message was truncated or empty.
158 const escape = (s) => String(s == null ? '' : s)
159 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
160 res.status(500).send(`<!doctype html>
161<meta charset="utf-8">
162<title>Render error: ${escape(viewName)}</title>
163<style>
164 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
165 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
166 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
167 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
168 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
169</style>
170<h1>Render error in ${escape(viewName)}</h1>
171<h2>Cause</h2>
172<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
173<h2>Stack</h2>
174<pre>${escape(err.stack || '(no stack)')}</pre>
175${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
176`);
177 }
178}
Note: See TracBrowser for help on using the repository browser.