Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

generate-og-image.ts

631 lines18.3 KB

1#!/usr/bin/env npx tsx
2/**
3 * Generate OpenGraph social media card image.
4 *
5 * Usage:
6 * npx tsx scripts/generate-og-image.ts
7 *
8 * Output:
9 * public/og-image.png (1200x630)
10 *
11 * Creates an epic hand-drawn style card with a large grid bleeding off all edges,
12 * colored edges matching the game style, and proper box completion rules.
13 */
14​
15import { mkdir, readFile, writeFile } from "node:fs/promises"
16import { existsSync } from "node:fs"
17import { execSync } from "node:child_process"
18import { dirname, join } from "node:path"
19import { fileURLToPath } from "node:url"
20import { Resvg } from "@resvg/resvg-js"
21import satori from "satori"
22​
23const __dirname = dirname(fileURLToPath(import.meta.url))
24const ROOT = join(__dirname, `..`)
25​
26// Image dimensions (OpenGraph standard)
27const WIDTH = 1200
28const HEIGHT = 630
29​
30// Team colors from shared/teams.ts
31const TEAM_COLORS = {
32 RED: `#E53935`,
33 BLUE: `#1E88E5`,
34 GREEN: `#43A047`,
35 YELLOW: `#FDD835`,
36} as const
37​
38type TeamColor = keyof typeof TEAM_COLORS
39​
40// Grid styling
41const DOT_COLOR = `#5a5a4a`
42const GRID_LINE_COLOR = `#d0d0c0` // Light gray for unplaced edges
43const BG_COLOR = `#f5f5dc`
44const MUTED_COLOR = `#6b6b5a`
45​
46// Large grid layout - extends beyond visible area on all sides
47const GRID_COLS = 14 // Extra columns to bleed left/right
48const GRID_ROWS = 12 // Extra rows to bleed top/bottom
49const CELL_SIZE = 70
50const DOT_SIZE = 10
51const LINE_WIDTH = 4
52​
53// Position the grid - starts off-screen to bleed edges
54const GRID_LEFT = -120
55const GRID_TOP = -100 // Start above visible area
56​
57// Seeded random for consistent "hand-drawn" look
58function seededRandom(seed: number): number {
59 seed = (seed * 1103515245 + 12345) & 0x7fffffff
60 return (seed / 0x7fffffff) * 2 - 1 // -1 to 1
62​
63function seededRandom2(seed: number): number {
64 return seededRandom(seed * 127 + 31)
66​
67// Edge key helpers
68function hEdgeKey(row: number, col: number): string {
69 return `h-${row}-${col}`
71​
72function vEdgeKey(row: number, col: number): string {
73 return `v-${row}-${col}`
75​
76// Generate a proper game state following the rules:
77// - Edges are placed by teams
78// - A box is only filled when all 4 edges exist
79// - The box color is the team that placed the 4th (completing) edge
80function generateGameState(): {
81 edges: Map<string, TeamColor>
82 filledBoxes: Map<string, TeamColor>
83} {
84 const edges = new Map<string, TeamColor>()
85 const teams: Array<TeamColor> = [`RED`, `BLUE`, `GREEN`, `YELLOW`]
86​
87 // Place edges with probability decreasing from left to right
88 // This simulates a game where left side is more complete
89​
90 // Horizontal edges - higher probability for more complete boxes
91 for (let row = 0; row <= GRID_ROWS; row++) {
92 for (let col = 0; col < GRID_COLS; col++) {
93 const seed = row * 1000 + col + 100
94 const rand = (seededRandom(seed) + 1) / 2
95​
96 // Probability decreases from left to right, but higher overall
97 const probability = Math.max(0.08, 1.0 - (col / GRID_COLS) * 0.92)
98​
99 if (rand < probability) {
100 const teamIndex = Math.floor(((seededRandom(seed * 7 + 13) + 1) / 2) * 4)
101 edges.set(hEdgeKey(row, col), teams[teamIndex])
102 }
103 }
104 }
105​
106 // Vertical edges - higher probability for more complete boxes
107 for (let row = 0; row < GRID_ROWS; row++) {
108 for (let col = 0; col <= GRID_COLS; col++) {
109 const seed = row * 1000 + col + 50000
110 const rand = (seededRandom(seed) + 1) / 2
111​
112 const probability = Math.max(0.08, 1.0 - (col / GRID_COLS) * 0.92)
113​
114 if (rand < probability) {
115 const teamIndex = Math.floor(((seededRandom(seed * 11 + 17) + 1) / 2) * 4)
116 edges.set(vEdgeKey(row, col), teams[teamIndex])
117 }
118 }
119 }
120​
121 // Now determine which boxes are complete (have all 4 edges)
122 // The box color is determined by which edge was placed "last"
123 // We'll simulate this by picking the edge with the highest seed-based "timestamp"
124 const filledBoxes = new Map<string, TeamColor>()
125​
126 for (let row = 0; row < GRID_ROWS; row++) {
127 for (let col = 0; col < GRID_COLS; col++) {
128 const topEdge = edges.get(hEdgeKey(row, col))
129 const bottomEdge = edges.get(hEdgeKey(row + 1, col))
130 const leftEdge = edges.get(vEdgeKey(row, col))
131 const rightEdge = edges.get(vEdgeKey(row, col + 1))
132​
133 // Only fill if ALL 4 edges exist
134 if (topEdge && bottomEdge && leftEdge && rightEdge) {
135 // Determine which edge was "last" (completing edge) using seeded random
136 const boxSeed = row * 1000 + col + 200000
137 const edgeOptions = [topEdge, bottomEdge, leftEdge, rightEdge]
138 const lastEdgeIndex = Math.floor(((seededRandom(boxSeed) + 1) / 2) * 4)
139 const completingTeam = edgeOptions[lastEdgeIndex]
140​
141 filledBoxes.set(`box-${row}-${col}`, completingTeam)
142 }
143 }
144 }
145​
146 return { edges, filledBoxes }
148​
149// Create a wobbly SVG path for a line
150function createWobblyLinePath(
151 x1: number,
152 y1: number,
153 x2: number,
154 y2: number,
155 seed: number,
156): string {
157 const wobble = 2.5
158​
159 const dx = x2 - x1
160 const dy = y2 - y1
161 const length = Math.sqrt(dx * dx + dy * dy)
162​
163 if (length < 0.001) return ``
164​
165 const r1 = seededRandom(seed)
166 const r2 = seededRandom2(seed)
167 const r3 = seededRandom(seed + 1000)
168 const r4 = seededRandom2(seed + 1000)
169​
170 // Perpendicular direction for wobble
171 const px = -dy / length
172 const py = dx / length
173​
174 const startX = x1 + r1 * 0.8
175 const startY = y1 + r2 * 0.8
176 const midX = (x1 + x2) / 2 + px * wobble * r1
177 const midY = (y1 + y2) / 2 + py * wobble * r2
178 const endX = x2 + r3 * 0.8
179 const endY = y2 + r4 * 0.8
180​
181 return `M ${startX} ${startY} Q ${midX} ${midY} ${endX} ${endY}`
183​
184// Build the React-like element tree for Satori
185async function buildImage() {
186 const children: Array<{ type: string; props: Record<string, unknown> }> = []
187 const { edges, filledBoxes } = generateGameState()
188​
189 // Create watercolor-style filled boxes (only for complete boxes)
190 let boxSeed = 42
191 for (const [boxKey, team] of filledBoxes) {
192 const match = boxKey.match(/box-(\d+)-(\d+)/)
193 if (!match) continue
194​
195 const row = parseInt(match[1])
196 const col = parseInt(match[2])
197​
198 const x = GRID_LEFT + col * CELL_SIZE + DOT_SIZE / 2
199 const y = GRID_TOP + row * CELL_SIZE + DOT_SIZE / 2
200 const size = CELL_SIZE - DOT_SIZE
201​
202 // Skip boxes that are completely off-screen
203 if (x + size < -50 || x > WIDTH + 50) continue
204 if (y + size < -50 || y > HEIGHT + 50) continue
205​
206 // Create 3 layered fills for watercolor effect
207 for (let layer = 0; layer < 3; layer++) {
208 const r1 = seededRandom(boxSeed + layer * 100)
209 const r2 = seededRandom2(boxSeed + layer * 100)
210 const inset = 3 + Math.abs(r1) * 2
211​
212 children.push({
213 type: `div`,
214 props: {
215 style: {
216 position: `absolute`,
217 left: x + inset + r1 * 1.5,
218 top: y + inset + r2 * 1.5,
219 width: size - inset * 2,
220 height: size - inset * 2,
221 backgroundColor: TEAM_COLORS[team],
222 opacity: 0.22 + Math.abs(r1) * 0.1,
223 borderRadius: 2 + Math.abs(r2) * 2,
224 } as React.CSSProperties,
225 },
226 })
227 }
228 boxSeed += 50
229 }
230​
231 // Build SVG paths for all edges grouped by color
232 const edgePathsByColor: Map<string, Array<string>> = new Map()
233 const gridPaths: Array<string> = []
234​
235 // Horizontal edges
236 for (let row = 0; row <= GRID_ROWS; row++) {
237 for (let col = 0; col < GRID_COLS; col++) {
238 const x1 = GRID_LEFT + col * CELL_SIZE + DOT_SIZE / 2
239 const y1 = GRID_TOP + row * CELL_SIZE + DOT_SIZE / 2
240 const x2 = x1 + CELL_SIZE - DOT_SIZE
241 const y2 = y1
242​
243 // Skip if completely off-screen
244 if (x2 < -50 || x1 > WIDTH + 50) continue
245 if (y1 < -50 || y1 > HEIGHT + 50) continue
246​
247 const edgeKey = hEdgeKey(row, col)
248 const edgeSeed = row * 1000 + col
249 const path = createWobblyLinePath(x1, y1, x2, y2, edgeSeed)
250​
251 const edgeColor = edges.get(edgeKey)
252 if (edgeColor) {
253 const color = TEAM_COLORS[edgeColor]
254 if (!edgePathsByColor.has(color)) {
255 edgePathsByColor.set(color, [])
256 }
257 edgePathsByColor.get(color)!.push(path)
258 } else {
259 gridPaths.push(path)
260 }
261 }
262 }
263​
264 // Vertical edges
265 for (let row = 0; row < GRID_ROWS; row++) {
266 for (let col = 0; col <= GRID_COLS; col++) {
267 const x1 = GRID_LEFT + col * CELL_SIZE + DOT_SIZE / 2
268 const y1 = GRID_TOP + row * CELL_SIZE + DOT_SIZE / 2
269 const x2 = x1
270 const y2 = y1 + CELL_SIZE - DOT_SIZE
271​
272 // Skip if completely off-screen
273 if (x1 < -50 || x1 > WIDTH + 50) continue
274 if (y2 < -50 || y1 > HEIGHT + 50) continue
275​
276 const edgeKey = vEdgeKey(row, col)
277 const edgeSeed = row * 1000 + col + 50000
278 const path = createWobblyLinePath(x1, y1, x2, y2, edgeSeed)
279​
280 const edgeColor = edges.get(edgeKey)
281 if (edgeColor) {
282 const color = TEAM_COLORS[edgeColor]
283 if (!edgePathsByColor.has(color)) {
284 edgePathsByColor.set(color, [])
285 }
286 edgePathsByColor.get(color)!.push(path)
287 } else {
288 gridPaths.push(path)
289 }
290 }
291 }
292​
293 // Create SVG for grid lines (light gray, behind colored edges)
294 const gridSvg = `
295 <svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">
296 ${gridPaths.map((d) => `<path d="${d}" stroke="${GRID_LINE_COLOR}" stroke-width="${LINE_WIDTH * 0.8}" stroke-linecap="round" fill="none"/>`).join(``)}
297 </svg>
298 `
299​
300 children.push({
301 type: `img`,
302 props: {
303 src: `data:image/svg+xml,${encodeURIComponent(gridSvg)}`,
304 style: {
305 position: `absolute`,
306 left: 0,
307 top: 0,
308 width: WIDTH,
309 height: HEIGHT,
310 } as React.CSSProperties,
311 },
312 })
313​
314 // Create SVG for colored edges (on top of grid)
315 const coloredEdgesSvgParts: Array<string> = []
316 for (const [color, paths] of edgePathsByColor) {
317 coloredEdgesSvgParts.push(
318 ...paths.map(
319 (d) =>
320 `<path d="${d}" stroke="${color}" stroke-width="${LINE_WIDTH * 1.1}" stroke-linecap="round" fill="none"/>`,
321 ),
322 )
323 }
324​
325 const coloredEdgesSvg = `
326 <svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">
327 ${coloredEdgesSvgParts.join(``)}
328 </svg>
329 `
330​
331 children.push({
332 type: `img`,
333 props: {
334 src: `data:image/svg+xml,${encodeURIComponent(coloredEdgesSvg)}`,
335 style: {
336 position: `absolute`,
337 left: 0,
338 top: 0,
339 width: WIDTH,
340 height: HEIGHT,
341 } as React.CSSProperties,
342 },
343 })
344​
345 // Add wobbly dots
346 let dotSeed = 5000
347 for (let row = 0; row <= GRID_ROWS; row++) {
348 for (let col = 0; col <= GRID_COLS; col++) {
349 const x = GRID_LEFT + col * CELL_SIZE + DOT_SIZE / 2
350 const y = GRID_TOP + row * CELL_SIZE + DOT_SIZE / 2
351​
352 // Skip if off-screen (with margin)
353 if (x < -DOT_SIZE * 2 || x > WIDTH + DOT_SIZE * 2) continue
354 if (y < -DOT_SIZE * 2 || y > HEIGHT + DOT_SIZE * 2) continue
355​
356 const r1 = seededRandom(dotSeed)
357 const r2 = seededRandom2(dotSeed)
358 const sizeVar = 1 + r1 * 0.12
359​
360 children.push({
361 type: `div`,
362 props: {
363 style: {
364 position: `absolute`,
365 left: x - (DOT_SIZE / 2) * sizeVar + r1 * 0.5,
366 top: y - (DOT_SIZE / 2) * sizeVar + r2 * 0.5,
367 width: DOT_SIZE * sizeVar,
368 height: DOT_SIZE * sizeVar,
369 backgroundColor: DOT_COLOR,
370 borderRadius: `50%`,
371 } as React.CSSProperties,
372 },
373 })
374 dotSeed += 7
375 }
376 }
377​
378 // Gradient fade overlay on the right side - use SVG for proper transparency
379 // Fade starts earlier (at x=350) to give more space for logo
380 const fadeSvg = `
381 <svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">
382 <defs>
383 <linearGradient id="fadeGrad" x1="0%" y1="0%" x2="100%" y2="0%">
384 <stop offset="0%" style="stop-color:${BG_COLOR};stop-opacity:0" />
385 <stop offset="40%" style="stop-color:${BG_COLOR};stop-opacity:1" />
386 <stop offset="100%" style="stop-color:${BG_COLOR};stop-opacity:1" />
387 </linearGradient>
388 </defs>
389 <rect x="350" y="0" width="850" height="${HEIGHT}" fill="url(#fadeGrad)" />
390 </svg>
391 `
392​
393 children.push({
394 type: `img`,
395 props: {
396 src: `data:image/svg+xml,${encodeURIComponent(fadeSvg)}`,
397 style: {
398 position: `absolute`,
399 left: 0,
400 top: 0,
401 width: WIDTH,
402 height: HEIGHT,
403 } as React.CSSProperties,
404 },
405 })
406​
407 // Load and embed the actual logo
408 const logoPath = join(ROOT, `public`, `logo.svg`)
409 const logoSvg = await readFile(logoPath, `utf-8`)
410 const logoDataUri = `data:image/svg+xml,${encodeURIComponent(logoSvg)}`
411​
412 // Main container
413 return {
414 type: `div`,
415 props: {
416 style: {
417 width: WIDTH,
418 height: HEIGHT,
419 backgroundColor: BG_COLOR,
420 display: `flex`,
421 position: `relative`,
422 overflow: `hidden`,
423 } as React.CSSProperties,
424 children: [
425 // Grid elements
426 ...children,
427​
428 // Background behind logo to cover transparent parts
429 {
430 type: `div`,
431 props: {
432 style: {
433 position: `absolute`,
434 right: 45,
435 top: 165,
436 width: 630,
437 height: 74,
438 backgroundColor: BG_COLOR,
439 borderRadius: 4,
440 } as React.CSSProperties,
441 },
442 },
443​
444 // Actual logo - positioned on right, bigger, nudged up slightly
445 {
446 type: `img`,
447 props: {
448 src: logoDataUri,
449 style: {
450 position: `absolute`,
451 right: 50,
452 top: 170,
453 width: 620,
454 height: 64,
455 } as React.CSSProperties,
456 },
457 },
458​
459 // Strapline under logo - right aligned
460 {
461 type: `div`,
462 props: {
463 style: {
464 position: `absolute`,
465 right: 50,
466 top: 260,
467 fontSize: 28,
468 fontWeight: 500,
469 color: MUTED_COLOR,
470 lineHeight: 1.5,
471 } as React.CSSProperties,
472 children: `The world's largest game of Dots and Boxes`,
473 },
474 },
475​
476 // Team color legend
477 {
478 type: `div`,
479 props: {
480 style: {
481 position: `absolute`,
482 right: 50,
483 top: 330,
484 display: `flex`,
485 gap: 14,
486 } as React.CSSProperties,
487 children: Object.entries(TEAM_COLORS).map(([, color], i) => ({
488 type: `div`,
489 props: {
490 style: {
491 width: 36,
492 height: 36,
493 backgroundColor: color,
494 opacity: 0.85,
495 borderRadius: 6,
496 transform: `rotate(${(i - 1.5) * 2}deg)`,
497 } as React.CSSProperties,
498 },
499 })),
500 },
501 },
502​
503 // Bottom tagline
504 {
505 type: `div`,
506 props: {
507 style: {
508 position: `absolute`,
509 right: 50,
510 bottom: 50,
511 fontSize: 22,
512 fontWeight: 400,
513 color: MUTED_COLOR,
514 textAlign: `right`,
515 } as React.CSSProperties,
516 children: `Complete the fourth edge. Claim the box.`,
517 },
518 },
519 ],
520 },
521 }
523​
524const INTER_VERSION = `v4.1`
525const INTER_ZIP_URL = `https://github.com/rsms/inter/releases/download/${INTER_VERSION}/Inter-4.1.zip`
526​
527async function downloadFonts(fontsDir: string): Promise<void> {
528 console.log(`📥 Downloading Inter fonts...`)
529 await mkdir(fontsDir, { recursive: true })
530 const zipPath = join(fontsDir, `Inter.zip`)
531 execSync(`curl -L -o "${zipPath}" "${INTER_ZIP_URL}"`, { stdio: `inherit` })
532 execSync(
533 `unzip -j "${zipPath}" "extras/ttf/Inter-Bold.ttf" "extras/ttf/Inter-Regular.ttf" -d "${fontsDir}"`,
534 { stdio: `inherit` },
535 )
536 execSync(`rm "${zipPath}"`)
537 console.log(` Fonts downloaded to ${fontsDir}`)
539​
540type FontWeight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
541​
542interface FontConfig {
543 name: string
544 data: ArrayBuffer
545 weight: FontWeight
546 style: `normal` | `italic`
548​
549async function loadFonts(): Promise<Array<FontConfig>> {
550 // Load fonts from public/fonts (shared with the web app)
551 const fontsDir = join(ROOT, `public`, `fonts`)
552 const fonts: Array<FontConfig> = []
553​
554 const fontFiles: Array<{ file: string; weight: FontWeight }> = [
555 { file: `Inter-Bold.ttf`, weight: 700 },
556 { file: `Inter-Regular.ttf`, weight: 400 },
557 ]
558​
559 const fontsExist = fontFiles.every(({ file }) => existsSync(join(fontsDir, file)))
560​
561 if (!fontsExist) {
562 await downloadFonts(fontsDir)
563 }
564​
565 for (const { file, weight } of fontFiles) {
566 const fontPath = join(fontsDir, file)
567 try {
568 const fontData = await readFile(fontPath)
569 fonts.push({
570 name: `Inter`,
571 data: fontData.buffer.slice(fontData.byteOffset, fontData.byteOffset + fontData.byteLength),
572 weight,
573 style: `normal`,
574 })
575 } catch {
576 console.log(`⚠️ Font not found: ${file}`)
577 }
578 }
579​
580 if (fonts.length === 0) {
581 throw new Error(`Failed to load fonts`)
582 }
583​
584 return fonts
586​
587async function main() {
588 console.log(`\n🎨 OG Image Generator`)
589 console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`)
590 console.log(`Output: public/og-image.png (${WIDTH}x${HEIGHT})`)
591 console.log(``)
592​
593 const element = await buildImage()
594​
595 const fonts = await loadFonts()
596 console.log(`📝 Loaded ${fonts.length} font(s)`)
597​
598 console.log(`📐 Generating SVG...`)
599 const svg = await satori(element as React.ReactNode, {
600 width: WIDTH,
601 height: HEIGHT,
602 fonts,
603 })
604​
605 console.log(`🖼️ Converting to PNG...`)
606 const resvg = new Resvg(svg, {
607 fitTo: {
608 mode: `width`,
609 value: WIDTH,
610 },
611 })
612 const pngData = resvg.render()
613 const pngBuffer = pngData.asPng()
614​
615 const outputPath = join(ROOT, `public`, `og-image.png`)
616 await writeFile(outputPath, pngBuffer)
617​
618 console.log(`✅ Done!`)
619 console.log(` Saved to: ${outputPath}`)
620 console.log(``)
621​
622 const svgPath = join(ROOT, `public`, `og-image.svg`)
623 await writeFile(svgPath, svg)
624 console.log(` SVG debug: ${svgPath}`)
625 console.log(``)
627​
628main().catch((err) => {
629 console.error(`Error:`, err)
630 process.exit(1)
631})