Skip to content

Commit

Permalink
change(compare): Updated scoped style example
Browse files Browse the repository at this point in the history
  • Loading branch information
DeepDoge committed Nov 8, 2024
1 parent a1b32a7 commit 8250b2f
Showing 1 changed file with 20 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,35 @@ declare global {
}
}

export const css = String.raw;
export function css(...params: Parameters<typeof String.raw>) {
return new String(String.raw(...params));
}

export function sheet(css: string) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(css);
return sheet;
}

export function useScope(css: string): Lifecycle.OnConnected {
const scopedCssCache = new WeakMap<
String,
{ styleSheet: CSSStyleSheet; id: string }
>();
export function useScope(css: String): Lifecycle.OnConnected {
return (element) => {
if (element.dataset.scope) return;

const scopeId = Math.random().toString(36).slice(2);
document.adoptedStyleSheets.push(
sheet(
`@scope ([data-scope="${scopeId}"]) to ([data-scope] > *) {${css}}`,
),
);
element.dataset.scope = scopeId;
let cache = scopedCssCache.get(css);
if (!cache) {
const id = Math.random().toString(36).slice(2);
const styleSheet = sheet(
`@scope ([data-scope="${id}"]) to ([data-scope] > *) {${css}}`,
);
cache = { id, styleSheet };
scopedCssCache.set(css, cache);
}

element.dataset.scope = cache.id;
document.adoptedStyleSheets.push(cache.styleSheet);
};
}

0 comments on commit 8250b2f

Please sign in to comment.