@ethercorps/sveltekit-og 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,188 +1,58 @@
1
- # SvelteKit Open Graph Image Generation
1
+ # create-svelte
2
2
 
3
- Dynamically generate Open Graph images from an HTML+CSS template or Svelte component using fast and efficient conversion from HTML > SVG > PNG. Based on [Satori](https://github.com/vercel/satori#documentation). No headless browser required.
3
+ Everything you need to build a Svelte library, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
4
4
 
5
- ## Installation
5
+ Read more about creating a library [in the docs](https://kit.svelte.dev/docs/packaging).
6
6
 
7
- ```bash
8
- pnpm install -D @ethercorps/sveltekit-og
9
- ```
10
- > Using with Cloudflare Pages or Workers then you have to provide `url` polyfill by just installing it as `devDependency`.
11
- >
12
- ```bash
13
- pnpm i -D url
14
- ```
15
-
16
- ## Usage
17
-
18
- Create a file at `/src/routes/og/+server.ts`. Alternatively, you can use JavaScript by removing the types from this example.
19
-
20
- ```typescript
21
- // src/routes/og/+server.ts
22
- import { ImageResponse } from '@ethercorps/sveltekit-og';
23
- import { RequestHandler } from './$types';
24
-
25
- const template = `
26
- <div tw="bg-gray-50 flex w-full h-full items-center justify-center">
27
- <div tw="flex flex-col md:flex-row w-full py-12 px-4 md:items-center justify-between p-8">
28
- <h2 tw="flex flex-col text-3xl sm:text-4xl font-bold tracking-tight text-gray-900 text-left">
29
- <span>Ready to dive in?</span>
30
- <span tw="text-indigo-600">Start your free trial today.</span>
31
- </h2>
32
- <div tw="mt-8 flex md:mt-0">
33
- <div tw="flex rounded-md shadow">
34
- <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>
35
- </div>
36
- <div tw="ml-3 flex rounded-md shadow">
37
- <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>
38
- </div>
39
- </div>
40
- </div>
41
- </div>
42
- `;
43
-
44
- const fontFile = await fetch('https://og-playground.vercel.app/inter-latin-ext-400-normal.woff');
45
- const fontData: ArrayBuffer = await fontFile.arrayBuffer();
46
-
47
- export const GET: RequestHandler = async () => {
48
- return await ImageResponse(template, {
49
- height: 630,
50
- width: 1200,
51
- fonts: [
52
- {
53
- name: 'Inter Latin',
54
- data: fontData,
55
- weight: 400
56
- }
57
- ]
58
- });
59
- };
60
- ```
61
-
62
- Then run `npm dev` and visit `localhost:5173/og` to view your generated PNG. Remember that hot module reloading does not work with server routes, so if you change your HTML or CSS, hard refresh the route to see changes.
63
-
64
- ## Example Output
65
-
66
- ![Rendered OG image](static/demo.png)
67
-
68
- ## Headers
69
-
70
- When run in development, image headers contain `cache-control: no-cache, no-store`. In production, image headers contain `'cache-control': 'public, immutable, no-transform, max-age=31536000'`, which caches the image for 1 year. In both cases, the `'content-type': 'image/png'` is used.
71
-
72
-
73
- ## Styling
74
-
75
- Notice that our example uses TailwindCSS classes (e.g. `tw="bg-gray-50"`). Alternatively, your HTML can contain style attributes using any of [the subset of CSS supported by Satori](https://github.com/vercel/satori#css).
76
-
77
- Satori supports only a subset of HTML and CSS. For full details, see [Satori’s documentation](https://github.com/vercel/satori#documentation). Notably, Satori only supports flex-based layouts.
78
-
79
- ## Fonts
80
-
81
- Satori supports `ttf`, `otf`, and `woff` font formats. To maximize the font parsing speed, `ttf` or `otf` are recommended over `woff`.
82
-
83
- By default, `@ethercorps/sveltekit-og` includes only 'Noto Sans' font. If you need to use other fonts, you can specify them as shown in the example. Notably, you can also import a font file that is stored locally within your project and are not required to use fetch.
7
+ ## Creating a project
84
8
 
85
- ## Examples
9
+ If you're seeing this, you've probably already done this step. Congrats!
86
10
 
87
- - `ImageResponse` · [_source_](/src/routes/new/+server.ts) · [_demo_](https://sveltekit-og-five.vercel.app/new)
88
- - `componentToImageResponse` · [_source_](/src/routes/component-og/) · [_demo_](https://sveltekit-og-five.vercel.app/component-og)
89
-
90
- ## API Reference
91
-
92
- The package exposes an `ImageResponse` and `componentToImageResponse` constructors, with the following options available:
93
-
94
- ```typescript
95
- import {ImageResponse, componentToImageResponse} from '@ethercorps/sveltekit-og'
96
- import {SvelteComponent} from "svelte";
97
-
98
- // ...
99
- ImageResponse(
100
- element : string,
101
- options : {
102
- width ? : number = 1200
103
- height ? : number = 630,
104
- backgroundColor ? : string = "#fff"
105
- fonts ? : {
106
- name: string,
107
- data: ArrayBuffer,
108
- weight: number,
109
- style: 'normal' | 'italic'
110
- }[]
111
- debug ? : boolean = false
112
- graphemeImages ? : Record<string, string>;
113
- loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
114
- // Options that will be passed to the HTTP response
115
- status ? : number = 200
116
- statusText ? : string
117
- headers ? : Record<string, string>
118
- })
11
+ ```bash
12
+ # create a new project in the current directory
13
+ npm create svelte@latest
119
14
 
120
- componentToImageResponse(
121
- component : typeof SvelteComponent,
122
- props : {}, // All export let example inside prop dictionary
123
- options : {
124
- width ? : number = 1200
125
- height ? : number = 630
126
- fonts ? : {
127
- name: string,
128
- data: ArrayBuffer,
129
- weight: number,
130
- style: 'normal' | 'italic'
131
- }[]
132
- debug ? : boolean = false
133
- graphemeImages ? : Record<string, string>;
134
- loadAdditionalAsset ? : (languageCode: string, segment: string) => Promise<SatoriOptions["fonts"] | string | undefined>;
135
- // Options that will be passed to the HTTP response
136
- status ? : number = 200
137
- statusText ? : string
138
- headers ? : Record<string, string>
139
- })
15
+ # create a new project in my-app
16
+ npm create svelte@latest my-app
140
17
  ```
141
18
 
142
- ## Changelog
19
+ ## Developing
143
20
 
144
- ### v1.2.3 Update (Breaking Changes)
145
- > Now you have to install dependency by yourself which will make it easier to build for all plateforms.
21
+ Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
146
22
 
147
- ```
148
- npm i @resvg/resvg-js
149
- ```
23
+ ```bash
24
+ npm run dev
150
25
 
151
- ```
152
- npm i satori
26
+ # or start the server and open the app in a new browser tab
27
+ npm run dev -- --open
153
28
  ```
154
29
 
155
- > From now on their will be no issues related to build, and soon this library going to have its own documentation.
30
+ Everything inside `src/lib` is part of your library, everything inside `src/routes` can be used as a showcase or preview app.
156
31
 
157
- ### v1.2.2 Update (Breaking Change)
32
+ ## Building
158
33
 
159
- - We don't provide access to satori from `@ethercorps/sveltekit-og`.
34
+ To build your library:
160
35
 
161
- ### v1.0.0 Update (Breaking Changes)
162
-
163
- Finally, We have added html to react like element like object converter out of the box and with svelte compiler.
164
- Now you can use `{ toReactElement }` with `"@ethercorps/sveltekit-og"` like:
165
-
166
- - We have changed to function based instead of class based ImageResponse and componentToImageResponse.
167
- - Removed `@resvg/resvg-wasm` with `@resvg/resvg-js` because of internal errors.
168
- - Removed `satori-html` because now we have `toReactElement` out of the box with svelte compiler.
169
- > If you find a problem related to undefined a please check [_vite.config.js_](/vite.config.ts) and add ` define: { _a: 'undefined' } in config.`
36
+ ```bash
37
+ npm run package
38
+ ```
170
39
 
171
- > If you find any issue and have suggestion for this project please open a ticket and if you want to contribute please create a new discussion.
40
+ To create a production version of your showcase app:
172
41
 
173
- ## Acknowledgements
42
+ ```bash
43
+ npm run build
44
+ ```
174
45
 
175
- This project will not be possible without the following projects:
46
+ You can preview the production build with `npm run preview`.
176
47
 
177
- - [Satori & @vercel/og](https://github.com/vercel/satori)
178
- - [Noto by Google Fonts](https://fonts.google.com/noto)
179
- - [svg2png-wasm](https://github.com/ssssota/svg2png-wasm)
48
+ > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
180
49
 
181
- ## Authors
50
+ ## Publishing
182
51
 
183
- - [@theetherGit](https://www.github.com/theetherGit)
184
- - [@etherCorps](https://www.github.com/etherCorps)
52
+ Go into the `package.json` and give your package the desired name through the `"name"` option. Also consider adding a `"license"` field and point it to a `LICENSE` file which you can create from a template (one popular option is the [MIT license](https://opensource.org/license/mit/)).
185
53
 
186
- ## Contributors
54
+ To publish your library to [npm](https://www.npmjs.com):
187
55
 
188
- - [@jasongitmail](https://github.com/jasongitmail)
56
+ ```bash
57
+ npm publish
58
+ ```
package/dist/api.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /// <reference types="node" />
2
+ import { ImageResponse as IR } from "@vercel/og";
3
+ import type { SvelteComponent } from "svelte";
4
+ export declare const ImageResponse: (htmlTemplate: string, options?: ImageResponseOptions) => Promise<IR>;
5
+ export declare const componentToImageResponse: (component: SvelteComponent, props: Record<string, any>, options?: ImageResponseOptions) => Promise<IR>;
6
+ declare const apis: {
7
+ twemoji: (code: any) => string;
8
+ openmoji: string;
9
+ blobmoji: string;
10
+ noto: string;
11
+ fluent: (code: any) => string;
12
+ fluentFlat: (code: any) => string;
13
+ };
14
+ declare type EmojiType = keyof typeof apis;
15
+ type Weight = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
16
+ type Style$1 = 'normal' | 'italic';
17
+ interface FontOptions {
18
+ data: Buffer | ArrayBuffer;
19
+ name: string;
20
+ weight?: Weight;
21
+ style?: Style$1;
22
+ lang?: string;
23
+ }
24
+ export declare type ImageResponseOptions = ImageOptions & ConstructorParameters<typeof Response>[1];
25
+ declare type ImageOptions = {
26
+ /**
27
+ * The width of the image.
28
+ *
29
+ * @type {number}
30
+ * @default 1200
31
+ */
32
+ width?: number;
33
+ /**
34
+ * The height of the image.
35
+ *
36
+ * @type {number}
37
+ * @default 630
38
+ */
39
+ height?: number;
40
+ /**
41
+ * Display debug information on the image.
42
+ *
43
+ * @type {boolean}
44
+ * @default false
45
+ */
46
+ debug?: boolean;
47
+ /**
48
+ * A list of fonts to use.
49
+ *
50
+ * @type {{ data: ArrayBuffer; name: string; weight?: 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; style?: 'normal' | 'italic' }[]}
51
+ * @default Noto Sans Latin Regular.
52
+ */
53
+ fonts?: FontOptions[];
54
+ /**
55
+ * Using a specific Emoji style. Defaults to `twemoji`.
56
+ *
57
+ * @link https://github.com/vercel/og#emoji
58
+ * @type {EmojiType}
59
+ * @default 'twemoji'
60
+ */
61
+ emoji?: EmojiType;
62
+ };
63
+ export {};
package/dist/api.js ADDED
@@ -0,0 +1,12 @@
1
+ import { html } from "satori-html";
2
+ import { ImageResponse as IR } from "@vercel/og";
3
+ export const ImageResponse = async (htmlTemplate, options) => {
4
+ const reactVNode = html(`${htmlTemplate}`);
5
+ console.log(reactVNode);
6
+ return new IR(reactVNode, options);
7
+ };
8
+ export const componentToImageResponse = async (component, props, options) => {
9
+ const ssrSvelte = component.render(props);
10
+ console.log(ssrSvelte);
11
+ return ImageResponse(`${ssrSvelte.html}<style>${ssrSvelte.css.code}</style>`, options);
12
+ };
@@ -0,0 +1 @@
1
+ export { componentToImageResponse, ImageResponse, type ImageResponseOptions } from "./api.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { componentToImageResponse, ImageResponse } from "./api.js";
package/package.json CHANGED
@@ -1,54 +1,55 @@
1
1
  {
2
2
  "name": "@ethercorps/sveltekit-og",
3
- "version": "2.0.0",
4
- "private": false,
3
+ "version": "2.0.2",
4
+ "exports": {
5
+ ".": {
6
+ "types": "./dist/index.d.ts",
7
+ "svelte": "./dist/index.js"
8
+ }
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "!dist/**/*.test.*",
13
+ "!dist/**/*.spec.*"
14
+ ],
15
+ "peerDependencies": {
16
+ "svelte": "^4.0.0"
17
+ },
5
18
  "devDependencies": {
6
- "@playwright/test": "^1.34.3",
7
- "@sveltejs/adapter-auto": "next",
8
- "@sveltejs/adapter-vercel": "^2.4.3",
9
- "@sveltejs/kit": "1.10.0",
10
- "@sveltejs/package": "next",
11
- "@typescript-eslint/eslint-plugin": "^5.59.9",
12
- "@typescript-eslint/parser": "^5.59.9",
13
- "autoprefixer": "^10.4.14",
14
- "brace": "^0.11.1",
15
- "eslint": "^8.42.0",
16
- "eslint-config-prettier": "^8.8.0",
17
- "eslint-plugin-svelte3": "^4.0.0",
18
- "postcss": "^8.4.24",
19
- "prettier": "^2.8.8",
19
+ "@sveltejs/adapter-auto": "^2.0.0",
20
+ "@sveltejs/kit": "^1.20.4",
21
+ "@sveltejs/package": "^2.0.0",
22
+ "@typescript-eslint/eslint-plugin": "^5.45.0",
23
+ "@typescript-eslint/parser": "^5.45.0",
24
+ "eslint": "^8.28.0",
25
+ "eslint-config-prettier": "^8.5.0",
26
+ "eslint-plugin-svelte": "^2.30.0",
27
+ "prettier": "^2.8.0",
20
28
  "prettier-plugin-svelte": "^2.10.1",
21
- "prismjs": "^1.29.0",
22
- "svelte": "^3.59.1",
23
- "svelte-check": "^2.10.3",
24
- "svelte-preprocess": "^4.10.7",
25
- "tailwindcss": "^3.3.2",
26
- "tslib": "^2.5.3",
27
- "typescript": "^4.9.5",
28
- "vite": "^4.3.9"
29
+ "publint": "^0.1.9",
30
+ "svelte": "^4.0.5",
31
+ "svelte-check": "^3.4.3",
32
+ "tslib": "^2.4.1",
33
+ "typescript": "^5.0.0",
34
+ "vite": "^4.4.2",
35
+ "vitest": "^0.34.0"
29
36
  },
37
+ "svelte": "./dist/index.js",
38
+ "types": "./dist/index.d.ts",
30
39
  "type": "module",
31
40
  "dependencies": {
32
- "satori": "^0.10.1",
33
- "svg2png-wasm": "^1.4.0"
41
+ "@vercel/og": "^0.5.17",
42
+ "satori-html": "^0.3.2"
34
43
  },
35
- "keywords": [
36
- "open graph image",
37
- "open graph",
38
- "og image",
39
- "og:image",
40
- "social",
41
- "card",
42
- "sveltekit og",
43
- "sveltekit-og",
44
- "@ethercorps/sveltekit-og"
45
- ],
46
- "license": "MIT",
47
- "repository": "https://github.com/etherCorps/sveltekit-og",
48
- "homepage": "https://github.com/etherCorps/sveltekit-og#readme",
49
- "exports": {
50
- "./package.json": "./package.json",
51
- ".": "./index.js",
52
- "./toReactElement": "./toReactElement.js"
44
+ "scripts": {
45
+ "dev": "vite dev",
46
+ "build": "vite build && npm run package",
47
+ "preview": "vite preview",
48
+ "package": "svelte-kit sync && svelte-package && publint",
49
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
50
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
51
+ "test": "vitest",
52
+ "lint": "prettier --plugin-search-dir . --check . && eslint .",
53
+ "format": "prettier --plugin-search-dir . --write ."
53
54
  }
54
55
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022 Ether Corps
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/index.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { type SatoriOptions } from 'satori';
2
- import type { SvelteComponent } from 'svelte';
3
- import toReactElement from './toReactElement';
4
- declare const ImageResponse: (htmlTemplate: string, optionsByUser: ImageResponseOptions) => Promise<Response>;
5
- declare const componentToImageResponse: (component: typeof SvelteComponent, props: {} | undefined, optionsByUser: ImageResponseOptions) => Promise<Response>;
6
- type ImageResponseOptions = ConstructorParameters<typeof Response>[1] & ImageOptions;
7
- type ImageOptions = {
8
- width?: number;
9
- height?: number;
10
- debug?: boolean;
11
- fonts?: SatoriOptions['fonts'];
12
- backgroundColor?: string;
13
- graphemeImages?: Record<string, string>;
14
- loadAdditionalAsset?: (languageCode: string, segment: string) => Promise<SatoriOptions['fonts'] | string | undefined>;
15
- };
16
- export type ImageResponseType = typeof ImageResponse;
17
- export { componentToImageResponse, ImageResponse, toReactElement };
package/index.js DELETED
@@ -1,62 +0,0 @@
1
- import satori, {} from 'satori';
2
- import toReactElement from './toReactElement';
3
- import { svg2png, initialize } from 'svg2png-wasm';
4
- let initialized = false;
5
- const fontFile = await fetch('https://sveltekit-og.ethercorps.io/noto-sans.ttf');
6
- const fontData = await fontFile.arrayBuffer();
7
- const indexWasmRes = await fetch('https://unpkg.com/svg2png-wasm/svg2png_wasm_bg.wasm');
8
- const svg2PngWasmBuffer = await indexWasmRes.arrayBuffer();
9
- const initSvgToPng = async () => {
10
- await initialize(svg2PngWasmBuffer).catch((e) => console.log(e));
11
- initialized = true;
12
- };
13
- const ImageResponse = async (htmlTemplate, optionsByUser) => {
14
- const options = Object.assign({ width: 1200, height: 630, debug: !1 }, optionsByUser);
15
- const svg = await satori(toReactElement(htmlTemplate), {
16
- width: options.width,
17
- height: options.height,
18
- debug: options.debug,
19
- fonts: options.fonts || [
20
- {
21
- name: 'sans serif',
22
- data: fontData,
23
- style: 'normal',
24
- weight: 700
25
- }
26
- ]
27
- });
28
- if (!initialized) {
29
- await initSvgToPng();
30
- initialized = true;
31
- }
32
- const defaultConfig = {
33
- width: options.width,
34
- height: options.height, // optional
35
- };
36
- if (Object.hasOwn(options, 'backgroundColor')) {
37
- defaultConfig.backgroundColor = options.backgroundColor;
38
- }
39
- const png = await svg2png(svg, defaultConfig);
40
- return new Response(png, {
41
- headers: {
42
- 'Content-Type': 'image/png',
43
- 'cache-control': 'public, immutable, no-transform, max-age=31536000',
44
- ...options.headers
45
- },
46
- status: options.status,
47
- statusText: options.statusText
48
- });
49
- };
50
- const componentToImageResponse = (component, props = {}, optionsByUser) => {
51
- const htmlTemplate = componentToMarkup(component, props);
52
- return ImageResponse(htmlTemplate, optionsByUser);
53
- };
54
- const componentToMarkup = (component, props = {}) => {
55
- const SvelteRenderedMarkup = component.render(props);
56
- let htmlTemplate = `${SvelteRenderedMarkup.html}`;
57
- if (SvelteRenderedMarkup && SvelteRenderedMarkup.css && SvelteRenderedMarkup.css.code) {
58
- htmlTemplate = `${SvelteRenderedMarkup.html}<style>${SvelteRenderedMarkup.css.code}</style>`;
59
- }
60
- return htmlTemplate;
61
- };
62
- export { componentToImageResponse, ImageResponse, toReactElement };
@@ -1,10 +0,0 @@
1
- interface VNode {
2
- type: string;
3
- props: {
4
- style?: Record<string, any>;
5
- children?: string | VNode | VNode[];
6
- [prop: string]: any;
7
- };
8
- }
9
- export declare const toReactElement: (htmlString: string) => VNode;
10
- export default toReactElement;
package/toReactElement.js DELETED
@@ -1,100 +0,0 @@
1
- import { parse, walk } from 'svelte/compiler';
2
- /* Start of code from satori-html for cssToObject converter*/
3
- const camelize = (ident) => ident.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
4
- const cssToObject = (str) => {
5
- const obj = {};
6
- let t = 0;
7
- let pair = ['', ''];
8
- const flags = {};
9
- for (const c of str) {
10
- if (!flags['('] && c === ':') {
11
- t = 1;
12
- }
13
- else if (c === ';') {
14
- const [decl = '', value = ''] = pair;
15
- obj[camelize(decl.trim())] = value.trim();
16
- t = 0;
17
- pair = ['', ''];
18
- }
19
- else {
20
- pair[t] += c;
21
- switch (c) {
22
- case '(': {
23
- flags[c]++;
24
- break;
25
- }
26
- case ')': {
27
- flags['(']--;
28
- break;
29
- }
30
- }
31
- }
32
- }
33
- const [decl = '', value = ''] = pair;
34
- if (decl.trim() && value.trim()) {
35
- obj[camelize(decl.trim())] = value.trim();
36
- }
37
- return obj;
38
- };
39
- const nodeMap = new WeakMap();
40
- const root = {
41
- type: 'div',
42
- props: {
43
- style: {
44
- display: 'flex',
45
- flexDirection: 'column',
46
- width: '100%',
47
- height: '100%'
48
- },
49
- children: []
50
- }
51
- };
52
- /* End of satori-html */
53
- export const toReactElement = (htmlString) => {
54
- const svelteAST = parse(htmlString);
55
- walk(svelteAST, {
56
- enter(node, parent, prop, index) {
57
- let newNode = {};
58
- if (node.type === 'Fragment') {
59
- nodeMap.set(node, root);
60
- }
61
- else if (node.type === 'Element') {
62
- newNode.type = node.name;
63
- const { ...props } = node.attributes;
64
- if (node.attributes.length > 0) {
65
- node.attributes.forEach((attribute) => {
66
- if (attribute.name === 'style') {
67
- props['style'] = cssToObject(attribute.value[0].data);
68
- }
69
- else
70
- props[attribute.name] = attribute.value[0].data;
71
- });
72
- delete props[0];
73
- }
74
- props.children = [];
75
- Object.assign(newNode, { props });
76
- nodeMap.set(node, newNode);
77
- if (parent) {
78
- const newParent = nodeMap.get(parent);
79
- newParent.props.children[index] = newNode;
80
- }
81
- }
82
- else if (node.type === 'Text') {
83
- newNode = node.data.trim();
84
- if (newNode) {
85
- if (parent && parent.type !== 'Attribute') {
86
- const newParent = nodeMap.get(parent);
87
- if (parent.children.length === 1) {
88
- newParent.props.children = newNode;
89
- }
90
- else {
91
- newParent.props.children[index] = newNode;
92
- }
93
- }
94
- }
95
- }
96
- }
97
- });
98
- return root;
99
- };
100
- export default toReactElement;