source: Klonkt/src/middleware/render.js@ 2708282

main
Last change on this file since 2708282 was 42e7616, checked in by Robin Genis <roboburr@…>, 6 weeks ago

Fix: load-more toont ineens de Klonkt-header (chrome-swap bij append)

Op Messages (en ook News/Cirkel) verscheen na "Load more" + omhoog scrollen de
volledige Klonkt-header. Oorzaak: renderPage behandelde de load-more-append als
een HTMX-NAVIGATIE en stuurde de HX-Trigger pcmsNav (met bodyClass) + de
out-of-band chrome mee. De append-render geeft geen bodyClass mee, dus die viel
terug op de default 'on-home'; de pcmsNav-listener in shell.ejs stript dan
'on-special' en de OOB-chrome herbouwt de header voor de home-variant → de
verborgen header komt tevoorschijn.

Een load-more voegt alleen rijen toe aan de bestaande pagina; dat is geen
navigatie. renderPage stuurt voor een append (req.query.append === '1') nu enkel
de content, zonder de nav-HX-Trigger en zonder de OOB-chrome. De OOB load-more-
knop zit in de content zelf en blijft dus gewoon werken.

Changed files:
src/middleware/render.js

  • isPartial + append=1 -> alleen content sturen (geen pcmsNav-trigger/OOB-chrome)

remarks: 187 tests groen. Dekt messages, news en cirkel load-more. Bug zit achter
login, dus niet live in een preview te reproduceren; diagnose via de code
bevestigd (pcmsNav-listener shell.ejs + on-special + ontbrekende bodyClass).

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 15.4 KB
Line 
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
12import fs from 'fs';
13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
16import db from '../config/database.js';
17import PermissionsService from '../services/PermissionsService.js';
18import { isViewer } from './auth.js';
19import { getSetting, apEnabled } from '../services/SettingsService.js';
20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
21import { emojiHtml, emojiName, parseQuote } from '../services/NoteRender.js';
22import ActivityPubService from '../services/ActivityPubService.js';
23import { imgProxyUrl } from '../services/ThumbnailService.js';
24import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
25
26// Add the per-request CSP nonce to every <script> tag that doesn't already have one, so the
27// strict script-src (nonce + 'strict-dynamic') allows them — including scripts in htmx
28// partials. HTML-escaped "&lt;script" in rendered content (e.g. sanitized post bodies) won't
29// match, so this only touches real tags.
30export function injectCspNonce(html, nonce) {
31 if (!html || !nonce) return html;
32 return String(html).replace(/<script(?![^>]*\snonce=)/gi, () => `<script nonce="${nonce}"`);
33}
34import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
35import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
36
37const __dirname = path.dirname(fileURLToPath(import.meta.url));
38const VIEWS_DIR = path.join(__dirname, '..', 'views');
39
40// App version (from package.json) + short commit hash (from .klonkt-version, written by
41// the deploy script) — shown in the footer next to "Klonkt Beta". The hash is updated
42// automatically on every deploy, so the displayed version is never stale.
43let APP_VERSION = '';
44try {
45 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
46 try {
47 const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
48 if (sha) APP_VERSION += ' · ' + sha;
49 } catch { /* no .klonkt-version (local dev) */ }
50} catch { /* no version available */ }
51
52// Site timezone (Admin → Settings). Empty = server default (UTC). Applied to
53// all server-side formatted dates so they display in the site's timezone instead of UTC.
54const siteTimezone = () => getSetting('timezone') || undefined;
55
56const formatDate = (iso) => {
57 if (!iso) return '';
58 return new Date(iso).toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' });
59};
60
61const formatDateTime = (iso) => {
62 if (!iso) return '';
63 return new Date(iso).toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' });
64};
65
66export async function renderPage(req, res, viewName, data = {}) {
67 // Decide: partial (HTMX) or full?
68 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
69
70 // Prevent the browser from caching an htmx PARTIAL (only #pcms-main, without <head>/CSS)
71 // under the same URL and serving it as a full page on "back" → unstyled HTML.
72 // Vary: HX-Request separates partial and full responses in the cache;
73 // no-store on the partial forces "back" to always re-fetch the full page.
74 // (Vary also applies to intermediate caches / Cloudflare.)
75 res.setHeader('Vary', 'HX-Request');
76 // A full HTML page must always be revalidated so an online visitor gets the
77 // fresh site, never a heuristically-cached copy. no-cache (not no-store) still
78 // allows bfcache and conditional requests. Partials stay no-store (see above).
79 res.setHeader('Cache-Control', isPartial ? 'no-store' : 'no-cache');
80
81 // Does this (non-god) user own a site? Determines whether they see an "Admin"
82 // entry (artist self-manage). god always sees admin (by role).
83 let _u = req.session?.user || null;
84 // Refresh avatar + role from the DB so a stale session (e.g. after an
85 // avatar change or role switch) heals itself without a new login.
86 if (_u && _u.id) {
87 const _fresh = db.prepare('SELECT role, lang FROM users WHERE id = ?').get(_u.id);
88 if (_fresh) _u = { ..._u, role: _fresh.role, lang: _fresh.lang };
89 // ONE image: a user's avatar everywhere (nav, account, comments) is simply their SITE
90 // photo — there is no separate account avatar. Falls back to the initial-letter
91 // placeholder when the site has no photo yet.
92 const _sp = db.prepare("SELECT profile_photo FROM sites WHERE owner_id = ? AND profile_photo IS NOT NULL ORDER BY is_primary DESC, created_at ASC LIMIT 1").get(_u.id);
93 _u = { ..._u, avatar_url: (_sp && _sp.profile_photo) || null };
94 }
95 const userOwnsSite = !!(_u && _u.role !== 'god' &&
96 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
97
98 const _site = data.site || res.locals.site || null;
99 // The site header uses the SITE photo (site.profile_photo) — the one and only image,
100 // set in site settings. (No separate account-avatar fallback anymore.)
101 const siteOwnerAvatar = null;
102
103 // Viewer mode: may view everything, change nothing. Views use canMutate
104 // to hide/disable write buttons (post, save, delete).
105 const _isViewer = isViewer(_u);
106
107 // Embeds are framed broadly (frame-src https: globally), EXCEPT on authorize_interaction:
108 // that page renders untrusted remote content next to the interact buttons, so lock its
109 // frame-src down to 'self' (no embeds → no clickjacking/overlay over the buttons).
110 if (viewName === 'pages/authorize-interaction') {
111 try {
112 const csp = res.getHeader('Content-Security-Policy');
113 if (csp) res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src [^;]*/i, "frame-src 'self'"));
114 } catch { /* best-effort */ }
115 }
116
117 // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
118 // and a viewer (may view Admin read-only). One source of truth,
119 // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
120 // for those who should see it (viewer didn't see it anywhere before).
121 const _role = _u ? _u.role : null;
122 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
123 // Who may use the fediverse client (timeline/notifications/blocking) — actual
124 // site managers only (these routes are requireSiteManager; viewers are excluded).
125 const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
126
127 // Interface language: session choice (this session) → logged-in user's own preference
128 // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
129 const _lang = resolveLang(req, {
130 userLang: _u && _u.lang,
131 defaultLang: getSetting('default_lang'),
132 });
133
134 // Common locals
135 const locals = {
136 user: _u,
137 lang: _lang,
138 t: (key, vars) => i18nT(_lang, key, vars),
139 langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
140 timezone: getSetting('timezone') || '',
141 notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
142 userOwnsSite,
143 canSeeBeheer,
144 canManageFedi,
145 apEnabled: apEnabled(),
146 // Cirkel = the artists you feature (auto-boost). Shown when AP is on and you
147 // auto-boost ≥1 account, or (legacy) on a circle-tenancy site.
148 hasCirkel: !!(_site && apEnabled() && (ActivityPubService.autoBoostCount(_site.slug) > 0 || ActivityPubService.boostedCount(_site.slug) > 0)),
149 isViewer: _isViewer,
150 canMutate: !_isViewer,
151 isPremium: isPremiumInstance(),
152 premiumEnabled: premiumEnabled(),
153 premiumUnlocked: premiumUnlocked(),
154 siteOwnerAvatar,
155 site: _site,
156 audioEnabled: audioFeatureEnabled(),
157 audioTracks: data.audioTracks || res.locals.audioTracks || [],
158 siteUrlBase: res.locals.siteUrlBase || '',
159 tenancy: res.locals.tenancy || 'solo',
160 hubTitle: getSetting('hub_title') || '',
161 footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
162 agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
163 platforms_catalog: PLATFORMS_CATALOG,
164 permissions: PermissionsService,
165 formatDate,
166 formatDateTime,
167 // Render the Shaer-native bits server-side so the web timeline matches the
168 // apps: FEP-9098 custom emojis in content/names, and the FEP-044f quote.
169 emojiHtml, // (html, emoji_json) → HTML with :shortcode: as <img>
170 emojiName, // (text, emoji_json) → escaped name with :shortcode: as <img>
171 noteQuote: parseQuote, // (quote_json) → the resolved quoted-post object or null
172 // Rewrite a local /media/<file> cover to its on-demand downscaled thumbnail
173 // (crisp grid/list images). External URLs + already-thumb URLs pass through.
174 thumb: (url, w) => {
175 if (!url || typeof url !== 'string') return url;
176 // Local cover → local thumb route; remote (federated) cover → signed downscale
177 // proxy (same as avatars), so remote line-art covers aren't browser-downscaled jagged.
178 if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 480}/${url.slice(7)}`;
179 if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 480);
180 return url;
181 },
182 // Crisp avatars: a local /media avatar goes through the local thumb route; a REMOTE
183 // (fediverse) avatar through the signed downscaling proxy. Same downscale, the remote
184 // one is just fetched first. Default 128px (covers feed 44px → profile ~120px).
185 avatar: (url, w) => {
186 if (!url || typeof url !== 'string') return url;
187 if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 128}/${url.slice(7)}`;
188 if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 128);
189 return url;
190 },
191 // pageTitleKey (translated with the resolved language) wins over a raw pageTitle string,
192 // so admin page titles aren't hardcoded in one language. Falls back to the site title.
193 pageTitle: (data.pageTitleKey ? i18nT(_lang, data.pageTitleKey, data.pageTitleVars) : data.pageTitle)
194 || (data.site && data.site.title) || 'Klonkt',
195 appVersion: APP_VERSION,
196 bodyClass: data.bodyClass || 'on-home',
197 socialDescr: data.socialDescr || '',
198 socialImage: data.socialImage || '',
199 cspNonce: () => '',
200 currentPath: req.path,
201 // Absolute origin (for building absolute URLs like the generated og:image).
202 ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
203 ...data,
204 };
205
206 try {
207 // Step 1: Render the page view to HTML
208 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
209 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
210
211 if (isPartial) {
212 // A "Load more" append (hx-swap=beforeend into a sub-list) is NOT a
213 // navigation: it only adds rows to the existing page. It must NOT touch
214 // the site chrome or the body class. Emitting the nav HX-Trigger + OOB
215 // chrome here (below) rebuilds the header for the DEFAULT bodyClass —
216 // which, on a 'on-special' page like Messages, swaps in the full Klonkt
217 // header that the page had hidden. So for an append, send content only.
218 if (req.query.append === '1') {
219 return res.send(injectCspNonce(pageContent, res.locals.cspNonce));
220 }
221 // HTMX: just send the content. Set HX-Trigger for body class swap.
222 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
223 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
224 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
225 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
226 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
227 // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
228 // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
229 // so the client updates them — otherwise an artist inherits the previous page's
230 // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
231 const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
232 ? _site.accent : '#e8b04b';
233 const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
234 const triggerJson = JSON.stringify({
235 pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
236 pcmsPostSwap: data.post ? {
237 title: data.post.title,
238 slug: data.post.slug,
239 pageTitle: locals.pageTitle,
240 } : null,
241 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
242 res.setHeader('HX-Trigger-After-Settle', triggerJson);
243 // Render the site chrome out-of-band so the header (topnav/profile header/
244 // view-switcher) ALWAYS matches the new page/artist on navigation —
245 // while the audio player (separate in document.body) keeps playing (no
246 // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
247 // if it fails, the old chrome remains (no crash).
248 let oobChrome = '';
249 try {
250 oobChrome = await ejs.renderFile(
251 path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
252 { ...locals, oob: true },
253 { async: false },
254 );
255 } catch (e) { /* skip chrome OOB */ }
256 return res.send(injectCspNonce(pageContent + oobChrome, res.locals.cspNonce));
257 }
258
259 // Full: wrap content in shell (rendered to a string so we can inject the CSP nonce).
260 locals.pageContent = pageContent;
261 const shellHtml = await ejs.renderFile(path.join(VIEWS_DIR, 'shell.ejs'), locals, { async: false });
262 res.send(injectCspNonce(shellHtml, res.locals.cspNonce));
263 } catch (err) {
264 console.error('[renderPage] Error rendering', viewName, err);
265 if (process.env.NODE_ENV === 'production') {
266 return res.status(500).send('Internal Server Error');
267 }
268 // Dev: surface the underlying cause prominently. EJS rewrites err.message
269 // to include the file/line/code-context, so we also surface name+stack
270 // separately in case the message was truncated or empty.
271 const escape = (s) => String(s == null ? '' : s)
272 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
273 res.status(500).send(`<!doctype html>
274<meta charset="utf-8">
275<title>Render error: ${escape(viewName)}</title>
276<style>
277 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
278 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
279 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
280 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
281 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
282</style>
283<h1>Render error in ${escape(viewName)}</h1>
284<h2>Cause</h2>
285<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
286<h2>Stack</h2>
287<pre>${escape(err.stack || '(no stack)')}</pre>
288${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
289`);
290 }
291}
Note: See TracBrowser for help on using the repository browser.