UNPKG

@lwc/ssr-client-utils

Version:

Client-side complement to @lwc/ssr-compiler

59 lines (55 loc) 2.31 kB
/** * Copyright (c) 2025 Salesforce, Inc. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /* * Copyright (c) 2025, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ const stylesheetCache = new Map(); class StyleDeduplicator extends HTMLElement { connectedCallback() { const styleId = this.getAttribute('style-id'); if (!styleId) { throw new Error('"style-id" attribute must be supplied for <lwc-style> element'); } const root = this.getRootNode(); let stylesheet = stylesheetCache.get(styleId); if (stylesheet) { root.adoptedStyleSheets.push(stylesheet); const placeholder = document.createElement('style'); placeholder.setAttribute('type', 'text/css'); // Not-first <lwc-style> should be replaced with a placeholder <style>, since that's // what the diffing algorithm and hydration logic will expect to find this.replaceWith(placeholder); } else { stylesheet = new CSSStyleSheet(); const element = root.getElementById(styleId); if (!element) { throw new Error(`<lwc-style> tag found with no corresponding <style id="${styleId}"> tag`); } stylesheet.replaceSync(element.innerHTML); stylesheetCache.set(styleId, stylesheet); // The first <lwc-style> should be removed, because it already has a <style> next to it this.remove(); } } } /** * This function should be called in a <script> tag in the <head> * before server-rendered markup is encountered while parsing an HTML * document. This ensures that deduplicated styles will be in effect * for components that insert an <lwc-style> tag in place of a full * stylesheet. * It can also be implicitly invoked by importing `@lwc/ssr-client-utils/register-lwc-style` as a bare import. */ function registerLwcStyleComponent() { customElements.define('lwc-style', StyleDeduplicator); } exports.registerLwcStyleComponent = registerLwcStyleComponent; /** version: 8.20.0 */ //# sourceMappingURL=index.cjs.js.map