Complete rewrite and added html to react element using svelte compiler

This commit is contained in:
Shivam Meena
2022-12-09 11:21:39 +05:30
parent 5f3692f078
commit 7965882383
15 changed files with 665 additions and 667 deletions

View File

@@ -1,6 +1,6 @@
import OG from './OG.svelte';
import type { RequestHandler } from '@sveltejs/kit';
import {componentToImageResponse} from "@ethercorps/sveltekit-og";
import { componentToImageResponse } from '@ethercorps/sveltekit-og';
const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-700-normal.woff');
const fontData: ArrayBuffer = await fontFile.arrayBuffer();

View File

@@ -14,29 +14,31 @@
"format": "prettier --plugin-search-dir . --write ."
},
"devDependencies": {
"@playwright/test": "^1.27.1",
"@playwright/test": "^1.28.1",
"@sveltejs/adapter-auto": "next",
"@sveltejs/kit": "next",
"@sveltejs/package": "next",
"@typescript-eslint/eslint-plugin": "^5.42.1",
"@typescript-eslint/parser": "^5.42.1",
"eslint": "^8.27.0",
"@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"eslint": "^8.29.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-svelte3": "^4.0.0",
"prettier": "^2.7.1",
"prettier-plugin-svelte": "^2.8.0",
"svelte": "^3.53.1",
"svelte-check": "^2.9.2",
"prettier": "^2.8.1",
"prettier-plugin-svelte": "^2.8.1",
"svelte": "^3.54.0",
"svelte-check": "^2.10.2",
"svelte-preprocess": "^4.10.7",
"tslib": "^2.4.1",
"typescript": "^4.8.4",
"vite": "^3.2.3"
"typescript": "^4.9.4",
"vite": "^3.2.5"
},
"type": "module",
"dependencies": {
"@resvg/resvg-wasm": "^2.1.0",
"satori": "^0.0.44",
"satori-html": "^0.3.0"
"@resvg/resvg-js": "^2.2.0",
"satori": "^0.0.44"
},
"peerDependencies": {
"svelte": "^3.54.0"
},
"keywords": [
"open graph image",

1001
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +1,14 @@
import { html as toReactNode } from 'satori-html';
import satori from 'satori';
import { Resvg, initWasm } from '@resvg/resvg-wasm';
import type { SatoriOptions } from 'satori';
import satori, { type SatoriOptions } from 'satori';
import { Resvg, type ResvgRenderOptions } from '@resvg/resvg-js';
import type { SvelteComponent } from 'svelte';
import toReactElement from './toReactElement';
const resSvgWasm = initWasm(fetch('https://sveltekit-og.ethercorps.io/resvg.wasm'));
const fontFile = await fetch('https://sveltekit-og.ethercorps.io/noto-sans.ttf');
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
class ImageResponse {
constructor(htmlTemplate: string, optionsByUser: ImageResponseOptions) {
const ImageResponse = async (htmlTemplate: string, optionsByUser: ImageResponseOptions) => {
const options = Object.assign({ width: 1200, height: 630, debug: !1 }, optionsByUser);
const png = new ReadableStream({
async start(a) {
await resSvgWasm;
const svg = await satori(toReactNode(htmlTemplate), {
const svg = await satori(toReactElement(htmlTemplate), {
width: options.width,
height: options.height,
debug: options.debug,
@@ -27,12 +21,16 @@ class ImageResponse {
}
]
});
const pngData = new Resvg(svg, { fitTo: { mode: 'width', value: options.width } });
a.enqueue(pngData.render().asPng());
a.close();
const reSvgOptions = {
fitTo: {
mode: 'width',
value: options.width
}
});
return new Response(png, {
} as ResvgRenderOptions;
const reSvgObject = new Resvg(svg, reSvgOptions);
const pngData = await reSvgObject.render().asPng();
return new Response(pngData, {
headers: {
'Content-Type': 'image/png',
'cache-control': 'public, immutable, no-transform, max-age=31536000',
@@ -42,15 +40,16 @@ class ImageResponse {
status: options.status,
statusText: options.statusText
});
}
}
};
class componentToImageResponse {
constructor(component: typeof SvelteComponent, props = {}, optionsByUser: ImageResponseOptions) {
const componentToImageResponse = (
component: typeof SvelteComponent,
props = {},
optionsByUser: ImageResponseOptions
) => {
const htmlTemplate = componentToMarkup(component, props);
return new ImageResponse(htmlTemplate, optionsByUser);
}
}
return ImageResponse(htmlTemplate, optionsByUser);
};
const componentToMarkup = (component: typeof SvelteComponent, props = {}) => {
const SvelteRenderedMarkup = (component as any).render(props);
@@ -75,4 +74,6 @@ type ImageOptions = {
) => Promise<SatoriOptions['fonts'] | string | undefined>;
};
export { componentToImageResponse, ImageResponse };
type ImageResponseType = typeof ImageResponse;
export { componentToImageResponse, ImageResponse, toReactElement, satori, type ImageResponseType };

107
src/lib/toReactElement.ts Normal file
View File

@@ -0,0 +1,107 @@
import { parse, walk } from 'svelte/compiler';
import type { Ast } from 'svelte/types/compiler/interfaces';
/* Start of code from satori-html for cssToObject converter*/
const camelize = (ident: string) => ident.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
const cssToObject = (str: string) => {
const obj: Record<string, string> = {};
let t = 0;
let pair = ['', ''];
const flags: Record<string, number> = {};
for (const c of str) {
if (!flags['('] && c === ':') {
t = 1;
} else if (c === ';') {
const [decl = '', value = ''] = pair;
obj[camelize(decl.trim())] = value.trim();
t = 0;
pair = ['', ''];
} else {
pair[t] += c;
switch (c) {
case '(': {
flags[c]++;
break;
}
case ')': {
flags['(']--;
break;
}
}
}
}
const [decl = '', value = ''] = pair;
if (decl.trim() && value.trim()) {
obj[camelize(decl.trim())] = value.trim();
}
return obj;
};
const nodeMap = new WeakMap();
interface VNode {
type: string;
props: {
style?: Record<string, any>;
children?: string | VNode | VNode[];
[prop: string]: any;
};
}
const root: VNode = {
type: 'div',
props: {
style: {
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%'
},
children: []
}
};
/* End of satori-html */
const toReactElement = (htmlString: string): VNode => {
const svelteAST: Ast = parse(htmlString);
walk(svelteAST, {
enter(node: any, parent: any, prop: any, index: any) {
let newNode: any = {};
if (node.type === 'Fragment') {
nodeMap.set(node, root);
} else if (node.type === 'Element') {
newNode.type = node.name;
const { ...props } = node.attributes;
if (node.attributes.length > 0) {
node.attributes.forEach((attribute: any) => {
if (attribute.name === 'style') {
props['style'] = cssToObject(attribute.value[0].data) as any;
} else props[attribute.name] = attribute.value[0].data as any;
});
delete props[0];
}
props.children = [] as unknown as string;
Object.assign(newNode, { props });
nodeMap.set(node, newNode);
if (parent) {
const newParent = nodeMap.get(parent);
newParent.props.children[index] = newNode;
}
} else if (node.type === 'Text') {
newNode = node.data.trim();
if (newNode) {
if (parent && parent.type !== 'Attribute') {
const newParent = nodeMap.get(parent);
if (parent.children.length === 1) {
newParent.props.children = newNode;
} else {
newParent.props.children[index] = newNode;
}
}
}
}
}
});
return root;
};
export default toReactElement;

View File

@@ -25,7 +25,7 @@ const fontData400: ArrayBuffer = await fontFile400.arrayBuffer();
const fontData700: ArrayBuffer = await fontFile700.arrayBuffer();
export const GET: RequestHandler = async () => {
return new ImageResponse(template, {
return await ImageResponse(template, {
height: 250,
width: 500,
fonts: [

View File

@@ -6,7 +6,7 @@ const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-7
const fontData: ArrayBuffer = await fontFile.arrayBuffer();
export const GET: RequestHandler = async () => {
return new componentToImageResponse(
return await componentToImageResponse(
OG,
{ text: 'Ready to dive in?', spanText: 'Start your free trial today.' },
{

44
src/routes/new/+server.ts Normal file
View File

@@ -0,0 +1,44 @@
import { ImageResponse } from '$lib';
import type { RequestHandler } from '@sveltejs/kit';
const template = `
<div tw="bg-gray-50 flex w-full h-full items-center justify-center">
<div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
<h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
<span>Ready to dive in?</span>
<span tw="text-indigo-600">Start your free trial today.</span>
</h2>
<div tw="mt-8 flex md:mt-0">
<div tw="flex rounded-md shadow">
<a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white">Get started</a>
</div>
<div tw="ml-3 flex rounded-md shadow">
<a href="#" tw="flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600">Learn more</a>
</div>
</div>
</div>
</div>
`;
const fontFile400 = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
const fontFile700 = await fetch('https://og-playground.vercel.app/inter-latin-ext-700-normal.woff');
const fontData400: ArrayBuffer = await fontFile400.arrayBuffer();
const fontData700: ArrayBuffer = await fontFile700.arrayBuffer();
export const GET: RequestHandler = async () => {
return await ImageResponse(template, {
height: 250,
width: 500,
fonts: [
{
name: 'Inter Latin',
data: fontData400,
weight: 400
},
{
name: 'Inter Latin',
data: fontData700,
weight: 700
}
]
});
};

View File

@@ -0,0 +1,43 @@
import toReactElement from '$lib/toReactElement';
import satori from 'satori';
const htmlString = `
<div tw="bg-gray-50 flex w-full">
<div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
<h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
<span>Ready to dive in?</span>
<span tw="text-indigo-600">Start your free trial today.</span>
</h2>
<div tw="mt-8 flex md:mt-0">
<div tw="flex rounded-md shadow">
<a tw="flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white">Get started</a>
</div>
<div tw="ml-3 flex rounded-md shadow">
<a tw="flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600">Learn more</a>
</div>
</div>
</div>
</div>
`;
const newNode = toReactElement(htmlString);
/** @type {import('./$types').PageServerLoad} */
export async function load() {
const fontFile400 = await fetch(
'https://og-playground.vercel.app/inter-latin-ext-400-normal.woff'
);
const fontData400 = await fontFile400.arrayBuffer();
const svg = await satori(newNode, {
height: 350,
width: 500,
fonts: [
{
name: 'sans serif',
data: fontData400,
style: 'normal',
weight: 700
}
]
});
return { svg };
}

View File

@@ -0,0 +1,5 @@
<script lang="ts">
export let data;
</script>
{@html data.svg}

BIN
static/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -2,7 +2,10 @@ import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()]
plugins: [sveltekit()],
define: {
_a: 'undefined'
}
};
export default config;