declare global { // eslint-disable-next-line @typescript-eslint/naming-convention var __mfeStyles__: Record | undefined; } type StyleRoot = ShadowRoot | Document; export class MfeStyleRegistry { readonly sheets = new Map(); readonly roots = new Set(); // Per-component state stored on globalThis.__mfeStyles__ so it survives Vite HMR module reloads. static for(componentName: string): MfeStyleRegistry { globalThis.__mfeStyles__ ??= {}; globalThis.__mfeStyles__[componentName] ??= new MfeStyleRegistry(); return globalThis.__mfeStyles__[componentName]; } injectSheet(sheetId: string, css: string) { let sheet = this.sheets.get(sheetId); if (sheet) { sheet.replaceSync(css); } else { sheet = new CSSStyleSheet(); sheet.replaceSync(css); this.sheets.set(sheetId, sheet); for (const root of this.roots) { root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet]; } } } observeRoot(root: StyleRoot) { if (this.roots.has(root)) { return; } this.roots.add(root); root.adoptedStyleSheets ??= []; root.adoptedStyleSheets = [...root.adoptedStyleSheets, ...this.sheets.values()]; } unobserveRoot(root: StyleRoot) { this.roots.delete(root); const sheets = new Set(this.sheets.values()); root.adoptedStyleSheets ??= []; root.adoptedStyleSheets = root.adoptedStyleSheets.filter(s => !sheets.has(s)); } }