From 6ea0b68d5927149d6544c4e70cbd97197b2bdeea Mon Sep 17 00:00:00 2001 From: Andrey Polischuk Date: Mon, 23 Sep 2024 13:55:59 +0300 Subject: [PATCH] feat(scoped-styles): add extract styles --- .size-limit.json | 2 +- packages/scoped-styles/index.test.ts | 10 +++++++++- packages/scoped-styles/index.ts | 17 +++++++++++++++++ packages/scoped-styles/style-sheet.ts | 4 ++++ 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/.size-limit.json b/.size-limit.json index 09e2c10..7192671 100644 --- a/.size-limit.json +++ b/.size-limit.json @@ -1,7 +1,7 @@ [ { "path": "packages/scoped-styles/dist/index.js", - "limit": "505 B" + "limit": "555 B" }, { "path": "packages/widget-element/dist/index.js", diff --git a/packages/scoped-styles/index.test.ts b/packages/scoped-styles/index.test.ts index c96062a..db6f249 100644 --- a/packages/scoped-styles/index.test.ts +++ b/packages/scoped-styles/index.test.ts @@ -1,4 +1,4 @@ -import {registerRoot, registerStyles, unregisterRoot} from '.' +import {registerRoot, registerStyles, unregisterRoot, extractStyles} from '.' import {sheetsRegistry} from './registry' test('append styles to document head', () => { @@ -56,6 +56,14 @@ test('register multiple roots for same sheets', () => { unregisterRoot(customRoot) }) +test('extract styles', () => { + const sheet = ':root { background-color: white; }' + + registerStyles(sheet) + + expect(extractStyles()).toEqual([sheet]) +}) + afterEach(() => { sheetsRegistry.clear() }) diff --git a/packages/scoped-styles/index.ts b/packages/scoped-styles/index.ts index a001be6..c2a2f9a 100644 --- a/packages/scoped-styles/index.ts +++ b/packages/scoped-styles/index.ts @@ -51,6 +51,23 @@ export function registerStyles(...sheets: string[]) { appendStyles(...rootsRegistry) } +/** + * Extract scoped style sheets as string + * + * ```tsx + * const styleSheets = extractStyles() + * + * styleSheets.forEach((sheetText) => { + * const style = document.createElement('style') + * style.textContent = sheetText + * document.head.append(style) + * }) + * ``` + */ +export function extractStyles() { + return Array.from(sheetsRegistry).map((sheet) => sheet.toString()) +} + /** * Register scoped root and inject styles * diff --git a/packages/scoped-styles/style-sheet.ts b/packages/scoped-styles/style-sheet.ts index 37ade8d..3eac83f 100644 --- a/packages/scoped-styles/style-sheet.ts +++ b/packages/scoped-styles/style-sheet.ts @@ -27,4 +27,8 @@ export class StyleSheet { this.registry.delete(root) } } + + toString() { + return this.content + } }