diff options
Diffstat (limited to 'packages/integrations/preact/src')
-rw-r--r-- | packages/integrations/preact/src/client-dev.ts | 5 | ||||
-rw-r--r-- | packages/integrations/preact/src/client.ts | 29 | ||||
-rw-r--r-- | packages/integrations/preact/src/context.ts | 32 | ||||
-rw-r--r-- | packages/integrations/preact/src/server.ts | 126 | ||||
-rw-r--r-- | packages/integrations/preact/src/signals.ts | 48 | ||||
-rw-r--r-- | packages/integrations/preact/src/static-html.ts | 24 | ||||
-rw-r--r-- | packages/integrations/preact/src/types.ts | 14 |
7 files changed, 278 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..9a9edcb3b --- /dev/null +++ b/packages/integrations/preact/src/client-dev.ts @@ -0,0 +1,5 @@ +// @ts-ignore +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..c7a31d60c --- /dev/null +++ b/packages/integrations/preact/src/client.ts @@ -0,0 +1,29 @@ +import type { SignalLike } from './types'; +import { h, render } from 'preact'; +import StaticHtml from './static-html.js'; + +const sharedSignalMap: Map<string, SignalLike> = new Map(); + +export default (element: HTMLElement) => + async (Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>) => { + 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> = JSON.parse(element.dataset.preactSignals as string); + for(const [propName, signalId] of Object.entries(signals)) { + if(!sharedSignalMap.has(signalId)) { + const signalValue = signal(props[propName]); + sharedSignalMap.set(signalId, signalValue); + } + props[propName] = sharedSignalMap.get(signalId); + } + } + render( + h(Component, props, children != null ? h(StaticHtml, { value: children }) : children), + element + ); + }; diff --git a/packages/integrations/preact/src/context.ts b/packages/integrations/preact/src/context.ts new file mode 100644 index 000000000..73c4402b0 --- /dev/null +++ b/packages/integrations/preact/src/context.ts @@ -0,0 +1,32 @@ +import type { RendererContext, SignalLike, PropNameToSignalMap } from './types'; + +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/server.ts b/packages/integrations/preact/src/server.ts new file mode 100644 index 000000000..2c1ac738a --- /dev/null +++ b/packages/integrations/preact/src/server.ts @@ -0,0 +1,126 @@ +import type { AstroPreactAttrs, RendererContext } from './types'; +import { h, Component as BaseComponent } from 'preact'; +import render from 'preact-render-to-string'; +import StaticHtml from './static-html.js'; +import { getContext } from './context.js'; +import { restoreSignalsOnProps, serializeSignals } from './signals.js'; + +const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase()); + +let originalConsoleError: typeof console.error; +let consoleFilterRefs = 0; + +function check(this: RendererContext, Component: any, props: Record<string, any>, children: any) { + if (typeof Component !== 'function') return false; + + if (Component.prototype != null && typeof Component.prototype.render === 'function') { + return BaseComponent.isPrototypeOf(Component); + } + + useConsoleFilter(); + + try { + try { + const { html } = renderToStaticMarkup.call(this, Component, props, children); + if (typeof html !== 'string') { + return false; + } + + // There are edge cases (SolidJS) where Preact *might* render a string, + // but components would be <undefined></undefined> + + return !/\<undefined\>/.test(html); + } catch (err) { + return false; + } + } finally { + finishUsingConsoleFilter(); + } +} + +function renderToStaticMarkup(this: RendererContext, Component: any, props: Record<string, any>, { default: children, ...slotted }: Record<string, any>) { + 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, { value, name }); + } + + // 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 html = render( + h(Component, newProps, children != null ? h(StaticHtml, { value: children }) : children) + ); + 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) { + // eslint-disable-next-line no-console + originalConsoleError = console.error; + + try { + // eslint-disable-next-line no-console + console.error = filteredConsoleError; + } catch (error) { + // 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); +} + +export default { + check, + renderToStaticMarkup, +}; diff --git a/packages/integrations/preact/src/signals.ts b/packages/integrations/preact/src/signals.ts new file mode 100644 index 000000000..db62961aa --- /dev/null +++ b/packages/integrations/preact/src/signals.ts @@ -0,0 +1,48 @@ +import type { AstroPreactAttrs, PropNameToSignalMap, SignalLike } from './types'; +import type { Context } from './context'; +import { incrementId } from './context.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: Record<string, string> = {}; + for(const [key, value] of Object.entries(props)) { + 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); + + let id: string; + if(ctx.signals.has(value)) { + id = ctx.signals.get(value)!; + } else { + id = incrementId(ctx); + ctx.signals.set(value, id); + } + signals[key] = id; + } + } + + if(Object.keys(signals).length) { + attrs['data-preact-signals'] = JSON.stringify(signals); + } +} diff --git a/packages/integrations/preact/src/static-html.ts b/packages/integrations/preact/src/static-html.ts new file mode 100644 index 000000000..e474caa5a --- /dev/null +++ b/packages/integrations/preact/src/static-html.ts @@ -0,0 +1,24 @@ +import { h } from 'preact'; + +/** + * 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 }: { value: string; name?: string; }) => { + if (!value) return null; + return h('astro-slot', { 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..e5058f5f3 --- /dev/null +++ b/packages/integrations/preact/src/types.ts @@ -0,0 +1,14 @@ +import type { SSRResult } from 'astro'; +export type RendererContext = { + result: SSRResult; +}; + +export type SignalLike = { + peek(): any; +}; + +export type PropNameToSignalMap = Map<string, SignalLike>; + +export type AstroPreactAttrs = { + ['data-preact-signals']?: string +}; |