diff --git a/.changeset/lost-days-sick.md b/.changeset/lost-days-sick.md new file mode 100644 index 0000000000..6e4bb7b5fe --- /dev/null +++ b/.changeset/lost-days-sick.md @@ -0,0 +1,24 @@ +--- +"@patternfly/pfe-core": minor +--- + +`ssrCallConnectedCallback`: filter which elements receive `connectedCallback` during SSR. + +Importing `ssr-shims.js`, or calling `ssrCallConnectedCallback()` with no options, keeps the previous behavior: every element opts in through the same `globalThis.litSsrCallConnectedCallback` flag earlier versions set, and this module adds nothing to `LitElementRenderer.renderOptions`. Existing `renderOptions` configuration (such as `disableSsr`) therefore keeps its order and precedence. + +Call `ssrCallConnectedCallback` with `include` and/or `exclude` predicates to restrict the set. Filtering clears the legacy flag (Lit ORs it with `renderOptions`, so it would otherwise override the filter) and registers a single `renderOptions` entry. `exclude` takes precedence when an element matches both: + +```typescript +import { ssrCallConnectedCallback } from '@patternfly/pfe-core/ssr-shims.js'; + +ssrCallConnectedCallback({ + include: el => el.localName.startsWith('pf-') || el.localName.startsWith('rh-'), + exclude: el => el.localName === 'pf-icon', +}); +``` + +To opt out entirely, exclude every element: + +```typescript +ssrCallConnectedCallback({ exclude: () => true }); +``` diff --git a/.changeset/poor-sky-blue.md b/.changeset/poor-sky-blue.md new file mode 100644 index 0000000000..12d97958c7 --- /dev/null +++ b/.changeset/poor-sky-blue.md @@ -0,0 +1,15 @@ +--- +"@patternfly/pfe-tools": minor +--- + +`renderGlobal`: third `connectedCallbackOptions` parameter limits which elements receive `connectedCallback` during SSR. Without it, all elements opt in exactly as before, and existing `LitElementRenderer.renderOptions` configuration keeps its order and precedence. + +```typescript +import { renderGlobal } from '@patternfly/pfe-tools/ssr/global.js'; + +const html = await renderGlobal( + '', + ['my-package/my-el.js'], + { include: el => el.localName.startsWith('my-') }, +); +``` diff --git a/core/pfe-core/ssr-shims.ts b/core/pfe-core/ssr-shims.ts index 32d0168960..369b77a414 100644 --- a/core/pfe-core/ssr-shims.ts +++ b/core/pfe-core/ssr-shims.ts @@ -1,4 +1,5 @@ import { installWindowOnGlobal } from '@lit-labs/ssr/lib/dom-shim.js'; +import { LitElementRenderer } from '@lit-labs/ssr/lib/lit-element-renderer.js'; class ObserverShim { observe(): void { @@ -30,8 +31,113 @@ function getComputedStyle() { }; }; -// @ts-expect-error: opt in to event support in ssr -globalThis.litSsrCallConnectedCallback = true; +type RenderOption = (typeof LitElementRenderer.renderOptions)[number]; + +type ElementPredicate = (element: { localName: string }) => boolean; + +/** Options for {@link ssrCallConnectedCallback}. */ +export interface SsrCallConnectedCallbackOptions { + /** + * Return true for elements that should receive `connectedCallback` during SSR. + * @default () => true + */ + include?: ElementPredicate; + + /** + * Return true for elements that should not receive `connectedCallback` during SSR. + * Takes precedence over {@link include}. + * @default () => false + */ + exclude?: ElementPredicate; +} + +/** Callback this module last registered on `LitElementRenderer.renderOptions`. */ +let registered: RenderOption | undefined; + +/** + * Set the legacy global flag Lit reads to opt every element in. + * Assigning through this helper keeps the property typed without augmenting + * the global type for consumers. + * @param value whether every element opts in + */ +function setLegacyConnectedCallbackFlag(value: boolean): void { + (globalThis as typeof globalThis & { litSsrCallConnectedCallback?: boolean }) + .litSsrCallConnectedCallback = value; +} + +/** + * Opt elements into `connectedCallback` during SSR. + * + * Called with no options, this keeps the previous behavior: every element + * receives `connectedCallback`. It does so through the same + * `globalThis.litSsrCallConnectedCallback` flag earlier versions set, and adds + * nothing to `LitElementRenderer.renderOptions`, so existing `renderOptions` + * configuration (such as `disableSsr`) keeps its order and precedence. + * + * Called with options, it filters which elements receive `connectedCallback`. + * The legacy global is cleared because Lit ORs it with `renderOptions`, so it + * would otherwise override the filter. A later call replaces this module's + * option in place, since Lit evaluates `renderOptions` first-match and a second + * push would never restrict the set. + * + * Elements matched by `exclude` never receive `connectedCallback` from this + * module, even when `include` also matches them. + * + * @example Restrict the opt-in to PatternFly and Red Hat elements + * ```ts + * ssrCallConnectedCallback({ + * include: el => el.localName.startsWith('pf-') || el.localName.startsWith('rh-'), + * exclude: el => el.localName === 'pf-icon', + * }); + * ``` + * @example Opt out entirely + * ```ts + * ssrCallConnectedCallback({ exclude: () => true }); + * ``` + * @param options which elements receive `connectedCallback`. Omit to opt every + * element in, as previous versions did. + */ +export function ssrCallConnectedCallback( + options?: SsrCallConnectedCallbackOptions, +): void { + if (options === undefined) { + // Preserve the pre-filter behavior exactly: the legacy global opts every + // element in and renderOptions is left untouched. + setLegacyConnectedCallbackFlag(true); + if (registered) { + const index = LitElementRenderer.renderOptions.indexOf(registered); + if (index !== -1) { + LitElementRenderer.renderOptions.splice(index, 1); + } + registered = undefined; + } + return; + } + + const include = options.include ?? (() => true); + const exclude = options.exclude ?? (() => false); + const option: RenderOption = element => + include(element) && !exclude(element) ? { connectedCallback: true } : undefined; + + // Lit checks the legacy global before renderOptions; clear it so the filter + // can actually narrow the set. + setLegacyConnectedCallbackFlag(false); + + if (registered) { + const index = LitElementRenderer.renderOptions.indexOf(registered); + if (index !== -1) { + LitElementRenderer.renderOptions[index] = option; + registered = option; + return; + } + } + + registered = option; + LitElementRenderer.renderOptions.push(option); +} + +// Preserve the behavior of importing this module: opt every element in. +ssrCallConnectedCallback(); installWindowOnGlobal({ ErrorEvent: Event, diff --git a/package-lock.json b/package-lock.json index e6e5f2b58b..962b137401 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1906,14 +1906,14 @@ } }, "node_modules/@lit-labs/ssr": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@lit-labs/ssr/-/ssr-4.0.0.tgz", - "integrity": "sha512-pODr+t7cZVIrCRLuSLuWAACDnztEk5IrRFwFsbxyAyWcP2XP8aKuUZdVM/biXqxvIyHyCKtNZ92Gdcr+pjA5BQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr/-/ssr-4.1.0.tgz", + "integrity": "sha512-m0zymVVlHB1ddJQ1lastsV8ROW3whFOiHJhVPQWd04MnGTkTlUUVLQctux1QlyD9BtLXNN6iASxv388vhgKMFg==", "license": "BSD-3-Clause", "peer": true, "dependencies": { "@lit-labs/ssr-client": "^1.1.7", - "@lit-labs/ssr-dom-shim": "^1.5.0", + "@lit-labs/ssr-dom-shim": "^1.6.0", "@lit/reactive-element": "^2.0.4", "@parse5/tools": "^0.3.0", "enhanced-resolve": "^5.10.0", @@ -1948,9 +1948,9 @@ } }, "node_modules/@lit-labs/ssr-dom-shim": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.5.1.tgz", - "integrity": "sha512-Aou5UdlSpr5whQe8AA/bZG0jMj96CoJIWbGfZ91qieWu5AWUMKw8VR/pAkQkJYvBNhmCcWnZlyyk5oze8JIqYA==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", + "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", "license": "BSD-3-Clause" }, "node_modules/@lit/context": { @@ -16022,7 +16022,7 @@ "@11ty/eleventy-plugin-syntaxhighlight": "^5.0.2", "@changesets/cli": "^2.29.8", "@koa/router": "^15.1.1", - "@lit-labs/ssr": "^4.0.0", + "@lit-labs/ssr": "^4.1.0", "@open-wc/testing": "^4.0.0", "@playwright/test": "~1.57.0", "@pwrs/mappa": "^0.0.4", diff --git a/tools/pfe-tools/package.json b/tools/pfe-tools/package.json index 9951194275..c604a1514b 100644 --- a/tools/pfe-tools/package.json +++ b/tools/pfe-tools/package.json @@ -68,7 +68,7 @@ "@11ty/eleventy-plugin-syntaxhighlight": "^5.0.2", "@changesets/cli": "^2.29.8", "@koa/router": "^15.1.1", - "@lit-labs/ssr": "^4.0.0", + "@lit-labs/ssr": "^4.1.0", "@open-wc/testing": "^4.0.0", "@playwright/test": "~1.57.0", "@pwrs/mappa": "^0.0.4", diff --git a/tools/pfe-tools/ssr/global.ts b/tools/pfe-tools/ssr/global.ts index eecb84a620..34685bce28 100644 --- a/tools/pfe-tools/ssr/global.ts +++ b/tools/pfe-tools/ssr/global.ts @@ -3,14 +3,34 @@ * first importing the provided component defintions into nodejs' global scope. * @param html string to render * @param importSpecifiers list of web component definition module import specifiers + * @param connectedCallbackOptions which elements receive `connectedCallback` + * during SSR. Defaults to all elements, matching previous behavior and + * leaving existing `LitElementRenderer.renderOptions` configuration intact. + * @param connectedCallbackOptions.include return true for elements that should receive `connectedCallback` + * @param connectedCallbackOptions.exclude return true for elements that should not receive `connectedCallback` + * @example Call `connectedCallback` only for elements whose tag starts with `my-` + * ```ts + * await renderGlobal(html, ['my-package/my-el.js'], { + * include: el => el.localName.startsWith('my-'), + * }); + * ``` + * @example Opt out entirely + * ```ts + * await renderGlobal(html, ['my-package/my-el.js'], { exclude: () => true }); + * ``` */ export async function renderGlobal( html: string, importSpecifiers: string[], + connectedCallbackOptions?: { + include?: (element: { localName: string }) => boolean; + exclude?: (element: { localName: string }) => boolean; + }, ): Promise { // hack to avoid circular typescript project reference const spec = '@patternfly/pfe-core/ssr-shims.js'; - await import(spec); + const { ssrCallConnectedCallback } = await import(spec); + ssrCallConnectedCallback(connectedCallbackOptions); const { ssr } = await import('./ssr.js'); await Promise.all(importSpecifiers.map(x => import(x))); return ssr(html);