Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(vite): preserve precompiled style composition order (#19162)

Inneiba3e528e4b7c
diff --git a/plugins/vite/staticStylesPrecompile.test.ts b/plugins/vite/staticStylesPrecompile.test.ts
index 3fac36a2f8c..0be7e8a4c20 100644
--- a/plugins/vite/staticStylesPrecompile.test.ts
+++ b/plugins/vite/staticStylesPrecompile.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { build, parseAst, type Plugin } from 'vite';
-import { beforeAll, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import {
loadAntdStyleEvaluator,
@@ -16,6 +16,10 @@ beforeAll(async () => {
evaluator = await loadAntdStyleEvaluator();
});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
const CALLBACK = `({ css, responsive }) => ({
root: css\`
display: flex;
@@ -57,9 +61,8 @@ describe('precompileStaticStyles', () => {
expect(output).toContain('@media (max-width: 479.98px){.acss-');
expect(output).toContain('"text-2": __lobeStaticStyle(');
expect(output).toMatch(
- /__lobeStaticStyle\("acss-[a-z0-9]+", \["\.acss-[a-z0-9]+\{font-size:12px;\}"\]\)/,
+ /__lobeStaticStyle\("acss-[a-z0-9]+", \["\.acss-[a-z0-9]+\{font-size:12px;\}"\], "font-size: 12px;"\)/,
);
- expect(output).not.toContain('font-size: 12px;');
});
it('matches the class names antd-style produces at runtime', () => {
@@ -155,13 +158,14 @@ describe('insertPrecompiledStyle', () => {
it('inserts rules once and exposes emotion-mergeable registered styles', async () => {
const { createStaticStyles, css, cx, styleManager } = (await import('antd-style')) as any;
const insert = vi.fn();
- styleManager.cache.sheet = { insert };
+ const insertSpy = vi.spyOn(styleManager.cache.sheet, 'insert').mockImplementation(insert);
const rules = ['.acss-fixture{color:red;}', '.acss-fixture:hover{color:blue;}'];
+ const registered = 'color:red;&:hover{color:blue;}';
- expect(insertPrecompiledStyle('acss-fixture', rules)).toBe('acss-fixture');
- insertPrecompiledStyle('acss-fixture', rules);
+ expect(insertPrecompiledStyle('acss-fixture', rules, registered)).toBe('acss-fixture');
+ insertPrecompiledStyle('acss-fixture', rules, registered);
expect(insert.mock.calls.map(([rule]) => rule)).toEqual(rules);
- expect(styleManager.cache.registered['acss-fixture']).toBe('&{color:red;}&:hover{color:blue;}');
+ expect(styleManager.cache.registered['acss-fixture']).toBe(registered);
const merged = cx(
'acss-fixture',
@@ -170,7 +174,7 @@ describe('insertPrecompiledStyle', () => {
`,
);
expect(merged).not.toBe('acss-fixture');
- expect(styleManager.cache.registered[merged]).toContain('&{color:red;}&:hover{color:blue;}');
+ expect(styleManager.cache.registered[merged]).toContain(registered);
expect(styleManager.cache.registered[merged]).toContain('margin: 0;');
const composed = createStaticStyles(({ css: s }: any) => ({
@@ -182,6 +186,51 @@ describe('insertPrecompiledStyle', () => {
styleManager.cache.registered['acss-fixture'] = 'color: green;';
expect(styleManager.cache.registered['acss-fixture']).toBe('color: green;');
+ insertSpy.mockRestore();
+ });
+
+ it.each([
+ ['padding-block:12px;padding-inline:12px;', 'padding:0;'],
+ [
+ 'padding-block:12px;--lobe-popover-viewport-inline-padding:12px;',
+ 'padding-block:0px;--lobe-popover-viewport-inline-padding:0px;',
+ ],
+ [
+ 'color:red;&:hover{color:orange;}@media(min-width:600px){color:green;}',
+ 'color:blue;&:hover{color:purple;}@media(min-width:600px){color:black;}',
+ ],
+ ])('preserves runtime composition for %s', async (base, override) => {
+ const { createStaticStyles, cx, styleManager } = await import('antd-style');
+ const makeStyle = (value: string) =>
+ createStaticStyles(({ css }) => ({ root: css(value) })).root;
+ const composeStyle = (className: string) =>
+ createStaticStyles(({ css }) => ({
+ root: css`
+ ${className}${override}
+ `,
+ })).root;
+ vi.spyOn(styleManager.cache.sheet, 'insert').mockImplementation(() => {});
+ const source = `import { createStaticStyles } from 'antd-style';
+ const styles = createStaticStyles(({ css }) => ({ root: css(${JSON.stringify(base)}) }));`;
+ const output = precompileStaticStyles(source, evaluator)!;
+ const run = new Function(
+ '__lobeStaticStyle',
+ `${output.replaceAll(/^import .*;\n/gm, '')}\nreturn styles.root;`,
+ );
+ const precompiled = run(insertPrecompiledStyle);
+ const runtimeOverride = makeStyle(override);
+ const mixed = cx(precompiled, runtimeOverride);
+ const reversed = cx(runtimeOverride, precompiled);
+ const interpolated = composeStyle(precompiled);
+
+ delete styleManager.cache.registered[precompiled];
+ const runtimeBase = makeStyle(base);
+ expect(mixed).toBe(cx(runtimeBase, runtimeOverride));
+ expect(reversed).toBe(cx(runtimeOverride, runtimeBase));
+ expect(interpolated).toBe(composeStyle(runtimeBase));
+ expect(styleManager.cache.inserted[mixed.slice(styleManager.cache.key.length + 1)]).toContain(
+ override.split(';')[0],
+ );
});
});
diff --git a/plugins/vite/staticStylesPrecompile.ts b/plugins/vite/staticStylesPrecompile.ts
index e983b11ce80..e03154539fe 100644
--- a/plugins/vite/staticStylesPrecompile.ts
+++ b/plugins/vite/staticStylesPrecompile.ts
@@ -12,6 +12,7 @@ interface AntdStyleEvaluator {
cache: {
inserted: Record<string, string | true>;
key: string;
+ registered: Record<string, string>;
};
createStaticStyles: (fn: (utils: unknown) => Record<string, unknown>) => Record<string, unknown>;
cssVar: unknown;
@@ -176,9 +177,10 @@ const serializeStyles = (result: Record<string, unknown>, evaluator: AntdStyleEv
for (const [key, value] of Object.entries(result)) {
if (typeof value !== 'string' || !value.startsWith(prefix)) return;
const css = evaluator.cache.inserted[value.slice(prefix.length)];
- if (typeof css !== 'string') return;
+ const registered = evaluator.cache.registered[value];
+ if (typeof css !== 'string' || typeof registered !== 'string') return;
entries.push(
- `${JSON.stringify(key)}: ${HELPER}(${JSON.stringify(value)}, ${JSON.stringify(splitRules(css))})`,
+ `${JSON.stringify(key)}: ${HELPER}(${JSON.stringify(value)}, ${JSON.stringify(splitRules(css))}, ${JSON.stringify(registered)})`,
);
}
return `({ ${entries.join(', ')} })`;
@@ -190,6 +192,7 @@ export const precompileStaticStyles = (code: string, evaluator: AntdStyleEvaluat
try {
program = parseAst(code) as unknown as Node;
} catch {
+ // Unsupported syntax keeps the original runtime call; precompilation is optional.
return;
}
@@ -214,6 +217,7 @@ export const precompileStaticStyles = (code: string, evaluator: AntdStyleEvaluat
evaluator,
);
} catch {
+ // Evaluation or serialization failures must preserve runtime style generation.
continue;
}
if (compiled) replacements.push({ end: call.end, start: call.start, text: compiled });
diff --git a/plugins/vite/staticStylesRuntime.js b/plugins/vite/staticStylesRuntime.js
index 8eaf3ef195b..d3577cab65e 100644
--- a/plugins/vite/staticStylesRuntime.js
+++ b/plugins/vite/staticStylesRuntime.js
@@ -3,18 +3,12 @@ import { styleManager } from 'antd-style';
const cache = styleManager.cache;
const prefixLength = cache.key.length + 1;
-export const insertPrecompiledStyle = (className, rules) => {
+export const insertPrecompiledStyle = (className, rules, registered) => {
const name = className.slice(prefixLength);
if (cache.inserted[name] === undefined) {
for (const rule of rules) cache.sheet.insert(rule);
cache.inserted[name] = true;
}
- const define = (descriptor) => Object.defineProperty(cache.registered, className, descriptor);
- define({
- configurable: true,
- enumerable: true,
- get: () => rules.map((rule) => rule.replaceAll(`.${className}`, '&')).join(''),
- set: (value) => define({ configurable: true, enumerable: true, value, writable: true }),
- });
+ cache.registered[className] = registered;
return className;
};