Skip to content

Commit

Permalink
feat: add preact-ssr-prepass (#9524)
Browse files Browse the repository at this point in the history
* feat: add preact-ssr-prepass

* added more info to changelog

* fix example in changelog

* fix changelog description

* fix tab in code of changelog

* Update .changeset/blue-bobcats-remain.md

---------

Co-authored-by: Florian Lefebvre <[email protected]>
  • Loading branch information
aleksandrjet and florian-lefebvre authored Jan 4, 2024
1 parent a1b324b commit 0903ef9
Show file tree
Hide file tree
Showing 18 changed files with 287 additions and 71 deletions.
21 changes: 21 additions & 0 deletions .changeset/blue-bobcats-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@astrojs/preact": minor
---

Allows rendering lazy components.

You can now use [lazy components](https://preactjs.com/guide/v10/switching-to-preact/#suspense-experimental) with Suspense:

``` jsx
import { lazy, Suspense } from 'preact/compat';

const HeavyComponent= lazy(() => import('./HeavyComponent'));

const Component = () => {
return (
<Suspense fallback={<p>Loading...</p>}>
<HeavyComponent foo="bar" />
</Suspense>
);
};
```
4 changes: 0 additions & 4 deletions examples/framework-preact/src/components/Counter.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,3 @@
margin-top: 2em;
place-items: center;
}

.counter-message {
text-align: center;
}
8 changes: 7 additions & 1 deletion examples/framework-preact/src/components/Counter.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { h, Fragment } from 'preact';
import { lazy, Suspense } from 'preact/compat';
import './Counter.css';

const Message = lazy(async () => import('./Message'));
const Fallback = () => <p>Loading...</p>;

export default function Counter({ children, count }) {
const add = () => count.value++;
const subtract = () => count.value--;
Expand All @@ -12,7 +16,9 @@ export default function Counter({ children, count }) {
<pre>{count}</pre>
<button onClick={add}>+</button>
</div>
<div class="counter-message">{children}</div>
<Suspense fallback={Fallback}>
<Message>{children}</Message>
</Suspense>
</>
);
}
3 changes: 3 additions & 0 deletions examples/framework-preact/src/components/Message.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.message {
text-align: center;
}
5 changes: 5 additions & 0 deletions examples/framework-preact/src/components/Message.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import './Message.css';

export default function Message({ children }) {
return <div class="message">{children}</div>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from 'astro/config';
import preact from '@astrojs/preact';
import mdx from '@astrojs/mdx';

// https://astro.build/config
export default defineConfig({
integrations: [preact(), mdx()],
});
11 changes: 11 additions & 0 deletions packages/astro/e2e/fixtures/preact-lazy-component/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "@e2e/preact-lazy-component",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/mdx": "workspace:*",
"@astrojs/preact": "workspace:*",
"astro": "workspace:*",
"preact": "^10.15.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.counter {
display: grid;
font-size: 2em;
grid-template-columns: repeat(3, minmax(0, 1fr));
margin-top: 2em;
place-items: center;
}

.counter-message {
text-align: center;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { h, Fragment } from 'preact';
import { useState } from 'preact/hooks';
import { Suspense, lazy } from 'preact/compat';
import './Counter.css';

const LazyCounterMessage = lazy(() => import('./CounterMessage'))

export default function Counter({ children, count: initialCount, id }) {
const [count, setCount] = useState(initialCount);
const add = () => setCount((i) => i + 1);
const subtract = () => setCount((i) => i - 1);

return (
<>
<div id={id} className="counter">
<button className="decrement" onClick={subtract}>-</button>
<pre>{count}</pre>
<button className="increment" onClick={add}>+</button>
</div>
<Suspense fallback={<p>Load message...</p>}>
<LazyCounterMessage className="counter-message">{children}</LazyCounterMessage>
</Suspense>
</>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const CounterMessage = (props) => {
return <div className={props.className}>{props.children}</div>
}

export default CounterMessage
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { h } from 'preact';

export default function({ id }) {
return <div id={id}>Framework client:only component</div>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<html>
<head><title>Preact component</title></head>
<body><slot></slot></body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
import Counter from '../components/Counter.jsx';
import PreactComponent from '../components/JSXComponent.jsx';
const someProps = {
count: 0,
};
---

<html>
<head>
<!-- Head Stuff -->
</head>
<body>
<Counter id="server-only" {...someProps}>
<h1>Hello, server!</h1>
</Counter>

<Counter id="client-idle" {...someProps} client:idle>
<h1>Hello, client:idle!</h1>
</Counter>

<Counter id="client-load" {...someProps} client:load>
<h1>Hello, client:load!</h1>
</Counter>

<Counter id="client-visible" {...someProps} client:visible>
<h1>Hello, client:visible!</h1>
</Counter>

<Counter id="client-media" {...someProps} client:media="(max-width: 50em)">
<h1>Hello, client:media!</h1>
</Counter>

<PreactComponent id="client-only" client:only="preact" />
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export { default } from '../components/Layout.astro';
import Counter from '../components/Counter.jsx';
import PreactComponent from '../components/JSXComponent.jsx';

export const someProps = {
count: 0,
};

<Counter id="server-only" {...someProps}>
# Hello, server!
</Counter>

<Counter id="client-idle" {...someProps} client:idle>
# Hello, client:idle!
</Counter>

<Counter id="client-load" {...someProps} client:load>
# Hello, client:load!
</Counter>

<Counter id="client-visible" {...someProps} client:visible>
# Hello, client:visible!
</Counter>

<Counter id="client-media" {...someProps} client:media="(max-width: 50em)">
# Hello, client:media!
</Counter>

<PreactComponent id="client-only" client:only="preact" />
24 changes: 24 additions & 0 deletions packages/astro/e2e/preact-lazy-component.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { prepareTestFactory } from './shared-component-tests.js';

const { test, createTests } = prepareTestFactory({ root: './fixtures/preact-lazy-component/' });

const config = {
counterComponentFilePath: './src/components/Counter.jsx',
componentFilePath: './src/components/JSXComponent.jsx',
};

test.describe('Preact lazy components in Astro files', () => {
createTests({
...config,
pageUrl: '/',
pageSourceFilePath: './src/pages/index.astro',
});
});

test.describe('Preact lazy components in MDX files', () => {
createTests({
...config,
pageUrl: '/mdx/',
pageSourceFilePath: './src/pages/mdx.mdx',
});
});
3 changes: 2 additions & 1 deletion packages/integrations/preact/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"@preact/preset-vite": "^2.7.0",
"@preact/signals": "^1.2.1",
"babel-plugin-transform-hook-names": "^1.0.2",
"preact-render-to-string": "^6.3.1"
"preact-render-to-string": "^6.3.1",
"preact-ssr-prepass": "^1.2.1"
},
"devDependencies": {
"astro": "workspace:*",
Expand Down
37 changes: 18 additions & 19 deletions packages/integrations/preact/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AstroComponentMetadata } from 'astro';
import { Component as BaseComponent, h, type VNode } from 'preact';
import prepass from "preact-ssr-prepass";
import { render } from 'preact-render-to-string';
import { getContext } from './context.js';
import { restoreSignalsOnProps, serializeSignals } from './signals.js';
Expand All @@ -11,7 +12,7 @@ const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w
let originalConsoleError: typeof console.error;
let consoleFilterRefs = 0;

function check(this: RendererContext, Component: any, props: Record<string, any>, children: any) {
async function check(this: RendererContext, Component: any, props: Record<string, any>, children: any) {
if (typeof Component !== 'function') return false;
if (Component.name === 'QwikComponent') return false;

Expand All @@ -23,7 +24,7 @@ function check(this: RendererContext, Component: any, props: Record<string, any>

try {
try {
const { html } = renderToStaticMarkup.call(this, Component, props, children, undefined);
const { html } = await renderToStaticMarkup.call(this, Component, props, children, undefined);
if (typeof html !== 'string') {
return false;
}
Expand All @@ -45,7 +46,7 @@ function shouldHydrate(metadata: AstroComponentMetadata | undefined) {
return metadata?.astroStaticSlot ? !!metadata.hydrate : true;
}

function renderToStaticMarkup(
async function renderToStaticMarkup(
this: RendererContext,
Component: any,
props: Record<string, any>,
Expand All @@ -72,22 +73,20 @@ function renderToStaticMarkup(
const attrs: AstroPreactAttrs = {};
serializeSignals(ctx, props, attrs, propsMap);

const html = render(
h(
Component,
newProps,
children != null
? h(StaticHtml, {
hydrate: shouldHydrate(metadata),
value: children,
})
: children
) as VNode<any>
);
return {
attrs,
html,
};
const vNode: VNode<any> = h(
Component,
newProps,
children != null
? h(StaticHtml, {
hydrate: shouldHydrate(metadata),
value: children,
})
: children
)

await prepass(vNode)
const html = render(vNode);
return { attrs, html };
}

/**
Expand Down
Loading

0 comments on commit 0903ef9

Please sign in to comment.