Skip to content

Commit

Permalink
feat(scoped-styles): add extract styles
Browse files Browse the repository at this point in the history
  • Loading branch information
andrepolischuk committed Sep 23, 2024
1 parent b66b939 commit 6ea0b68
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .size-limit.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[
{
"path": "packages/scoped-styles/dist/index.js",
"limit": "505 B"
"limit": "555 B"
},
{
"path": "packages/widget-element/dist/index.js",
Expand Down
10 changes: 9 additions & 1 deletion packages/scoped-styles/index.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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()
})
17 changes: 17 additions & 0 deletions packages/scoped-styles/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
4 changes: 4 additions & 0 deletions packages/scoped-styles/style-sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ export class StyleSheet {
this.registry.delete(root)
}
}

toString() {
return this.content
}
}

0 comments on commit 6ea0b68

Please sign in to comment.