Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor iso #197

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions preact-iso/src/prerender.d.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { VNode } from 'preact';
import { VNode } from "preact";

export interface PrerenderOptions {
maxDepth?: number;
props?: Record<string, unknown>;
}

export interface PrerenderResult {
html: string;
links?: Set<string>
links?: Set<string>;
}

export default function prerender(
Expand Down
18 changes: 3 additions & 15 deletions preact-iso/src/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,19 @@ options.vnode = (vnode) => {
/**
* @param {ReturnType<h>} vnode The root JSX element to render (eg: `<App />`)
* @param {object} [options]
* @param {number} [options.maxDepth = 10] The maximum number of nested asynchronous operations to wait for before flushing
* @param {object} [options.props] Additional props to merge into the root JSX element
*/
export default async function prerender(vnode, options) {
options = options || {};

const maxDepth = options.maxDepth || 10;
const props = options.props;
let tries = 0;

if (typeof vnode === "function") {
vnode = h(vnode, props);
} else if (props) {
vnode = cloneElement(vnode, props);
}

const render = () => {
if (++tries > maxDepth) return;
try {
return renderToStringAsync(vnode);
} catch (e) {
if (e && e.then) return e.then(render);
throw e;
}
};

let links = new Set();
vnodeHook = ({ type, props }) => {
if (
Expand All @@ -51,8 +38,9 @@ export default async function prerender(vnode, options) {
};

try {
let html = await render();
html += `<script type="isodata"></script>`;
const html = `${await renderToStringAsync(
vnode
)}<script type="isodata"></script>`;
return { html, links };
} finally {
vnodeHook = null;
Expand Down
Loading