source: Klonkt/src/services/OgImageService.js@ 5f483e3

main
Last change on this file since 5f483e3 was 69815b2, checked in by Robin Genis <roboburr@…>, 3 months ago

feat: auto-generated per-site OG image from palette + accent

New OgImageService renders a themed 1200x630 social card (palette gradient +
accent + site title/tagline + klonkt wordmark) via @resvg/resvg-js, cached on
disk. Served at GET /og/:slug.png and used as the default og:image/twitter:image
when a site has no custom share image — so every site gets a branded preview.
Bundles a static Fraunces TTF for rendering; graceful no-op if resvg can't load.

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

  • Property mode set to 100644
File size: 4.9 KB
RevLine 
[69815b2]1/**
2 * OgImageService — generates a themed Open Graph card (1200x630 PNG) per site,
3 * derived from the site's palette + accent, so every site has a branded social
4 * preview even without uploading one. SVG is hand-built and rasterized with
5 * @resvg/resvg-js. Result is cached on disk (keyed by the theming inputs).
6 *
7 * Graceful: if @resvg/resvg-js can't load (exotic platform), ogImageFor()
8 * returns null and the caller falls back to no/other og:image — never throws.
9 */
10import fs from 'fs';
11import path from 'path';
12import crypto from 'crypto';
13import { fileURLToPath } from 'url';
14import { createRequire } from 'module';
15import ThemeService from './ThemeService.js';
16
17const require = createRequire(import.meta.url);
18const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
20const FONT = path.join(__dirname, '..', 'assets', 'fonts', 'fraunces-og.ttf');
21const DATA_DIR = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
22const CACHE_DIR = path.join(DATA_DIR, 'og');
23const TEMPLATE_VERSION = 1; // bump to invalidate all cached cards after a design change
24
25let _Resvg = null, _tried = false;
26function getResvg() {
27 if (_tried) return _Resvg;
28 _tried = true;
29 try { _Resvg = require('@resvg/resvg-js').Resvg; } catch { _Resvg = null; }
30 return _Resvg;
31}
32
33// ── tiny colour helpers ───────────────────────────────────────────
34function hx(h) {
35 h = String(h || '').replace('#', '');
36 if (h.length === 3) h = h.split('').map((c) => c + c).join('');
37 return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16) || 0);
38}
39function rgb(a) {
40 return '#' + a.map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
41}
42function mix(a, b, t) { const A = hx(a), B = hx(b); return rgb(A.map((v, i) => v + (B[i] - v) * t)); }
43function esc(s) { return String(s == null ? '' : s).replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c])); }
44
45function buildSvg(site, palette, accent) {
46 const pal = (ThemeService.PALETTES[palette] || ThemeService.PALETTES.klonkt).dark;
47 const paper = pal.paper, ink = pal.ink;
48 const paper2 = mix(paper, ink, 0.08);
49 const muted = mix(ink, paper, 0.42);
50
51 let title = (site.title || 'Klonkt').trim();
52 let tag = (site.tagline || site.description || '').trim();
53 if (title.length > 38) title = title.slice(0, 37) + '…';
54 if (tag.length > 74) tag = tag.slice(0, 73) + '…';
55 const tsize = title.length <= 12 ? 100 : title.length <= 20 ? 82 : title.length <= 30 ? 64 : 54;
56
57 return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630">
58 <defs>
59 <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
60 <stop offset="0" stop-color="${paper}"/><stop offset="1" stop-color="${paper2}"/>
61 </linearGradient>
62 <radialGradient id="glow" cx="0.85" cy="0.12" r="0.7">
63 <stop offset="0" stop-color="${accent}" stop-opacity="0.20"/>
64 <stop offset="1" stop-color="${accent}" stop-opacity="0"/>
65 </radialGradient>
66 </defs>
67 <rect width="1200" height="630" fill="url(#bg)"/>
68 <rect width="1200" height="630" fill="url(#glow)"/>
69 <rect x="0" y="0" width="14" height="630" fill="${accent}"/>
70 <g transform="translate(96,232)">
71 <rect x="0" y="14" width="11" height="34" rx="3" fill="${accent}"/>
72 <rect x="18" y="0" width="11" height="48" rx="3" fill="${accent}"/>
73 <rect x="36" y="22" width="11" height="26" rx="3" fill="${accent}"/>
74 <rect x="54" y="8" width="11" height="40" rx="3" fill="${accent}"/>
75 </g>
76 <text x="96" y="400" font-size="${tsize}" fill="${ink}">${esc(title)}</text>
77 ${tag ? `<text x="98" y="462" font-size="34" fill="${muted}">${esc(tag)}</text>` : ''}
78 <text x="96" y="566" font-size="30" fill="${accent}">klonkt</text>
79</svg>`;
80}
81
82/**
83 * Returns a PNG Buffer of the site's OG card (cached), or null if generation
84 * isn't possible. `site` needs: slug, title, palette, accent, tagline/description.
85 */
86export function ogImageFor(site) {
87 const Resvg = getResvg();
88 if (!Resvg || !site || !site.slug) return null;
89
90 const palette = ThemeService.PALETTES[site.palette] ? site.palette : 'klonkt';
91 const accent = site.accent || (ThemeService.PALETTES[palette] || ThemeService.PALETTES.klonkt).dark.accent;
92 const key = crypto.createHash('sha1')
93 .update([TEMPLATE_VERSION, site.slug, palette, accent, site.title || '', site.tagline || site.description || ''].join('\x1f'))
94 .digest('hex').slice(0, 16);
95 const file = path.join(CACHE_DIR, key + '.png');
96
97 try { return fs.readFileSync(file); } catch { /* not cached yet */ }
98
99 try {
100 const svg = buildSvg(site, palette, accent);
101 const png = new Resvg(svg, {
102 font: { fontFiles: [FONT], loadSystemFonts: false },
103 fitTo: { mode: 'width', value: 1200 },
104 }).render().asPng();
105 try { fs.mkdirSync(CACHE_DIR, { recursive: true }); fs.writeFileSync(file, png); } catch { /* cache best-effort */ }
106 return png;
107 } catch {
108 return null;
109 }
110}
111
112export default { ogImageFor };
Note: See TracBrowser for help on using the repository browser.