summaryrefslogtreecommitdiff
path: root/packages/integrations/preact/src
diff options
context:
space:
mode:
Diffstat (limited to 'packages/integrations/preact/src')
-rw-r--r--packages/integrations/preact/src/client-dev.ts4
-rw-r--r--packages/integrations/preact/src/client.ts61
-rw-r--r--packages/integrations/preact/src/context.ts32
-rw-r--r--packages/integrations/preact/src/index.ts88
-rw-r--r--packages/integrations/preact/src/server.ts153
-rw-r--r--packages/integrations/preact/src/signals.ts88
-rw-r--r--packages/integrations/preact/src/static-html.ts31
-rw-r--r--packages/integrations/preact/src/types.ts18
8 files changed, 475 insertions, 0 deletions
diff --git a/packages/integrations/preact/src/client-dev.ts b/packages/integrations/preact/src/client-dev.ts
new file mode 100644
index 000000000..d37e6e0af
--- /dev/null
+++ b/packages/integrations/preact/src/client-dev.ts
@@ -0,0 +1,4 @@
+import 'preact/debug';
+import clientFn from './client.js';
+
+export default clientFn;
diff --git a/packages/integrations/preact/src/client.ts b/packages/integrations/preact/src/client.ts
new file mode 100644
index 000000000..32fdc9888
--- /dev/null
+++ b/packages/integrations/preact/src/client.ts
@@ -0,0 +1,61 @@
+import { h, hydrate, render } from 'preact';
+import StaticHtml from './static-html.js';
+import type { SignalLike } from './types.js';
+
+const sharedSignalMap = new Map<string, SignalLike>();
+
+export default (element: HTMLElement) =>
+ async (
+ Component: any,
+ props: Record<string, any>,
+ { default: children, ...slotted }: Record<string, any>,
+ { client }: Record<string, string>,
+ ) => {
+ if (!element.hasAttribute('ssr')) return;
+ for (const [key, value] of Object.entries(slotted)) {
+ props[key] = h(StaticHtml, { value, name: key });
+ }
+ let signalsRaw = element.dataset.preactSignals;
+ if (signalsRaw) {
+ const { signal } = await import('@preact/signals');
+ let signals: Record<string, string | [string, number][]> = JSON.parse(
+ element.dataset.preactSignals!,
+ );
+ for (const [propName, signalId] of Object.entries(signals)) {
+ if (Array.isArray(signalId)) {
+ signalId.forEach(([id, indexOrKeyInProps]) => {
+ const mapValue = props[propName][indexOrKeyInProps];
+ let valueOfSignal = mapValue;
+
+ // not an property key
+ if (typeof indexOrKeyInProps !== 'string') {
+ valueOfSignal = mapValue[0];
+ indexOrKeyInProps = mapValue[1];
+ }
+
+ if (!sharedSignalMap.has(id)) {
+ const signalValue = signal(valueOfSignal);
+ sharedSignalMap.set(id, signalValue);
+ }
+ props[propName][indexOrKeyInProps] = sharedSignalMap.get(id);
+ });
+ } else {
+ if (!sharedSignalMap.has(signalId)) {
+ const signalValue = signal(props[propName]);
+ sharedSignalMap.set(signalId, signalValue);
+ }
+ props[propName] = sharedSignalMap.get(signalId);
+ }
+ }
+ }
+
+ const bootstrap = client !== 'only' ? hydrate : render;
+
+ bootstrap(
+ h(Component, props, children != null ? h(StaticHtml, { value: children }) : children),
+ element,
+ );
+
+ // Preact has no "unmount" option, but you can use `render(null, element)`
+ element.addEventListener('astro:unmount', () => render(null, element), { once: true });
+ };
diff --git a/packages/integrations/preact/src/context.ts b/packages/integrations/preact/src/context.ts
new file mode 100644
index 000000000..4d2398d28
--- /dev/null
+++ b/packages/integrations/preact/src/context.ts
@@ -0,0 +1,32 @@
+import type { PropNameToSignalMap, RendererContext, SignalLike } from './types.js';
+
+export type Context = {
+ id: string;
+ c: number;
+ signals: Map<SignalLike, string>;
+ propsToSignals: Map<Record<string, any>, PropNameToSignalMap>;
+};
+
+const contexts = new WeakMap<RendererContext['result'], Context>();
+
+export function getContext(result: RendererContext['result']): Context {
+ if (contexts.has(result)) {
+ return contexts.get(result)!;
+ }
+ let ctx = {
+ c: 0,
+ get id() {
+ return 'p' + this.c.toString();
+ },
+ signals: new Map(),
+ propsToSignals: new Map(),
+ };
+ contexts.set(result, ctx);
+ return ctx;
+}
+
+export function incrementId(ctx: Context): string {
+ let id = ctx.id;
+ ctx.c++;
+ return id;
+}
diff --git a/packages/integrations/preact/src/index.ts b/packages/integrations/preact/src/index.ts
new file mode 100644
index 000000000..fd16a9e4a
--- /dev/null
+++ b/packages/integrations/preact/src/index.ts
@@ -0,0 +1,88 @@
+import { fileURLToPath } from 'node:url';
+import { type PreactPluginOptions as VitePreactPluginOptions, preact } from '@preact/preset-vite';
+import type { AstroIntegration, AstroRenderer, ContainerRenderer, ViteUserConfig } from 'astro';
+
+const babelCwd = new URL('../', import.meta.url);
+
+function getRenderer(development: boolean): AstroRenderer {
+ return {
+ name: '@astrojs/preact',
+ clientEntrypoint: development ? '@astrojs/preact/client-dev.js' : '@astrojs/preact/client.js',
+ serverEntrypoint: '@astrojs/preact/server.js',
+ };
+}
+
+export function getContainerRenderer(): ContainerRenderer {
+ return {
+ name: '@astrojs/preact',
+ serverEntrypoint: '@astrojs/preact/server.js',
+ };
+}
+
+export interface Options extends Pick<VitePreactPluginOptions, 'include' | 'exclude'> {
+ compat?: boolean;
+ devtools?: boolean;
+}
+
+export default function ({ include, exclude, compat, devtools }: Options = {}): AstroIntegration {
+ return {
+ name: '@astrojs/preact',
+ hooks: {
+ 'astro:config:setup': ({ addRenderer, updateConfig, command, injectScript }) => {
+ const preactPlugin = preact({
+ reactAliasesEnabled: compat ?? false,
+ include,
+ exclude,
+ babel: {
+ cwd: fileURLToPath(babelCwd),
+ },
+ });
+
+ const viteConfig: ViteUserConfig = {
+ optimizeDeps: {
+ include: ['@astrojs/preact/client.js', 'preact', 'preact/jsx-runtime'],
+ exclude: ['@astrojs/preact/server.js'],
+ },
+ };
+
+ if (compat) {
+ viteConfig.optimizeDeps!.include!.push(
+ 'preact/compat',
+ 'preact/test-utils',
+ 'preact/compat/jsx-runtime',
+ );
+ viteConfig.resolve = {
+ dedupe: ['preact/compat', 'preact'],
+ };
+ // noExternal React entrypoints to be bundled, resolved, and aliased by Vite
+ viteConfig.ssr = {
+ noExternal: ['react', 'react-dom', 'react-dom/test-utils', 'react/jsx-runtime'],
+ };
+ }
+
+ viteConfig.plugins = [preactPlugin];
+
+ addRenderer(getRenderer(command === 'dev'));
+ updateConfig({
+ vite: viteConfig,
+ });
+
+ if (command === 'dev' && devtools) {
+ injectScript('page', 'import "preact/debug";');
+ }
+ },
+ 'astro:config:done': ({ logger, config }) => {
+ const knownJsxRenderers = ['@astrojs/react', '@astrojs/preact', '@astrojs/solid-js'];
+ const enabledKnownJsxRenderers = config.integrations.filter((renderer) =>
+ knownJsxRenderers.includes(renderer.name),
+ );
+
+ if (enabledKnownJsxRenderers.length > 1 && !include && !exclude) {
+ logger.warn(
+ 'More than one JSX renderer is enabled. This will lead to unexpected behavior unless you set the `include` or `exclude` option. See https://docs.astro.build/en/guides/integrations-guide/preact/#combining-multiple-jsx-frameworks for more information.',
+ );
+ }
+ },
+ },
+ };
+}
diff --git a/packages/integrations/preact/src/server.ts b/packages/integrations/preact/src/server.ts
new file mode 100644
index 000000000..5b38ff590
--- /dev/null
+++ b/packages/integrations/preact/src/server.ts
@@ -0,0 +1,153 @@
+import type { AstroComponentMetadata, NamedSSRLoadedRendererValue } from 'astro';
+import { Component as BaseComponent, type VNode, h } from 'preact';
+import { renderToStringAsync } from 'preact-render-to-string';
+import { getContext } from './context.js';
+import { restoreSignalsOnProps, serializeSignals } from './signals.js';
+import StaticHtml from './static-html.js';
+import type { AstroPreactAttrs, RendererContext } from './types.js';
+
+const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
+
+let originalConsoleError: typeof console.error;
+let consoleFilterRefs = 0;
+
+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;
+
+ if (Component.prototype != null && typeof Component.prototype.render === 'function') {
+ return BaseComponent.isPrototypeOf(Component);
+ }
+
+ useConsoleFilter();
+
+ try {
+ const { html } = await renderToStaticMarkup.call(this, Component, props, children, undefined);
+ if (typeof html !== 'string') {
+ return false;
+ }
+
+ // There are edge cases (SolidJS) where Preact *might* render a string,
+ // but components would be <undefined></undefined>
+ // It also might render an empty sting.
+ return html == '' ? false : !html.includes('<undefined>');
+ } catch {
+ return false;
+ } finally {
+ finishUsingConsoleFilter();
+ }
+}
+
+function shouldHydrate(metadata: AstroComponentMetadata | undefined) {
+ // Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
+ return metadata?.astroStaticSlot ? !!metadata.hydrate : true;
+}
+
+async function renderToStaticMarkup(
+ this: RendererContext,
+ Component: any,
+ props: Record<string, any>,
+ { default: children, ...slotted }: Record<string, any>,
+ metadata: AstroComponentMetadata | undefined,
+) {
+ const ctx = getContext(this.result);
+
+ const slots: Record<string, ReturnType<typeof h>> = {};
+ for (const [key, value] of Object.entries(slotted)) {
+ const name = slotName(key);
+ slots[name] = h(StaticHtml, {
+ hydrate: shouldHydrate(metadata),
+ value,
+ name,
+ }) as VNode<any>;
+ }
+
+ // Restore signals back onto props so that they will be passed as-is to components
+ let propsMap = restoreSignalsOnProps(ctx, props);
+
+ const newProps = { ...props, ...slots };
+
+ const attrs: AstroPreactAttrs = {};
+ serializeSignals(ctx, props, attrs, propsMap);
+
+ const vNode: VNode<any> = h(
+ Component,
+ newProps,
+ children != null
+ ? h(StaticHtml, {
+ hydrate: shouldHydrate(metadata),
+ value: children,
+ })
+ : children,
+ );
+
+ const html = await renderToStringAsync(vNode);
+ return { attrs, html };
+}
+
+/**
+ * Reduces console noise by filtering known non-problematic errors.
+ *
+ * Performs reference counting to allow parallel usage from async code.
+ *
+ * To stop filtering, please ensure that there always is a matching call
+ * to `finishUsingConsoleFilter` afterwards.
+ */
+function useConsoleFilter() {
+ consoleFilterRefs++;
+
+ if (!originalConsoleError) {
+ originalConsoleError = console.error;
+
+ try {
+ console.error = filteredConsoleError;
+ } catch {
+ // If we're unable to hook `console.error`, just accept it
+ }
+ }
+}
+
+/**
+ * Indicates that the filter installed by `useConsoleFilter`
+ * is no longer needed by the calling code.
+ */
+function finishUsingConsoleFilter() {
+ consoleFilterRefs--;
+
+ // Note: Instead of reverting `console.error` back to the original
+ // when the reference counter reaches 0, we leave our hook installed
+ // to prevent potential race conditions once `check` is made async
+}
+
+/**
+ * Hook/wrapper function for the global `console.error` function.
+ *
+ * Ignores known non-problematic errors while any code is using the console filter.
+ * Otherwise, simply forwards all arguments to the original function.
+ */
+function filteredConsoleError(msg: string, ...rest: any[]) {
+ if (consoleFilterRefs > 0 && typeof msg === 'string') {
+ // In `check`, we attempt to render JSX components through Preact.
+ // When attempting this on a React component, React may output
+ // the following error, which we can safely filter out:
+ const isKnownReactHookError =
+ msg.includes('Warning: Invalid hook call.') &&
+ msg.includes('https://reactjs.org/link/invalid-hook-call');
+ if (isKnownReactHookError) return;
+ }
+ originalConsoleError(msg, ...rest);
+}
+
+const renderer: NamedSSRLoadedRendererValue = {
+ name: '@astrojs/preact',
+ check,
+ renderToStaticMarkup,
+ supportsAstroStaticSlot: true,
+};
+
+export default renderer;
diff --git a/packages/integrations/preact/src/signals.ts b/packages/integrations/preact/src/signals.ts
new file mode 100644
index 000000000..88a50327a
--- /dev/null
+++ b/packages/integrations/preact/src/signals.ts
@@ -0,0 +1,88 @@
+import type { Context } from './context.js';
+import { incrementId } from './context.js';
+import type {
+ ArrayObjectMapping,
+ AstroPreactAttrs,
+ PropNameToSignalMap,
+ SignalLike,
+ SignalToKeyOrIndexMap,
+ Signals,
+} from './types.js';
+
+function isSignal(x: any): x is SignalLike {
+ return x != null && typeof x === 'object' && typeof x.peek === 'function' && 'value' in x;
+}
+
+export function restoreSignalsOnProps(ctx: Context, props: Record<string, any>) {
+ // Restore signal props that were mutated for serialization
+ let propMap: PropNameToSignalMap;
+ if (ctx.propsToSignals.has(props)) {
+ propMap = ctx.propsToSignals.get(props)!;
+ } else {
+ propMap = new Map();
+ ctx.propsToSignals.set(props, propMap);
+ }
+ for (const [key, signal] of propMap) {
+ props[key] = signal;
+ }
+ return propMap;
+}
+
+export function serializeSignals(
+ ctx: Context,
+ props: Record<string, any>,
+ attrs: AstroPreactAttrs,
+ map: PropNameToSignalMap,
+) {
+ // Check for signals
+ const signals: Signals = {};
+ for (const [key, value] of Object.entries(props)) {
+ const isPropArray = Array.isArray(value);
+ // `typeof null` is 'object' in JS, so we need to check for `null` specifically
+ const isPropObject =
+ !isSignal(value) && typeof props[key] === 'object' && props[key] !== null && !isPropArray;
+
+ if (isPropObject || isPropArray) {
+ const values = isPropObject ? Object.keys(props[key]) : value;
+ values.forEach((valueKey: number | string, valueIndex: number) => {
+ const signal = isPropObject ? props[key][valueKey] : valueKey;
+ if (isSignal(signal)) {
+ const keyOrIndex = isPropObject ? valueKey.toString() : valueIndex;
+
+ props[key] = isPropObject
+ ? Object.assign({}, props[key], { [keyOrIndex]: signal.peek() })
+ : props[key].map((v: SignalLike, i: number) =>
+ i === valueIndex ? [signal.peek(), i] : v,
+ );
+
+ const currentMap = (map.get(key) || []) as SignalToKeyOrIndexMap;
+ map.set(key, [...currentMap, [signal, keyOrIndex]]);
+
+ const currentSignals = (signals[key] || []) as ArrayObjectMapping;
+ signals[key] = [...currentSignals, [getSignalId(ctx, signal), keyOrIndex]];
+ }
+ });
+ } else if (isSignal(value)) {
+ // Set the value to the current signal value
+ // This mutates the props on purpose, so that it will be serialized correct.
+ props[key] = value.peek();
+ map.set(key, value);
+
+ signals[key] = getSignalId(ctx, value);
+ }
+ }
+
+ if (Object.keys(signals).length) {
+ attrs['data-preact-signals'] = JSON.stringify(signals);
+ }
+}
+
+function getSignalId(ctx: Context, item: SignalLike) {
+ let id = ctx.signals.get(item);
+ if (!id) {
+ id = incrementId(ctx);
+ ctx.signals.set(item, id);
+ }
+
+ return id;
+}
diff --git a/packages/integrations/preact/src/static-html.ts b/packages/integrations/preact/src/static-html.ts
new file mode 100644
index 000000000..453e72b7f
--- /dev/null
+++ b/packages/integrations/preact/src/static-html.ts
@@ -0,0 +1,31 @@
+import { h } from 'preact';
+
+type Props = {
+ value: string;
+ name?: string;
+ hydrate?: boolean;
+};
+
+/**
+ * Astro passes `children` as a string of HTML, so we need
+ * a wrapper `div` to render that content as VNodes.
+ *
+ * As a bonus, we can signal to Preact that this subtree is
+ * entirely static and will never change via `shouldComponentUpdate`.
+ */
+const StaticHtml = ({ value, name, hydrate = true }: Props) => {
+ if (!value) return null;
+ const tagName = hydrate ? 'astro-slot' : 'astro-static-slot';
+ return h(tagName, { name, dangerouslySetInnerHTML: { __html: value } });
+};
+
+/**
+ * This tells Preact to opt-out of re-rendering this subtree,
+ * In addition to being a performance optimization,
+ * this also allows other frameworks to attach to `children`.
+ *
+ * See https://preactjs.com/guide/v8/external-dom-mutations
+ */
+StaticHtml.shouldComponentUpdate = () => false;
+
+export default StaticHtml;
diff --git a/packages/integrations/preact/src/types.ts b/packages/integrations/preact/src/types.ts
new file mode 100644
index 000000000..e1c56ca30
--- /dev/null
+++ b/packages/integrations/preact/src/types.ts
@@ -0,0 +1,18 @@
+import type { SSRResult } from 'astro';
+export type RendererContext = {
+ result: SSRResult;
+};
+
+export type SignalLike = {
+ peek(): any;
+};
+
+export type ArrayObjectMapping = [string, number | string][];
+export type Signals = Record<string, string | ArrayObjectMapping>;
+
+export type SignalToKeyOrIndexMap = [SignalLike, number | string][];
+export type PropNameToSignalMap = Map<string, SignalLike | SignalToKeyOrIndexMap>;
+
+export type AstroPreactAttrs = {
+ ['data-preact-signals']?: string;
+};