Skip to content

v3 #17

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

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft

v3 #17

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
31 changes: 5 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const App = () => (
Primarily meant for use with prerendering via [`@preact/preset-vite`](https://github.com/preactjs/preset-vite#prerendering-configuration) or other prerendering systems that share the API. If you're server-side rendering your app via any other method, you can use `preact-render-to-string` (specifically `renderToStringAsync()`) directly.

```js
import { render, hydrate } from 'preact';
import { LocationProvider, ErrorBoundary, Router, lazy, prerender as ssr } from 'preact-iso';

// Asynchronous (throws a promise)
Expand All @@ -67,7 +68,10 @@ const App = () => (
</LocationProvider>
);

hydrate(<App />);
if (typeof window !== 'undefined') {
const target = document.getElementById('app');
import.meta.env.DEV ? render(<App />, target) : hydrate(<App />, target);
}

export async function prerender(data) {
return await ssr(<App />);
Expand Down Expand Up @@ -270,31 +274,6 @@ const App = () => (
);
```

### `hydrate`

A thin wrapper around Preact's `hydrate` export, it switches between hydrating and rendering the provided element, depending on whether the current page has been prerendered. Additionally, it checks to ensure it's running in a browser context before attempting any rendering, making it a no-op during SSR.

Pairs with the `prerender()` function.

Params:

- `jsx: ComponentChild` - The JSX element or component to render
- `parent?: Element | Document | ShadowRoot | DocumentFragment` - The parent element to render into. Defaults to `document.body` if not provided.

```js
import { hydrate } from 'preact-iso';

const App = () => (
<div class="app">
<h1>Hello World</h1>
</div>
);

hydrate(<App />);
```

However, it is just a simple utility method. By no means is it essential to use, you can always use Preact's `hydrate` export directly.

### `prerender`

Renders a Virtual DOM tree to an HTML string using `preact-render-to-string`. The Promise returned from `prerender()` resolves to an Object with `html` and `links[]` properties. The `html` property contains your pre-rendered static HTML markup, and `links` is an Array of any non-external URL strings found in links on the generated page.
Expand Down
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@
"types": "src/index.d.ts",
"exports": {
".": "./src/index.js",
"./router": "./src/router.js",
"./lazy": "./src/lazy.js",
"./prerender": "./src/prerender.js",
"./hydrate": "./src/hydrate.js"
"./package.json": "./package.json"
},
"license": "MIT",
"description": "Isomorphic utilities for Preact",
Expand All @@ -35,6 +33,11 @@
"preact": ">=10",
"preact-render-to-string": ">=6.4.0"
},
"peerDependenciesMeta": {
"preact-render-to-string": {
"optional": true
}
},
"devDependencies": {
"@types/mocha": "^10.0.7",
"@types/sinon-chai": "^3.2.12",
Expand Down
3 changes: 0 additions & 3 deletions src/hydrate.d.ts

This file was deleted.

17 changes: 0 additions & 17 deletions src/hydrate.js

This file was deleted.

4 changes: 1 addition & 3 deletions src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
export { default as prerender } from './prerender.js';
export * from './lazy.js';
export * from './router.js';
export { default as lazy, ErrorBoundary } from './lazy.js';
export { default as hydrate } from './hydrate.js';
9 changes: 2 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,2 @@
export { Router, LocationProvider, useLocation, Route, useRoute } from './router.js';
export { default as lazy, ErrorBoundary } from './lazy.js';
export { default as hydrate } from './hydrate.js';

export function prerender(vnode, options) {
return import('./prerender.js').then(m => m.default(vnode, options));
}
export * from './lazy.js';
export * from './router.js';
2 changes: 1 addition & 1 deletion src/lazy.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ComponentChildren, VNode } from 'preact';

export default function lazy<T>(load: () => Promise<{ default: T } | T>): T & {
export function lazy<T>(load: () => Promise<{ default: T } | T>): T & {
preload: () => Promise<T>;
};

Expand Down
2 changes: 1 addition & 1 deletion src/lazy.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ options.__b = (vnode) => {
if (oldDiff) oldDiff(vnode);
};

export default function lazy(load) {
export function lazy(load) {
let p, c;

const loadModule = () =>
Expand Down
2 changes: 1 addition & 1 deletion src/prerender.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export interface PrerenderResult {
links?: Set<string>
}

export default function prerender(
export function prerender(
vnode: VNode,
options?: PrerenderOptions
): Promise<PrerenderResult>;
Expand Down
7 changes: 3 additions & 4 deletions src/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ options.vnode = vnode => {
* @param {object} [options]
* @param {object} [options.props] Additional props to merge into the root JSX element
*/
export default async function prerender(vnode, options) {
export async function prerender(vnode, options) {
options = options || {};

const props = options.props;
Expand All @@ -25,16 +25,15 @@ export default async function prerender(vnode, options) {
vnode = cloneElement(vnode, props);
}

let links = new Set();
const links = new Set();
vnodeHook = ({ type, props }) => {
if (type === 'a' && props && props.href && (!props.target || props.target === '_self')) {
links.add(props.href);
}
};

try {
let html = await renderToStringAsync(vnode);
html += `<script type="isodata"></script>`;
const html = await renderToStringAsync(vnode);
return { html, links };
} finally {
vnodeHook = null;
Expand Down
12 changes: 3 additions & 9 deletions src/router.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type NestedArray<T> = Array<T | NestedArray<T>>;

/**
* Check if a URL path matches against a URL path pattern.
*
*
* Warning: This is an internal API exported only for testing purpose. API could change in future.
* @param url - URL path (e.g. /user/12345)
* @param route - URL pattern (e.g. /user/:id)
Expand Down Expand Up @@ -38,18 +38,12 @@ export function Router(props: {
interface LocationHook {
url: string;
path: string;
query: Record<string, string>;
pathParams: Record<string, string>;
searchParams: Record<string, string>;
route: (url: string, replace?: boolean) => void;
}
export const useLocation: () => LocationHook;

interface RouteHook {
path: string;
query: Record<string, string>;
params: Record<string, string>;
}
export const useRoute: () => RouteHook;

type RoutableProps =
| { path: string; default?: false; }
| { path?: never; default: true; }
Expand Down
32 changes: 15 additions & 17 deletions src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ const UPDATE = (state, url) => {
export const exec = (url, route, matches = {}) => {
url = url.split('/').filter(Boolean);
route = (route || '').split('/').filter(Boolean);
if (!matches.params) matches.params = {};
if (!matches.pathParams) matches.pathParams = {};
for (let i = 0, val, rest; i < Math.max(url.length, route.length); i++) {
let [, m, param, flag] = (route[i] || '').match(/^(:?)(.*?)([+*?]?)$/);
let [, m, pathParam, flag] = (route[i] || '').match(/^(:?)(.*?)([+*?]?)$/);
val = url[i];
// segment match:
if (!m && param == val) continue;
if (!m && pathParam == val) continue;
// /foo/* match
if (!m && val && flag == '*') {
matches.rest = '/' + url.slice(i).map(decodeURIComponent).join('/');
Expand All @@ -69,8 +69,8 @@ export const exec = (url, route, matches = {}) => {
if (rest) val = url.slice(i).map(decodeURIComponent).join('/') || undefined;
// normal/optional field:
else if (val) val = decodeURIComponent(val);
matches.params[param] = val;
if (!(param in matches)) matches[param] = val;
matches.pathParams[pathParam] = val;
if (!(pathParam in matches)) matches[pathParam] = val;
if (rest) break;
}
return matches;
Expand All @@ -80,19 +80,19 @@ export const exec = (url, route, matches = {}) => {
* @type {import('./router.d.ts').LocationProvider}
*/
export function LocationProvider(props) {
// @ts-expect-error - props.url is not implemented correctly & will be removed in the future
const [url, route] = useReducer(UPDATE, props.url || location.pathname + location.search);
const [url, route] = useReducer(UPDATE, location.pathname + location.search);
if (props.scope) scope = props.scope;
const wasPush = push === true;

const value = useMemo(() => {
const u = new URL(url, location.origin);
const path = u.pathname.replace(/\/+$/g, '') || '/';
// @ts-ignore-next

return {
url,
path,
query: Object.fromEntries(u.searchParams),
pathParams: {},
searchParams: Object.fromEntries(u.searchParams),
route: (url, replace) => route({ url, replace }),
wasPush
};
Expand All @@ -108,7 +108,6 @@ export function LocationProvider(props) {
};
}, []);

// @ts-ignore
return h(LocationProvider.ctx.Provider, { value }, props.children);
}

Expand All @@ -117,8 +116,8 @@ const RESOLVED = Promise.resolve();
export function Router(props) {
const [c, update] = useReducer(c => c + 1, 0);

const { url, query, wasPush, path } = useLocation();
const { rest = path, params = {} } = useContext(RouteContext);
const { url, path, pathParams, searchParams, wasPush } = useLocation();
const { rest = path } = useContext(RouterContext);

const isLoading = useRef(false);
const prevRoute = useRef(path);
Expand All @@ -138,7 +137,7 @@ export function Router(props) {

let pathRoute, defaultRoute, matchProps;
toChildArray(props.children).some((/** @type {VNode<any>} */ vnode) => {
const matches = exec(rest, vnode.props.path, (matchProps = { ...vnode.props, path: rest, query, params, rest: '' }));
const matches = exec(rest, vnode.props.path, (matchProps = { ...vnode.props, path: rest, pathParams, searchParams }));
if (matches) return (pathRoute = cloneElement(vnode, matchProps));
if (vnode.props.default) defaultRoute = cloneElement(vnode, matchProps);
});
Expand All @@ -151,7 +150,7 @@ export function Router(props) {
const routeChanged = useMemo(() => {
prev.current = cur.current;

cur.current = /** @type {VNode<any>} */ (h(RouteContext.Provider, { value: matchProps }, incoming));
cur.current = /** @type {VNode<any>} */ (h(RouterContext.Provider, { value: matchProps }, incoming));

// Only mark as an update if the route component changed.
const outgoing = prev.current && prev.current.props.children;
Expand Down Expand Up @@ -265,11 +264,10 @@ Router.Provider = LocationProvider;
LocationProvider.ctx = createContext(
/** @type {import('./router.d.ts').LocationHook & { wasPush: boolean }} */ ({})
);
const RouteContext = createContext(
/** @type {import('./router.d.ts').RouteHook & { rest: string }} */ ({})
const RouterContext = createContext(
/** @type {{ rest: string }} */ ({})
);

export const Route = props => h(props.component, props);

export const useLocation = () => useContext(LocationProvider.ctx);
export const useRoute = () => useContext(RouteContext);
2 changes: 1 addition & 1 deletion test/lazy.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as sinon from 'sinon';
import sinonChai from 'sinon-chai';

import { LocationProvider, Router } from '../src/router.js';
import lazy, { ErrorBoundary } from '../src/lazy.js';
import { lazy, ErrorBoundary } from '../src/lazy.js';

import './setup.js';

Expand Down
8 changes: 1 addition & 7 deletions test/node/prerender.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { test } from 'uvu';
import * as assert from 'uvu/assert';
import { html } from 'htm/preact';

import { default as prerender } from '../../src/prerender.js';
import { prerender } from '../../src/prerender.js';

test('extracts links', async () => {
const App = () => html`
Expand All @@ -20,10 +20,4 @@ test('extracts links', async () => {
assert.ok(links.has('/baz'), `missing: /baz`);
});

test('appends iso data script', async () => {
const { html: h } = await prerender(html`<div />`);
// Empty for now, but used for hydration vs render detection
assert.match(h, /<script type="isodata"><\/script>/, 'missing iso data script tag');
});

test.run();
Loading