From 1dee6885753e096b911b04597928d17928409ba6 Mon Sep 17 00:00:00 2001 From: Hans Vanderstraeten Date: Fri, 4 Jul 2025 18:34:15 +0200 Subject: [PATCH] fix createStyles to return constructable stylesheet --- packages/common/src/lib/create-styles.test.ts | 37 +++++++++++++++++++ packages/common/src/lib/create-styles.ts | 12 ++---- 2 files changed, 40 insertions(+), 9 deletions(-) create mode 100644 packages/common/src/lib/create-styles.test.ts diff --git a/packages/common/src/lib/create-styles.test.ts b/packages/common/src/lib/create-styles.test.ts new file mode 100644 index 0000000..2b30d49 --- /dev/null +++ b/packages/common/src/lib/create-styles.test.ts @@ -0,0 +1,37 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { createStyles } from './create-styles.js'; + +describe('createStyles', () => { + const originalWindow = (globalThis as any).window; + const originalDocument = (globalThis as any).Document; + + afterEach(() => { + if (originalWindow === undefined) { + delete (globalThis as any).window; + } else { + (globalThis as any).window = originalWindow; + } + + if (originalDocument === undefined) { + delete (globalThis as any).Document; + } else { + (globalThis as any).Document = originalDocument; + } + }); + + it('returns a CSSStyleSheet when constructable stylesheets are supported', () => { + class FakeSheet { + replaceSync(_css: string) {} + } + (FakeSheet as any).prototype.replaceSync = function () {}; + const FakeDoc = function () {} as any; + FakeDoc.prototype = { adoptedStyleSheets: [] }; + + (globalThis as any).window = { CSSStyleSheet: FakeSheet }; + (globalThis as any).Document = FakeDoc; + + const result = createStyles('body{}'); + expect(result).toBeInstanceOf(FakeSheet); + }); +}); + diff --git a/packages/common/src/lib/create-styles.ts b/packages/common/src/lib/create-styles.ts index 0014a7f..750f27a 100644 --- a/packages/common/src/lib/create-styles.ts +++ b/packages/common/src/lib/create-styles.ts @@ -10,21 +10,15 @@ const hasConstructableStylesheetsSupport = () => export const createStyles = (cssText: string) => { if (!hasConstructableStylesheetsSupport()) { - return css` - ${unsafeCSS(cssText)} - `; + return css`${unsafeCSS(cssText)}`; } try { const sheet = new CSSStyleSheet(); sheet.replaceSync(cssText); - return css` - ${unsafeCSS(cssText)} - `; + return sheet; } catch (error) { warn("Failed to create CSSStyleSheet:", error); - return css` - ${unsafeCSS(cssText)} - `; + return css`${unsafeCSS(cssText)}`; } };