~james/core

core/ogre/src/lib/render.ts -rw-r--r-- 1021 bytes
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import type { VNode } from "preact";
import { initSatori, initResvg, loadFonts } from "@tangled/ogre-runtime";
import type { ResvgClass } from "@tangled/ogre-runtime/types";

let satoriFn: typeof import("satori").default | null = null;
let Resvg: ResvgClass | null = null;
let fontsLoaded = false;
let cachedFonts: Awaited<ReturnType<typeof loadFonts>> | null = null;

export interface RenderResult {
  svg: string;
  png: Uint8Array;
}

export async function renderCard(component: VNode): Promise<RenderResult> {
  if (!satoriFn) {
    satoriFn = await initSatori();
  }

  if (!Resvg) {
    Resvg = await initResvg();
  }

  if (!fontsLoaded) {
    cachedFonts = await loadFonts();
    fontsLoaded = true;
  }

  const svg = await satoriFn(component as any, {
    width: 1200,
    height: 630,
    fonts: cachedFonts!,
    embedFont: true,
  });

  const resvg = new Resvg!(svg, {
    fitTo: { mode: "width", value: 1200 },
  });

  const pngData = resvg.render();

  return {
    svg,
    png: pngData.asPng(),
  };
}