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

main
Last change on this file since b94c08e was 42081fb, checked in by roboburr <roboburr@…>, 3 months ago

hub: home button on user sites — masthead brand becomes the hub name -> hub home

On /user/<artist> pages the masthead now shows the HUB name (hub_title)
top-left, linking to the hub home (/) — a clear home button. The artist
name remains in the profile header below. Not on the overview (the name
is already in the hero there). hubTitle comes from render.js (getSetting).

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 4.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
12import path from 'path';
13import { fileURLToPath } from 'url';
14import ejs from 'ejs';
[8cb1dc7]15import db from '../config/database.js';
[7bc636b]16import PermissionsService from '../services/PermissionsService.js';
[42081fb]17import { getSetting } from '../services/SettingsService.js';
[7bc636b]18import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
19
20const __dirname = path.dirname(fileURLToPath(import.meta.url));
21const VIEWS_DIR = path.join(__dirname, '..', 'views');
22
23const formatDate = (iso) => {
24 if (!iso) return '';
25 const d = new Date(iso);
26 const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
27 return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
28};
29
30const formatDateTime = (iso) => {
31 if (!iso) return '';
32 const d = new Date(iso);
33 return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
34};
35
36export async function renderPage(req, res, viewName, data = {}) {
37 // Decide: partial (HTMX) or full?
38 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
39
[8cb1dc7]40 // Bezit deze (niet-god) user een eigen site? Bepaalt of 'ie een "Beheer"-
41 // ingang ziet (artiest-zelfbeheer). god ziet beheer sowieso (op rol).
42 const _u = req.session?.user || null;
43 const userOwnsSite = !!(_u && _u.role !== 'god' &&
44 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
45
[ab544fd]46 // De avatar van de SITE-EIGENAAR (niet de kijker!) — voor de PrutFolio-kop,
47 // zodat de artiest z'n eigen account-foto als sitefoto kan gebruiken.
48 const _site = data.site || res.locals.site || null;
49 const siteOwnerAvatar = (_site && _site.owner_id)
50 ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
51 : null;
52
[7bc636b]53 // Common locals
54 const locals = {
[8cb1dc7]55 user: _u,
56 userOwnsSite,
[ab544fd]57 siteOwnerAvatar,
58 site: _site,
[7bc636b]59 audioTracks: data.audioTracks || res.locals.audioTracks || [],
60 siteUrlBase: res.locals.siteUrlBase || '',
[2cc887b]61 tenancy: res.locals.tenancy || 'solo',
[42081fb]62 hubTitle: getSetting('hub_title') || '',
[7bc636b]63 platforms_catalog: PLATFORMS_CATALOG,
64 permissions: PermissionsService,
65 formatDate,
66 formatDateTime,
67 pageTitle: data.pageTitle || (data.site && data.site.title) || 'PrutCMS',
68 bodyClass: data.bodyClass || 'on-home',
69 socialDescr: data.socialDescr || '',
70 socialImage: data.socialImage || '',
71 cspNonce: () => '',
72 currentPath: req.path,
73 ...data,
74 };
75
76 try {
77 // Step 1: Render the page view to HTML
78 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
79 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
80
81 if (isPartial) {
82 // HTMX: just send the content. Set HX-Trigger for body class swap
83 res.setHeader('HX-Trigger-After-Settle', JSON.stringify({
84 pcmsNav: { bodyClass: locals.bodyClass },
85 pcmsPostSwap: data.post ? {
86 title: data.post.title,
87 slug: data.post.slug,
88 pageTitle: locals.pageTitle,
89 } : null,
90 }));
91 return res.send(pageContent);
92 }
93
94 // Full: wrap content in shell
95 locals.pageContent = pageContent;
96 res.render('shell', locals);
97 } catch (err) {
98 console.error('[renderPage] Error rendering', viewName, err);
99 if (process.env.NODE_ENV === 'production') {
100 return res.status(500).send('Internal Server Error');
101 }
102 // Dev: surface the underlying cause prominently. EJS rewrites err.message
103 // to include the file/line/code-context, so we also surface name+stack
104 // separately in case the message was truncated or empty.
105 const escape = (s) => String(s == null ? '' : s)
106 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
107 res.status(500).send(`<!doctype html>
108<meta charset="utf-8">
109<title>Render error: ${escape(viewName)}</title>
110<style>
111 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
112 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
113 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
114 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
115 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
116</style>
117<h1>Render error in ${escape(viewName)}</h1>
118<h2>Cause</h2>
119<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
120<h2>Stack</h2>
121<pre>${escape(err.stack || '(no stack)')}</pre>
122${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
123`);
124 }
125}
Note: See TracBrowser for help on using the repository browser.