From 629ac2560e800c92141e00fec1f5e8c45457c174 Mon Sep 17 00:00:00 2001 From: taiiiyang <781547101@qq.com> Date: Wed, 17 Dec 2025 21:38:47 +0800 Subject: [PATCH 1/2] feat: add cssPropertyRename option to prevent CSS @property conflicts --- packages/wxt/package.json | 4 + .../rename-css-custom-properties.test.ts | 251 ++++++++++++++++++ .../utils/content-script-ui/shadow-root.ts | 33 ++- .../src/utils/rename-css-custom-properties.ts | 110 ++++++++ packages/wxt/typedoc.json | 1 + 5 files changed, 398 insertions(+), 1 deletion(-) create mode 100644 packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts create mode 100644 packages/wxt/src/utils/rename-css-custom-properties.ts diff --git a/packages/wxt/package.json b/packages/wxt/package.json index 9346c1393..0c2df2d01 100644 --- a/packages/wxt/package.json +++ b/packages/wxt/package.json @@ -171,6 +171,10 @@ "types": "./dist/utils/split-shadow-root-css.d.ts", "default": "./dist/utils/split-shadow-root-css.mjs" }, + "./utils/rename-css-custom-properties": { + "types": "./dist/utils/rename-css-custom-properties.d.ts", + "default": "./dist/utils/rename-css-custom-properties.mjs" + }, "./utils/storage": { "types": "./dist/utils/storage.d.ts", "default": "./dist/utils/storage.mjs" diff --git a/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts new file mode 100644 index 000000000..27e7eb803 --- /dev/null +++ b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts @@ -0,0 +1,251 @@ +import { describe, it, expect } from 'vitest'; +import { renameCssCustomProperties } from '../rename-css-custom-properties'; + +describe('renameCssCustomProperties', () => { + const defaultOptions = { + fromPrefix: '--tw-', + toPrefix: '--wxt-tw-', + }; + + describe('@property rules', () => { + it('should rename @property rule names', () => { + const css = `@property --tw-gradient-from { + syntax: ""; + inherits: false; + initial-value: #0000; +}`; + const expected = `@property --wxt-tw-gradient-from { + syntax: ""; + inherits: false; + initial-value: #0000; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should rename multiple @property rules', () => { + const css = `@property --tw-gradient-from { + syntax: ""; +} +@property --tw-gradient-to { + syntax: ""; +}`; + const expected = `@property --wxt-tw-gradient-from { + syntax: ""; +} +@property --wxt-tw-gradient-to { + syntax: ""; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should not rename @property rules with non-matching prefix', () => { + const css = `@property --other-prop { + syntax: "*"; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(css); + }); + }); + + describe('property declarations', () => { + it('should rename property declarations', () => { + const css = `.class { + --tw-gradient-from: #ff0000; +}`; + const expected = `.class { + --wxt-tw-gradient-from: #ff0000; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should rename multiple property declarations', () => { + const css = `.class { + --tw-gradient-from: #ff0000; + --tw-gradient-to: #0000ff; +}`; + const expected = `.class { + --wxt-tw-gradient-from: #ff0000; + --wxt-tw-gradient-to: #0000ff; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should not rename declarations with non-matching prefix', () => { + const css = `.class { + --other-prop: value; +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(css); + }); + }); + + describe('var() references', () => { + it('should rename var() references', () => { + const css = `.class { + background: var(--tw-gradient-from); +}`; + const expected = `.class { + background: var(--wxt-tw-gradient-from); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should rename var() with fallback values', () => { + const css = `.class { + background: var(--tw-gradient-from, #000); +}`; + const expected = `.class { + background: var(--wxt-tw-gradient-from, #000); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should rename nested var() references', () => { + const css = `.class { + background: var(--tw-gradient-from, var(--tw-gradient-to)); +}`; + const expected = `.class { + background: var(--wxt-tw-gradient-from, var(--wxt-tw-gradient-to)); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should rename var() inside calc()', () => { + const css = `.class { + width: calc(var(--tw-spacing) * 2); +}`; + const expected = `.class { + width: calc(var(--wxt-tw-spacing) * 2); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should not rename var() with non-matching prefix', () => { + const css = `.class { + background: var(--other-prop); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(css); + }); + }); + + describe('combined cases', () => { + it('should rename all occurrences in a complete CSS snippet', () => { + const css = `@property --tw-gradient-from { + syntax: ""; + inherits: false; + initial-value: #0000; +} + +.from-red-500 { + --tw-gradient-from: #ef4444; +} + +.bg-gradient-to-r { + background-image: linear-gradient(to right, var(--tw-gradient-from), var(--tw-gradient-to)); +}`; + + const expected = `@property --wxt-tw-gradient-from { + syntax: ""; + inherits: false; + initial-value: #0000; +} + +.from-red-500 { + --wxt-tw-gradient-from: #ef4444; +} + +.bg-gradient-to-r { + background-image: linear-gradient(to right, var(--wxt-tw-gradient-from), var(--wxt-tw-gradient-to)); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should handle minified CSS', () => { + const css = `@property --tw-shadow{syntax:"*";inherits:false}.class{--tw-shadow:0 0 #0000;box-shadow:var(--tw-shadow)}`; + const expected = `@property --wxt-tw-shadow{syntax:"*";inherits:false}.class{--wxt-tw-shadow:0 0 #0000;box-shadow:var(--wxt-tw-shadow)}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + }); + + describe('custom prefixes', () => { + it('should work with custom fromPrefix and toPrefix', () => { + const css = `.class { + --custom-prop: value; + background: var(--custom-prop); +}`; + const expected = `.class { + --my-custom-prop: value; + background: var(--my-custom-prop); +}`; + + expect( + renameCssCustomProperties(css, { + fromPrefix: '--custom-', + toPrefix: '--my-custom-', + }), + ).toBe(expected); + }); + }); + + describe('edge cases', () => { + it('should handle empty CSS string', () => { + expect(renameCssCustomProperties('', defaultOptions)).toBe(''); + }); + + it('should handle CSS without any custom properties', () => { + const css = `.class { color: red; }`; + expect(renameCssCustomProperties(css, defaultOptions)).toBe(css); + }); + + it('should preserve whitespace in var() references', () => { + const css = `.class { + background: var( --tw-gradient-from ); +}`; + const expected = `.class { + background: var( --wxt-tw-gradient-from ); +}`; + + expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); + }); + + it('should return original CSS when both fromPrefix and toPrefix are undefined', () => { + const css = `.class { --tw-prop: value; }`; + expect(renameCssCustomProperties(css, {})).toBe(css); + }); + + it('should prepend toPrefix to all custom properties when fromPrefix is undefined', () => { + const css = `.class { --prop: value; background: var(--prop); }`; + const expected = `.class { --wxt-prop: value; background: var(--wxt-prop); }`; + expect(renameCssCustomProperties(css, { toPrefix: '--wxt-' })).toBe( + expected, + ); + }); + + it('should remove fromPrefix when toPrefix is undefined', () => { + const css = `.class { --tw-prop: value; }`; + const expected = `.class { prop: value; }`; + expect(renameCssCustomProperties(css, { fromPrefix: '--tw-' })).toBe( + expected, + ); + }); + + it('should replace with empty string when toPrefix is empty string', () => { + const css = `.class { --tw-prop: value; }`; + const expected = `.class { prop: value; }`; + expect( + renameCssCustomProperties(css, { fromPrefix: '--tw-', toPrefix: '' }), + ).toBe(expected); + }); + }); +}); diff --git a/packages/wxt/src/utils/content-script-ui/shadow-root.ts b/packages/wxt/src/utils/content-script-ui/shadow-root.ts index 8d1c37d86..407ab75d9 100644 --- a/packages/wxt/src/utils/content-script-ui/shadow-root.ts +++ b/packages/wxt/src/utils/content-script-ui/shadow-root.ts @@ -6,6 +6,10 @@ import { createIsolatedElement } from '@webext-core/isolated-element'; import { applyPosition, createMountFunctions, mountUi } from './shared'; import { logger } from '../internal/logger'; import { splitShadowRootCss } from '../split-shadow-root-css'; +import { + renameCssCustomProperties, + type CssPropertyPrefixOptions, +} from '../rename-css-custom-properties'; /** * Create a content script UI inside a [`ShadowRoot`](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot). @@ -33,8 +37,14 @@ export async function createShadowRootUi( css.push(entryCss.replaceAll(':root', ':host')); } + // Rename CSS custom properties if prefix options are provided + let finalCss = css.join('\n').trim(); + if (options.cssPropertyRename) { + finalCss = renameCssCustomProperties(finalCss, options.cssPropertyRename); + } + // Some rules must be applied outside the shadow root, so split the CSS apart - const { shadowCss, documentCss } = splitShadowRootCss(css.join('\n').trim()); + const { shadowCss, documentCss } = splitShadowRootCss(finalCss); const { isolatedElement: uiContainer, @@ -207,4 +217,25 @@ export type ShadowRootContentScriptUiOptions = shadow: ShadowRoot, shadowHost: HTMLElement, ) => TMounted; + /** + * Rename CSS custom property prefixes to prevent conflicts with host page styles. + * + * This is useful when your extension uses CSS frameworks like Tailwind CSS v4 that define + * typed `@property` rules, which can conflict with host pages using older versions. + * + * @example + * ```ts + * createShadowRootUi(ctx, { + * name: 'my-ui', + * cssPropertyRename: { + * fromPrefix: '--tw-', + * toPrefix: '--my-ext-tw-', + * }, + * onMount(container) { + * // ... + * }, + * }); + * ``` + */ + cssPropertyRename?: CssPropertyPrefixOptions; }; diff --git a/packages/wxt/src/utils/rename-css-custom-properties.ts b/packages/wxt/src/utils/rename-css-custom-properties.ts new file mode 100644 index 000000000..b0690111b --- /dev/null +++ b/packages/wxt/src/utils/rename-css-custom-properties.ts @@ -0,0 +1,110 @@ +/** @module wxt/utils/rename-css-custom-properties */ + +/** + * Options for renaming CSS custom properties. + */ +export interface CssPropertyPrefixOptions { + /** + * The original prefix to match and replace. + * @default '' + * @example '--tw-' + */ + fromPrefix?: string; + /** + * The new prefix to use as replacement. + * @default '' + * @example '--wxt-tw-' + */ + toPrefix?: string; +} + +/** + * Renames a CSS custom property name if it starts with the specified prefix. + */ +function renamePropertyName( + propertyName: string, + fromPrefix: string, + toPrefix: string, +): string { + if (!propertyName.startsWith(fromPrefix)) { + return propertyName; + } + return toPrefix + propertyName.slice(fromPrefix.length); +} + +/** + * Renames CSS custom properties in a CSS string. + * + * This function handles three types of CSS custom property occurrences: + * 1. `@property` rules: `@property {fromPrefix}xxx { ... }` → `@property {toPrefix}xxx { ... }` + * 2. Property declarations: `{fromPrefix}xxx: value` → `{toPrefix}xxx: value` + * 3. `var()` references: `var({fromPrefix}xxx)` → `var({toPrefix}xxx)` + * + * @param css - The CSS string to process + * @param options - The prefix options + * @returns The CSS string with renamed custom properties + * + * @example + * ```ts + * const css = ` + * @property --tw-gradient-from { syntax: ""; } + * .class { --tw-gradient-from: red; background: var(--tw-gradient-from); } + * `; + * const result = renameCssCustomProperties(css, { + * fromPrefix: '--tw-', + * toPrefix: '--wxt-tw-' + * }); + * // Result: + * // @property --wxt-tw-gradient-from { syntax: ""; } + * // .class { --wxt-tw-gradient-from: red; background: var(--wxt-tw-gradient-from); } + * ``` + */ +export function renameCssCustomProperties( + css: string, + options: CssPropertyPrefixOptions, +): string { + const hasFromPrefix = options.fromPrefix !== undefined; + const hasToPrefix = options.toPrefix !== undefined; + + // If both are not provided, do nothing + if (!hasFromPrefix && !hasToPrefix) { + return css; + } + + // If fromPrefix is not provided, default to '' (prepend toPrefix to all custom properties) + // If toPrefix is not provided, default to '' (remove fromPrefix) + const fromPrefix = options.fromPrefix ?? ''; + const toPrefix = options.toPrefix ?? ''; + + // Escape special regex characters in the prefix + const escapedFromPrefix = fromPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + + // 1. Rename @property rules: @property --tw-xxx + // Matches: @property followed by whitespace and a custom property name starting with fromPrefix + const atPropertyRegex = new RegExp( + `(@property\\s+)(${escapedFromPrefix}[\\w-]*)`, + 'g', + ); + let result = css.replace(atPropertyRegex, (_, prefix, propName) => { + return `${toPrefix}${renamePropertyName(propName, fromPrefix, toPrefix)}`; + }); + + // 2. Rename property declarations: --tw-xxx: value + // Matches: custom property name starting with fromPrefix, followed by optional whitespace and colon + const declarationRegex = new RegExp( + `(${escapedFromPrefix}[\\w-]*)(\\s*:)`, + 'g', + ); + result = result.replace(declarationRegex, (_, propName, colonPart) => { + return `${renamePropertyName(propName, fromPrefix, toPrefix)}${colonPart}`; + }); + + // 3. Rename var() references: var(--tw-xxx) or var(--tw-xxx, fallback) + // Matches: var( followed by optional whitespace and a custom property name starting with fromPrefix + const varRegex = new RegExp(`(var\\(\\s*)(${escapedFromPrefix}[\\w-]*)`, 'g'); + result = result.replace(varRegex, (_, varPrefix, propName) => { + return `${varPrefix}${renamePropertyName(propName, fromPrefix, toPrefix)}`; + }); + + return result; +} diff --git a/packages/wxt/typedoc.json b/packages/wxt/typedoc.json index 1cfd97c04..9e1830364 100644 --- a/packages/wxt/typedoc.json +++ b/packages/wxt/typedoc.json @@ -15,6 +15,7 @@ "src/utils/define-wxt-plugin.ts", "src/utils/match-patterns.ts", "src/utils/split-shadow-root-css.ts", + "src/utils/rename-css-custom-properties.ts", "src/utils/storage.ts", "src/testing/index.ts", "src/testing/fake-browser.ts", From 49ed882279a29159f6b387e4b4c77e2817151201 Mon Sep 17 00:00:00 2001 From: taiiiyang <781547101@qq.com> Date: Mon, 22 Dec 2025 16:09:32 +0800 Subject: [PATCH 2/2] refactor(cssPropertyRename): require both prefixes and optimize regex --- .../rename-css-custom-properties.bench.ts | 39 ++++++++ .../rename-css-custom-properties.test.ts | 41 ++++---- .../utils/content-script-ui/shadow-root.ts | 2 +- .../src/utils/rename-css-custom-properties.ts | 93 ++++++++----------- 4 files changed, 99 insertions(+), 76 deletions(-) create mode 100644 packages/wxt/src/utils/__tests__/rename-css-custom-properties.bench.ts diff --git a/packages/wxt/src/utils/__tests__/rename-css-custom-properties.bench.ts b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.bench.ts new file mode 100644 index 000000000..a4e5be9a8 --- /dev/null +++ b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.bench.ts @@ -0,0 +1,39 @@ +import { bench, describe } from 'vitest'; +import { renameCssCustomProperties } from '../rename-css-custom-properties'; +import { splitShadowRootCss } from '../split-shadow-root-css'; + +// Real Tailwind CSS v4.0.13 minified output for realistic benchmarking +// This is the same CSS used in split-shadow-root-css.test.ts +const TAILWIND_CSS = `/*! tailwindcss v4.0.13 | MIT License | https://tailwindcss.com */@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--spacing:.25rem;--container-3xl:48rem;--container-5xl:64rem;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5/2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-light:300;--font-weight-semibold:600;--font-weight-bold:700;--radius-md:.375rem;--radius-xl:.75rem;--aspect-video:16/9;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-font-feature-settings:var(--font-sans--font-feature-settings);--default-font-variation-settings:var(--font-sans--font-variation-settings);--default-mono-font-family:var(--font-mono);--default-mono-font-feature-settings:var(--font-mono--font-feature-settings);--default-mono-font-variation-settings:var(--font-mono--font-variation-settings);--color-primary:#ffc700;--color-primary-content:#000;--color-secondary:#c00;--color-secondary-content:#fff;--color-base:#000;--color-base-content:#fff;--color-neutral:#1c1c1c;--color-neutral-content:#fff;--color-white:#fff;--color-black:#000;--font-poppins:Poppins,sans-serif;--spacing-main-navigation:calc(20*var(--spacing))}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}body{line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1;color:color-mix(in oklab,currentColor 50%,transparent)}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}*{min-width:0;min-height:0}body{background-color:var(--color-base);color:var(--color-base-content)}}@layer components{.btn{--btn-bg:var(--color-primary);--btn-text:var(--color-primary-content);background-color:var(--btn-bg);color:var(--btn-text);border-radius:calc(2*var(--spacing));font-weight:500;font-family:var(--font-poppins);padding:calc(3*var(--spacing))calc(6*var(--spacing));justify-content:center;align-items:center;gap:calc(3*var(--spacing));cursor:pointer;transition:transform .2s;display:flex}.btn:hover{transform:scale(1.05)}.btn:active{transform:scale(.97)}.btn-neutral{--btn-bg:var(--color-neutral);--btn-text:var(--color-neutral-content)}.btn-base{--btn-bg:var(--color-base);--btn-text:var(--color-base-content)}.btn-white{--btn-bg:var(--color-white);--btn-text:var(--color-black)}.btn-secondary{--btn-bg:var(--color-secondary);--btn-text:var(--color-secondary-content)}.btn-square{padding:calc(3*var(--spacing))}.nav-link{font-family:var(--font-poppins);font-size:var(--text-xl);transition:color .2s;position:relative}.nav-link:hover,.nav-link.active{color:var(--color-primary)}.nav-link.active:after{content:"";bottom:calc(-1*var(--spacing));background-color:var(--color-primary);width:100%;height:2px;position:absolute;left:0}.link{color:color-mix(in srgb,var(--color-secondary),white 30%);font-weight:500;text-decoration:underline}.link-white{color:var(--color-white)}}@layer utilities{.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.inset-x-0{inset-inline:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.z-0{z-index:0}.z-1{z-index:1}.z-10{z-index:10}.mx-4{margin-inline:calc(var(--spacing)*4)}.mx-auto{margin-inline:auto}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-main-navigation{margin-top:var(--spacing-main-navigation)}.-mr-2{margin-right:calc(var(--spacing)*-2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.-ml-2{margin-left:calc(var(--spacing)*-2)}.i-heroicons-bars-3{width:1.5em;height:1.5em;-webkit-mask-image:var(--svg);mask-image:var(--svg);--svg:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5'/%3E%3C/svg%3E");background-color:currentColor;display:inline-block;-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}.i-heroicons-calendar-days{width:1.5em;height:1.5em;-webkit-mask-image:var(--svg);mask-image:var(--svg);--svg:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 0 1 2.25-2.25h13.5A2.25 2.25 0 0 1 21 7.5v11.25m-18 0A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75m-18 0v-7.5A2.25 2.25 0 0 1 5.25 9h13.5A2.25 2.25 0 0 1 21 11.25v7.5m-9-6h.008v.008H12zM12 15h.008v.008H12zm0 2.25h.008v.008H12zM9.75 15h.008v.008H9.75zm0 2.25h.008v.008H9.75zM7.5 15h.008v.008H7.5zm0 2.25h.008v.008H7.5zm6.75-4.5h.008v.008h-.008zm0 2.25h.008v.008h-.008zm0 2.25h.008v.008h-.008zm2.25-4.5h.008v.008H16.5zm0 2.25h.008v.008H16.5z'/%3E%3C/svg%3E");background-color:currentColor;display:inline-block;-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}.i-heroicons-chevron-right{width:1.5em;height:1.5em;-webkit-mask-image:var(--svg);mask-image:var(--svg);--svg:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m8.25 4.5l7.5 7.5l-7.5 7.5'/%3E%3C/svg%3E");background-color:currentColor;display:inline-block;-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}.i-heroicons-x-mark{width:1.5em;height:1.5em;-webkit-mask-image:var(--svg);mask-image:var(--svg);--svg:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 18L18 6M6 6l12 12'/%3E%3C/svg%3E");background-color:currentColor;display:inline-block;-webkit-mask-size:100% 100%;mask-size:100% 100%;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat}.flex{display:flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1}.aspect-video{aspect-ratio:var(--aspect-video)}.h-12{height:calc(var(--spacing)*12)}.h-20{height:calc(var(--spacing)*20)}.h-\\[70vh\\]{height:70vh}.h-\\[95vh\\]{height:95vh}.h-\\[100vh\\]{height:100vh}.h-full{height:100%}.h-main-navigation{height:var(--spacing-main-navigation)}.w-24{width:calc(var(--spacing)*24)}.w-40{width:calc(var(--spacing)*40)}.w-full{width:100%}.max-w-3xl{max-width:var(--container-3xl)}.max-w-5xl{max-width:var(--container-5xl)}.flex-1{flex:1}.shrink-0{flex-shrink:0}.transform{transform:var(--tw-rotate-x)var(--tw-rotate-y)var(--tw-rotate-z)var(--tw-skew-x)var(--tw-skew-y)}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-items-center{justify-items:center}.gap-2{gap:calc(var(--spacing)*2)}.gap-4{gap:calc(var(--spacing)*4)}.gap-8{gap:calc(var(--spacing)*8)}.gap-16{gap:calc(var(--spacing)*16)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-base>:not(:last-child)){border-color:var(--color-base)}.overflow-hidden{overflow:hidden}.rounded-md{border-radius:var(--radius-md)}.rounded-xl{border-radius:var(--radius-xl)}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-white\\/50{border-color:color-mix(in oklab,var(--color-white)50%,transparent)}.bg-base\\/0{background-color:color-mix(in oklab,var(--color-base)0%,transparent)}.bg-base\\/100{background-color:color-mix(in oklab,var(--color-base)100%,transparent)}.bg-neutral{background-color:var(--color-neutral)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-8{padding:calc(var(--spacing)*8)}.p-16{padding:calc(var(--spacing)*16)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-8{padding-inline:calc(var(--spacing)*8)}.py-20{padding-block:calc(var(--spacing)*20)}.pt-main-navigation{padding-top:var(--spacing-main-navigation)}.text-center{text-align:center}.font-poppins{font-family:var(--font-poppins)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.leading-\\[3\\]{--tw-leading:3;line-height:3}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-light{--tw-font-weight:var(--font-weight-light);font-weight:var(--font-weight-light)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-primary{color:var(--color-primary)}.text-secondary{color:var(--color-secondary)}.text-white{color:var(--color-white)}.opacity-0{opacity:0}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.opacity-100{opacity:1}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.ring-4{--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(4px + var(--tw-ring-offset-width))var(--tw-ring-color,currentColor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-primary\\/50{--tw-shadow-color:color-mix(in oklab,var(--color-primary)50%,transparent)}.ring-primary\\/30{--tw-ring-color:color-mix(in oklab,var(--color-primary)30%,transparent)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.hover\\:text-primary:hover{color:var(--color-primary)}}@media (width>=48rem){.md\\:mx-16{margin-inline:calc(var(--spacing)*16)}.md\\:block{display:block}.md\\:flex{display:flex}.md\\:hidden{display:none}.md\\:aspect-square{aspect-ratio:1}.md\\:h-56{height:calc(var(--spacing)*56)}.md\\:h-full{height:100%}.md\\:w-\\[unset\\]{width:unset}.md\\:flex-1{flex:1}.md\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\\:flex-row-reverse{flex-direction:row-reverse}.md\\:items-start{align-items:flex-start}.md\\:justify-start{justify-content:flex-start}.md\\:justify-items-start{justify-items:start}.md\\:gap-12{gap:calc(var(--spacing)*12)}.md\\:px-16{padding-inline:calc(var(--spacing)*16)}.md\\:pr-\\[30vw\\]{padding-right:30vw}.md\\:text-left{text-align:left}}@media (width>=64rem){.lg\\:aspect-\\[4\\/3\\]{aspect-ratio:4/3}.lg\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}}@property --tw-rotate-x{syntax:"*";inherits:false;initial-value:rotateX(0)}@property --tw-rotate-y{syntax:"*";inherits:false;initial-value:rotateY(0)}@property --tw-rotate-z{syntax:"*";inherits:false;initial-value:rotateZ(0)}@property --tw-skew-x{syntax:"*";inherits:false;initial-value:skewX(0)}@property --tw-skew-y{syntax:"*";inherits:false;initial-value:skewY(0)}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@font-face{font-family: "custom-font";font-display: swap;font-weight: 500;src: url("fonts/custom-font.otf") format("opentype");}`; + +describe('renameCssCustomProperties performance', () => { + const renameOptions = { + fromPrefix: '--tw-', + toPrefix: '--wxt-tw-', + }; + + bench('splitShadowRootCss only (baseline)', () => { + splitShadowRootCss(TAILWIND_CSS); + }); + + bench('renameCssCustomProperties only', () => { + renameCssCustomProperties(TAILWIND_CSS, renameOptions); + }); + + bench( + 'renameCssCustomProperties + splitShadowRootCss (full pipeline)', + () => { + const renamed = renameCssCustomProperties(TAILWIND_CSS, renameOptions); + splitShadowRootCss(renamed); + }, + ); + + bench( + 'splitShadowRootCss + renameCssCustomProperties (alternate order)', + () => { + const { shadowCss, documentCss } = splitShadowRootCss(TAILWIND_CSS); + renameCssCustomProperties(shadowCss, renameOptions); + renameCssCustomProperties(documentCss, renameOptions); + }, + ); +}); diff --git a/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts index 27e7eb803..2742e9a04 100644 --- a/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts +++ b/packages/wxt/src/utils/__tests__/rename-css-custom-properties.test.ts @@ -181,12 +181,12 @@ describe('renameCssCustomProperties', () => { describe('custom prefixes', () => { it('should work with custom fromPrefix and toPrefix', () => { const css = `.class { - --custom-prop: value; background: var(--custom-prop); + --custom-prop: value; }`; const expected = `.class { - --my-custom-prop: value; background: var(--my-custom-prop); + --my-custom-prop: value; }`; expect( @@ -219,33 +219,28 @@ describe('renameCssCustomProperties', () => { expect(renameCssCustomProperties(css, defaultOptions)).toBe(expected); }); - it('should return original CSS when both fromPrefix and toPrefix are undefined', () => { - const css = `.class { --tw-prop: value; }`; - expect(renameCssCustomProperties(css, {})).toBe(css); - }); - - it('should prepend toPrefix to all custom properties when fromPrefix is undefined', () => { - const css = `.class { --prop: value; background: var(--prop); }`; - const expected = `.class { --wxt-prop: value; background: var(--wxt-prop); }`; - expect(renameCssCustomProperties(css, { toPrefix: '--wxt-' })).toBe( - expected, - ); + it('should not modify CSS when fromPrefix matches nothing', () => { + const css = `.class { --other-prop: value; }`; + expect( + renameCssCustomProperties(css, { + fromPrefix: '--tw-', + toPrefix: '--wxt-tw-', + }), + ).toBe(css); }); - it('should remove fromPrefix when toPrefix is undefined', () => { + it('should throw error when fromPrefix is missing', () => { const css = `.class { --tw-prop: value; }`; - const expected = `.class { prop: value; }`; - expect(renameCssCustomProperties(css, { fromPrefix: '--tw-' })).toBe( - expected, - ); + expect(() => + renameCssCustomProperties(css, { toPrefix: '--wxt-' } as any), + ).toThrow('cssPropertyRename requires both "fromPrefix" and "toPrefix"'); }); - it('should replace with empty string when toPrefix is empty string', () => { + it('should throw error when toPrefix is missing', () => { const css = `.class { --tw-prop: value; }`; - const expected = `.class { prop: value; }`; - expect( - renameCssCustomProperties(css, { fromPrefix: '--tw-', toPrefix: '' }), - ).toBe(expected); + expect(() => + renameCssCustomProperties(css, { fromPrefix: '--tw-' } as any), + ).toThrow('cssPropertyRename requires both "fromPrefix" and "toPrefix"'); }); }); }); diff --git a/packages/wxt/src/utils/content-script-ui/shadow-root.ts b/packages/wxt/src/utils/content-script-ui/shadow-root.ts index 407ab75d9..b8089f300 100644 --- a/packages/wxt/src/utils/content-script-ui/shadow-root.ts +++ b/packages/wxt/src/utils/content-script-ui/shadow-root.ts @@ -218,7 +218,7 @@ export type ShadowRootContentScriptUiOptions = shadowHost: HTMLElement, ) => TMounted; /** - * Rename CSS custom property prefixes to prevent conflicts with host page styles. + * Rename CSS custom property and var prefixes to prevent conflicts with host page styles. * * This is useful when your extension uses CSS frameworks like Tailwind CSS v4 that define * typed `@property` rules, which can conflict with host pages using older versions. diff --git a/packages/wxt/src/utils/rename-css-custom-properties.ts b/packages/wxt/src/utils/rename-css-custom-properties.ts index b0690111b..437f9b799 100644 --- a/packages/wxt/src/utils/rename-css-custom-properties.ts +++ b/packages/wxt/src/utils/rename-css-custom-properties.ts @@ -6,30 +6,14 @@ export interface CssPropertyPrefixOptions { /** * The original prefix to match and replace. - * @default '' * @example '--tw-' */ - fromPrefix?: string; + fromPrefix: string; /** * The new prefix to use as replacement. - * @default '' * @example '--wxt-tw-' */ - toPrefix?: string; -} - -/** - * Renames a CSS custom property name if it starts with the specified prefix. - */ -function renamePropertyName( - propertyName: string, - fromPrefix: string, - toPrefix: string, -): string { - if (!propertyName.startsWith(fromPrefix)) { - return propertyName; - } - return toPrefix + propertyName.slice(fromPrefix.length); + toPrefix: string; } /** @@ -63,48 +47,53 @@ export function renameCssCustomProperties( css: string, options: CssPropertyPrefixOptions, ): string { - const hasFromPrefix = options.fromPrefix !== undefined; - const hasToPrefix = options.toPrefix !== undefined; + const { fromPrefix, toPrefix } = options; - // If both are not provided, do nothing - if (!hasFromPrefix && !hasToPrefix) { - return css; + if (!fromPrefix || !toPrefix) { + throw new Error( + 'cssPropertyRename requires both "fromPrefix" and "toPrefix" to be specified', + ); } - // If fromPrefix is not provided, default to '' (prepend toPrefix to all custom properties) - // If toPrefix is not provided, default to '' (remove fromPrefix) - const fromPrefix = options.fromPrefix ?? ''; - const toPrefix = options.toPrefix ?? ''; - // Escape special regex characters in the prefix const escapedFromPrefix = fromPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const fromPrefixLength = fromPrefix.length; - // 1. Rename @property rules: @property --tw-xxx - // Matches: @property followed by whitespace and a custom property name starting with fromPrefix - const atPropertyRegex = new RegExp( - `(@property\\s+)(${escapedFromPrefix}[\\w-]*)`, + // Combined regex matching all three patterns in a single pass: + // 1. @property --prefix-xxx + // 2. --prefix-xxx: (declaration) + // 3. var(--prefix-xxx + const combinedRegex = new RegExp( + `(@property\\s+)(${escapedFromPrefix}[\\w-]*)|(${escapedFromPrefix}[\\w-]*)(\\s*:)|(var\\(\\s*)(${escapedFromPrefix}[\\w-]*)`, 'g', ); - let result = css.replace(atPropertyRegex, (_, prefix, propName) => { - return `${toPrefix}${renamePropertyName(propName, fromPrefix, toPrefix)}`; - }); - // 2. Rename property declarations: --tw-xxx: value - // Matches: custom property name starting with fromPrefix, followed by optional whitespace and colon - const declarationRegex = new RegExp( - `(${escapedFromPrefix}[\\w-]*)(\\s*:)`, - 'g', + return css.replace( + combinedRegex, + ( + match, + atPropertyPrefix, + atPropertyName, + declareName, + colonPart, + varPrefix, + varName, + ) => { + if (atPropertyPrefix !== undefined) { + // @property rule: @property --tw-xxx + return ( + atPropertyPrefix + toPrefix + atPropertyName.slice(fromPrefixLength) + ); + } + if (declareName !== undefined) { + // Property declaration: --tw-xxx: value + return toPrefix + declareName.slice(fromPrefixLength) + colonPart; + } + if (varPrefix !== undefined) { + // var() reference: var(--tw-xxx) + return varPrefix + toPrefix + varName.slice(fromPrefixLength); + } + return match; + }, ); - result = result.replace(declarationRegex, (_, propName, colonPart) => { - return `${renamePropertyName(propName, fromPrefix, toPrefix)}${colonPart}`; - }); - - // 3. Rename var() references: var(--tw-xxx) or var(--tw-xxx, fallback) - // Matches: var( followed by optional whitespace and a custom property name starting with fromPrefix - const varRegex = new RegExp(`(var\\(\\s*)(${escapedFromPrefix}[\\w-]*)`, 'g'); - result = result.replace(varRegex, (_, varPrefix, propName) => { - return `${varPrefix}${renamePropertyName(propName, fromPrefix, toPrefix)}`; - }); - - return result; }