🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(style-equivalence): recognize standalone css constants and let agent notes sign rendered-equal items (#22682)
Innei08d32e66b9e0
diff --git a/packages/style-equivalence/src/capture/inspect.ts b/packages/style-equivalence/src/capture/inspect.tsindex c3fc20aeb4e..04af3adc281 100644--- a/packages/style-equivalence/src/capture/inspect.ts+++ b/packages/style-equivalence/src/capture/inspect.ts@@ -214,7 +214,9 @@ export const inspectRules = (page: Page): Promise<RuleInspection> =>const hostClasses = (section: Element) => {const owners = new Map<string, string | null>();for (const element of section.querySelectorAll('[data-synthetic-element]')) {- const id = element.getAttribute('data-synthetic-element')!;+ const id =+ element.getAttribute('data-synthetic-pair') ??+ element.getAttribute('data-synthetic-element')!;for (const name of element.classList)owners.set(name, owners.has(name) && owners.get(name) !== id ? null : id);}diff --git a/packages/style-equivalence/src/capture/runner.test.ts b/packages/style-equivalence/src/capture/runner.test.tsindex e1668126746..75200700bf2 100644--- a/packages/style-equivalence/src/capture/runner.test.ts+++ b/packages/style-equivalence/src/capture/runner.test.ts@@ -112,6 +112,23 @@ ${css}page(`.t { color: black; animation: ${name} 1ms; } @keyframes ${name} { from { opacity: 0; } to { opacity: 1; } }`,);+ await write(+ 'state-animation',+ `<!doctype html><html><head><style>+body { margin: 0; font: 14px Arial; }+.f:focus-visible { animation: ring 120ms; }+@keyframes ring { from { opacity: 0.25; } to { opacity: 1; } }+</style></head><body><div id="app" data-synthetic-ready="true"><main data-synthetic-cases="">+${Array.from({ length: 800 }, (_, index) => `<section data-case="a.tsx|A#${index}|0"><div data-synthetic-element="A#${index}" class="f">x</div></section>`).join('')}+</main></div></body></html>`,+ );+ const paired = (id: string) =>+ page('.t { color: black; } .lib:disabled { opacity: 0.5; }').replace(+ '<span data-synthetic-element="A#1" class="t">',+ `<span data-synthetic-element="${id}" data-synthetic-pair="A#0/0" class="t lib">`,+ );+ await write('paired-base', paired('A#0/0'));+ await write('paired-head', paired('A#1'));await write('base-fade', fade('enter'));await write('head-fade', fade('lobe-x-enter'));server = await serveDirectories(root);@@ -184,6 +201,16 @@ describe('captureRun + analyzeRun', () => {expect(gaps).toEqual({ 'a.tsx|A#0': ['STATE_UNMODELED'] });});+ it('matches a library state rule on two paired elements that carry different ids', async () => {+ const gaps = await inspectCaseGaps(+ browser,+ { base: `${server.url}/paired-base/`, head: `${server.url}/paired-head/` },+ conditionFromLabel('light/1280/default'),+ [],+ );+ expect(gaps).toEqual({});+ });+it('matches an unmodeled pseudo rule kept verbatim under a different class on the same element', async () => {const [same] = await run('base-scrollbar', 'head-scrollbar');expect(same.gaps).toEqual([]);@@ -245,6 +272,24 @@ describe('captureRun + analyzeRun', () => {expect(result.status).toBe('unstable');});+ it('holds every animation a forced state starts at its first frame until capture', async () => {+ const { page, snapshots } = await capturePage(+ browser,+ `${server.url}/state-animation/`,+ conditionFromLabel('light/1280/focus-visible'),+ [],+ );+ await page.close();+ const settled = Object.values(snapshots).filter(+ (snapshot) =>+ 'error' in snapshot ||+ snapshot.animations.length !== 1 ||+ snapshot.styles[snapshot.nodes[1].style].opacity !== '0.25',+ );+ expect(Object.keys(snapshots)).toHaveLength(800);+ expect(settled).toHaveLength(0);+ });+it('treats renamed keyframes with the same frames as equal after the animation ends', async () => {const [result] = await run('base-fade', 'head-fade');expect(result).toMatchObject({ differingConditions: [], status: 'equal' });diff --git a/packages/style-equivalence/src/capture/states.ts b/packages/style-equivalence/src/capture/states.tsindex 5ccd4af7e03..59d3274a4c2 100644--- a/packages/style-equivalence/src/capture/states.ts+++ b/packages/style-equivalence/src/capture/states.ts@@ -39,6 +39,10 @@ export const applyState = async (page: Page, state: CaptureState) => {if (state === 'default') return;const { pseudos, selector } = forcing(state);const cdp = await page.context().newCDPSession(page);+ // Forcing runs one call per node; a frozen timeline keeps animations the states start from+ // finishing at staggered times before capture.+ await cdp.send('Animation.enable');+ await cdp.send('Animation.setPlaybackRate', { playbackRate: 0 });await cdp.send('DOM.enable');await cdp.send('CSS.enable');const { root } = await cdp.send('DOM.getDocument', { depth: -1 });diff --git a/packages/style-equivalence/src/cli/review.ts b/packages/style-equivalence/src/cli/review.tsindex a0de2c59f7a..79a0268e0cf 100644--- a/packages/style-equivalence/src/cli/review.ts+++ b/packages/style-equivalence/src/cli/review.ts@@ -1,6 +1,7 @@import { readdir, readFile } from 'node:fs/promises';import path from 'node:path';+import { agentPassRecord, asksAgentNote } from '../review/state';import { writeReviews } from '../review/store';import type { StoredRun } from '../server/api';import { reviewPayload, reviewState } from '../server/review';@@ -37,22 +38,20 @@ export const reworkList = async (stored: StoredRun, format: 'json' | 'text' = 'texport const annotateList = async (stored: StoredRun) => {const payload = await reviewPayload(stored);- return payload.items- .filter((item) => item.needsAgent)- .map((item) => ({- ask: item.ask,- component: item.component,- file: item.file,- flags: item.flags,- hash: item.hash,- key: item.key,- source: {- base: `git show ${String(stored.run.base ?? '')}:${item.file}`,- head: `git show ${String(stored.run.head ?? '')}:${item.file}`,- },- state: item.state,- title: item.title,- }));+ return payload.items.filter(asksAgentNote).map((item) => ({+ ask: item.ask,+ component: item.component,+ file: item.file,+ flags: item.flags,+ hash: item.hash,+ key: item.key,+ source: {+ base: `git show ${String(stored.run.base ?? '')}:${item.file}`,+ head: `git show ${String(stored.run.head ?? '')}:${item.file}`,+ },+ state: item.state,+ title: item.title,+ }));};export interface NoteInput {@@ -70,6 +69,7 @@ export const applyNotes = async (stored: StoredRun, notes: NoteInput[]) => {if (!note.finding?.trim()) throw new Error(`FINDING_REQUIRED:${note.key}`);if (note.suggestion !== 'pass' && note.suggestion !== 'rework')throw new Error(`INVALID_SUGGESTION:${note.key}`);+ const pass = note.suggestion === 'pass' ? agentPassRecord(item, note.finding, now) : undefined;await writeReviews(stored.recordsDir, item.file, {notes: [{@@ -80,6 +80,7 @@ export const applyNotes = async (stored: StoredRun, notes: NoteInput[]) => {suggestion: note.suggestion,},],+ ...(pass ? { passes: [pass] } : {}),});}};diff --git a/packages/style-equivalence/src/extract/attributes.ts b/packages/style-equivalence/src/extract/attributes.tsindex 5732bf0cf86..8b40e843e9c 100644--- a/packages/style-equivalence/src/extract/attributes.ts+++ b/packages/style-equivalence/src/extract/attributes.ts@@ -1,3 +1,5 @@+import ts from 'typescript';+const escape = (text: string) => text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');export const isStateAttribute = (name: string) => /^(?:aria|data)-[\w-]+$/.test(name);@@ -10,3 +12,86 @@ export const booleanAttribute = (code: string, name: string) => {values.every((value) => value === undefined || value === 'true' || value === 'false'));};++const unwrap = (node: ts.Expression): ts.Expression =>+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;++const isEmpty = (node: ts.Expression) =>+ node.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(node) && node.text === 'undefined');++const isCondition = (node: ts.Expression): boolean => {+ const inner = unwrap(node);+ if (ts.isIdentifier(inner)) return inner.text !== 'undefined';+ if (ts.isPropertyAccessExpression(inner)) return isCondition(inner.expression);+ if (inner.kind === ts.SyntaxKind.TrueKeyword || inner.kind === ts.SyntaxKind.FalseKeyword)+ return true;+ if (ts.isPrefixUnaryExpression(inner))+ return inner.operator === ts.SyntaxKind.ExclamationToken && isCondition(inner.operand);+ if (ts.isBinaryExpression(inner))+ return (+ (inner.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||+ inner.operatorToken.kind === ts.SyntaxKind.BarBarToken) &&+ isCondition(inner.left) &&+ isCondition(inner.right)+ );+ return false;+};++const isValue = (node: ts.Expression): boolean => {+ const inner = unwrap(node);+ if (+ ts.isStringLiteral(inner) ||+ ts.isNoSubstitutionTemplateLiteral(inner) ||+ ts.isNumericLiteral(inner) ||+ inner.kind === ts.SyntaxKind.TrueKeyword ||+ inner.kind === ts.SyntaxKind.FalseKeyword ||+ isEmpty(inner)+ )+ return true;+ if (ts.isConditionalExpression(inner))+ return isCondition(inner.condition) && isValue(inner.whenTrue) && isValue(inner.whenFalse);+ if (+ ts.isBinaryExpression(inner) &&+ inner.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken+ )+ return isCondition(inner.left) && isValue(inner.right);+ return false;+};++export const evaluableAttribute = (expression: ts.Expression) =>+ !ts.isIdentifier(unwrap(expression)) && isValue(expression);++const stateKeysOf = (node: ts.Expression): string[] | undefined => {+ const inner = unwrap(node);+ if (isEmpty(inner) || inner.kind === ts.SyntaxKind.FalseKeyword) return [];+ if (ts.isConditionalExpression(inner)) {+ if (!isCondition(inner.condition)) return undefined;+ const left = stateKeysOf(inner.whenTrue);+ const right = stateKeysOf(inner.whenFalse);+ return left && right ? [...left, ...right] : undefined;+ }+ if (+ ts.isBinaryExpression(inner) &&+ inner.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken+ )+ return isCondition(inner.left) ? stateKeysOf(inner.right) : undefined;+ if (!ts.isObjectLiteralExpression(inner)) return undefined;+ const keys: string[] = [];+ for (const property of inner.properties) {+ if (!ts.isPropertyAssignment(property)) return undefined;+ const name = property.name;+ const key = ts.isStringLiteral(name) || ts.isIdentifier(name) ? name.text : undefined;+ if (!key || !isStateAttribute(key) || !isValue(property.initializer)) return undefined;+ keys.push(key);+ }+ return keys;+};++export const spreadAttributes = (expression: ts.Expression, ast: ts.SourceFile) => {+ const keys = stateKeysOf(expression);+ if (!keys?.length) return undefined;+ const text = unwrap(expression).getText(ast);+ return Object.fromEntries(+ [...new Set(keys)].map((key) => [key, `(${text})?.[${JSON.stringify(key)}]`]),+ );+};diff --git a/packages/style-equivalence/src/extract/children.ts b/packages/style-equivalence/src/extract/children.tsindex 1107f2a1465..a6381021e2c 100644--- a/packages/style-equivalence/src/extract/children.ts+++ b/packages/style-equivalence/src/extract/children.ts@@ -102,6 +102,7 @@ export const collectChildren = (styled: Map<ts.Node, StyleElement>,ast: ts.SourceFile,classifyTag: (tag: string) => boolean,+ describe: (tag: string, opening: ts.JsxOpeningLikeElement) => Partial<StyleElement> = () => ({}),) => {const plain: StyleElement[] = [];for (const [node, element] of styled) {@@ -114,7 +115,7 @@ export const collectChildren = (const { literalProps, opaque } = plainAttributes(opening, ast);const id = `${element.id}/${index}`;const real = classifyTag(tag);- const { counts: tags } = subtreeTags(child, ast);+ const { components: nested, counts: tags } = subtreeTags(child, ast);plain.push({bindings: [],flags: opaque ? [PLAIN_ATTRIBUTES_UNMODELED] : [],@@ -124,9 +125,11 @@ export const collectChildren = (parent: element.id,...(real ? { real } : {}),slots: [],+ ...(nested.length ? { subtreeComponents: nested } : {}),...(Object.keys(tags).length ? { subtreeTags: tags } : {}),tag,variables: [],+ ...describe(tag, opening),});return id;});diff --git a/packages/style-equivalence/src/extract/components.ts b/packages/style-equivalence/src/extract/components.tsnew file mode 100644index 00000000000..22b323a21e8--- /dev/null+++ b/packages/style-equivalence/src/extract/components.ts@@ -0,0 +1,56 @@+import ts from 'typescript';++import { literalOf } from './children';+import type { ComponentImport } from './types';++const STYLE_PROPS = new Set(['className', 'classNames', 'key', 'ref', 'style', 'styles']);++export const componentImport = (+ tag: string,+ importOf: Map<string, ts.ImportDeclaration>,+): ComponentImport | undefined => {+ const statement = importOf.get(tag);+ if (!statement || !ts.isStringLiteral(statement.moduleSpecifier)) return undefined;+ const source = statement.moduleSpecifier.text;+ const clause = statement.importClause;+ if (clause?.name?.text === tag) return { imported: 'default', source };+ const named = clause?.namedBindings;+ const element =+ named && ts.isNamedImports(named)+ ? named.elements.find((item) => item.name.text === tag)+ : undefined;+ return element ? { imported: (element.propertyName ?? element.name).text, source } : undefined;+};++const isLiteral = (attribute: ts.JsxAttribute) => {+ const { initializer } = attribute;+ if (!initializer || ts.isStringLiteral(initializer)) return true;+ return (+ ts.isJsxExpression(initializer) &&+ !!initializer.expression &&+ literalOf(initializer.expression) !== undefined+ );+};++export const propTextsOf = (opening: ts.JsxOpeningLikeElement, ast: ts.SourceFile) =>+ opening.attributes.properties+ .filter(+ (attribute): attribute is ts.JsxAttribute =>+ ts.isJsxAttribute(attribute) &&+ !STYLE_PROPS.has(attribute.name.getText(ast)) &&+ !isLiteral(attribute),+ )+ .map((attribute) => attribute.getText(ast).replaceAll(/\s+/g, ' '))+ .sort();++export const componentFields = (+ tag: string,+ opening: ts.JsxOpeningLikeElement,+ ast: ts.SourceFile,+ importOf: Map<string, ts.ImportDeclaration>,+) => {+ const component = /^[a-z]/.test(tag) ? undefined : componentImport(tag, importOf);+ if (!component) return {};+ const propTexts = propTextsOf(opening, ast);+ return { component, ...(propTexts.length ? { propTexts } : {}) };+};diff --git a/packages/style-equivalence/src/extract/cssConstants.ts b/packages/style-equivalence/src/extract/cssConstants.tsnew file mode 100644index 00000000000..15f20abda9c--- /dev/null+++ b/packages/style-equivalence/src/extract/cssConstants.ts@@ -0,0 +1,46 @@+import ts from 'typescript';++export const CSS_TAG_SOURCES = new Set(['@emotion/css', '@lobehub/ui', 'antd-style']);++const cssTemplate = (node: ts.Expression, isCssTag: (name: string) => boolean) =>+ ts.isTaggedTemplateExpression(node) && ts.isIdentifier(node.tag) && isCssTag(node.tag.text)+ ? node+ : undefined;++export const cssTemplatesOf = (+ initializer: ts.Expression,+ isCssTag: (name: string) => boolean,+): ts.TaggedTemplateExpression[] | undefined => {+ const direct = cssTemplate(initializer, isCssTag);+ if (direct) return [direct];+ if (+ !ts.isCallExpression(initializer) ||+ !ts.isIdentifier(initializer.expression) ||+ initializer.expression.text !== 'cx' ||+ !initializer.arguments.length+ )+ return undefined;+ const templates = initializer.arguments.map((argument) => cssTemplate(argument, isCssTag));+ return templates.every(Boolean) ? (templates as ts.TaggedTemplateExpression[]) : undefined;+};++export const cssConstantFactory = (+ ast: ts.SourceFile,+ name: string,+ templates: ts.TaggedTemplateExpression[],+) => {+ const members = templates.map((template) => `${name}: ${template.getText(ast)}`).join(',\n');+ const sf = ts.createSourceFile(+ ast.fileName,+ `${ast.text}\n;createStaticStyles(() => ({\n${members}\n}));\n`,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ );+ const statement = sf.statements.at(-1);+ return statement &&+ ts.isExpressionStatement(statement) &&+ ts.isCallExpression(statement.expression)+ ? statement.expression+ : undefined;+};diff --git a/packages/style-equivalence/src/extract/extract.test.ts b/packages/style-equivalence/src/extract/extract.test.tsindex af43786d4d3..b5db88ed065 100644--- a/packages/style-equivalence/src/extract/extract.test.ts+++ b/packages/style-equivalence/src/extract/extract.test.ts@@ -346,3 +346,54 @@ export const A = () => <span {...stylex.props(styles.activated)} />;});});});++describe('extractFile standalone css constants', () => {+ const code = `import { css, cssVar, cx } from '@lobehub/ui';++const hotArea = css\`+ width: 32px;++ &:hover {+ color: \${cssVar.colorText};+ }+\`;+const ghost = cx(css\`opacity: 0.5;\`);++export const Upload = () => (+ <div className={cx(hotArea)}>+ <span className={ghost} />+ </div>+);+`;++ it('treats a module-level css template as a style slot of its own name', () => {+ const extraction = extractFile(code, 'a.tsx', options);++ expect(extraction.elements.map(({ id, slots }) => ({ id, slots }))).toEqual([+ { id: 'Upload#0', slots: ['hotArea.hotArea'] },+ { id: 'Upload#1', slots: ['ghost.ghost'] },+ ]);+ expect(+ extraction.rules+ .filter((rule) => rule.slot === 'hotArea.hotArea')+ .map(({ declarations, selector }) => ({ declarations, selector })),+ ).toEqual([{ declarations: ['color: __I0__'], selector: '.__self__:hover' }]);+ expect(extraction.slotProperties?.['hotArea.hotArea']).toEqual(['color', 'width']);+ });++ it('keeps the constant and its imports in the prelude so the binding renders', () => {+ const { prelude } = extractFile(code, 'a.tsx', options);++ expect(prelude).toContain("import { css, cssVar, cx } from '@lobehub/ui';");+ expect(prelude).toContain('const hotArea = css`');+ expect(prelude).toContain('const ghost = cx(css`opacity: 0.5;`);');+ });++ it('ignores a css template whose tag is not imported from a style library', () => {+ const local = `const css = (parts) => parts.join('');+const hotArea = css\`width: 32px;\`;+export const Upload = () => <div className={hotArea} />;+`;+ expect(extractFile(local, 'a.tsx', options).elements).toEqual([]);+ });+});diff --git a/packages/style-equivalence/src/extract/globals.ts b/packages/style-equivalence/src/extract/globals.tsnew file mode 100644index 00000000000..0223298b0bb--- /dev/null+++ b/packages/style-equivalence/src/extract/globals.ts@@ -0,0 +1,16 @@+export const GLOBALS = new Set([+ 'Array',+ 'Boolean',+ 'JSON',+ 'Math',+ 'Number',+ 'Object',+ 'String',+ 'console',+ 'document',+ 'false',+ 'null',+ 'true',+ 'undefined',+ 'window',+]);diff --git a/packages/style-equivalence/src/extract/index.ts b/packages/style-equivalence/src/extract/index.tsindex a1b52d13e53..528c70d041a 100644--- a/packages/style-equivalence/src/extract/index.ts+++ b/packages/style-equivalence/src/extract/index.ts@@ -1,11 +1,17 @@import ts from 'typescript';import { aliasDeclaration, aliasOf, constInitializer } from './aliases';-import { booleanAttribute, isStateAttribute } from './attributes';+import {+ booleanAttribute,+ evaluableAttribute,+ isStateAttribute,+ spreadAttributes,+} from './attributes';import { collectChildren, literalOf } from './children';+import { componentFields, componentImport } from './components';import { localCondition, renderGuards } from './constraints';-import { parseRules } from './css';import { applicationIn, componentOfStatement, forwardsOf } from './forward';+import { GLOBALS } from './globals';import { globalStyleRules } from './globalStyles';import {declaredLocally,@@ -15,8 +21,10 @@ import {usageKinds,valueIdentifierNodes,} from './identifiers';+import { ownerOf } from './owner';import { applyRenderedStyle, renderedStyle, slotStylesOf } from './renderedStyle';-import { classifyRules, classNamesIn, foreignClassNames } from './selectors';+import { collectRules, memberOf } from './rules';+import { classifyRules, foreignClassNames } from './selectors';import { collectTables } from './tables';import { collectTopLevel } from './topLevel';import type {@@ -25,40 +33,15 @@ import type {LiteralValue,StyleBinding,StyleElement,- StyleRule,VariableKind,} from './types';-import { stylexUnsupported } from './unsupported';+import { localWrappers, wrapperFields } from './wrappers';+export { GLOBALS } from './globals';export type * from './types';-export const GLOBALS = new Set([- 'Array',- 'Boolean',- 'JSON',- 'Math',- 'Number',- 'Object',- 'String',- 'console',- 'document',- 'false',- 'null',- 'true',- 'undefined',- 'window',-]);-const CLASS_PROPS = new Set(['...', 'className', 'classNames']);-const ownerOf = (statement: ts.Statement, ast: ts.SourceFile) => {- if (ts.isVariableStatement(statement))- return statement.declarationList.declarations.map((d) => d.name.getText(ast)).join(',');- if (ts.isFunctionDeclaration(statement)) return statement.name?.text ?? 'default';- if (ts.isExportAssignment(statement)) return 'default';- return `statement@${ast.getLineAndCharacterOfPosition(statement.getStart(ast)).line + 1}`;-};-export const extractFile = (code: string,file: string,@@ -72,18 +55,8 @@ export const extractFile = (const layout = new Set(options.layoutComponents);const isReal = (tag: string) => {const component = options.realComponents?.[tag];- const statement = top.importOf.get(tag);- if (!component || !statement || !ts.isStringLiteral(statement.moduleSpecifier)) return false;- if (statement.moduleSpecifier.text !== component.source) return false;- const named = statement.importClause?.namedBindings;- return (- !!named &&- ts.isNamedImports(named) &&- named.elements.some(- (element) =>- element.name.text === tag && (element.propertyName ?? element.name).text === tag,- )- );+ const found = componentImport(tag, top.importOf);+ return !!component && found?.source === component.source && found.imported === tag;};const derived = new Map<string, string>();const isStyleName = (name: string) => top.styleSymbols.has(name) || markers.has(name);@@ -105,6 +78,12 @@ export const extractFile = (const slots = new Set<string>();const visit = (current: ts.Node) => {if (isJsxNode(current)) return;+ if (+ ts.isIdentifier(current) &&+ top.cssConstants.has(current.text) &&+ !(ts.isPropertyAccessExpression(current.parent) && current.parent.name === current)+ )+ slots.add(`${current.text}.${current.text}`);if (ts.isPropertyAccessExpression(current) &&ts.isIdentifier(current.expression) &&@@ -117,78 +96,17 @@ export const extractFile = (ts.forEachChild(current, visit);};if (!isJsxNode(node)) ts.forEachChild(node, visit);- if (ts.isPropertyAccessExpression(node)) visit(node);+ if (ts.isPropertyAccessExpression(node) || ts.isIdentifier(node)) visit(node);return slots;};- const gaps: string[] = [];- const rules: StyleRule[] = [];- const slotProperties: Record<string, string[]> = {};- const slotConditions: Record<string, string[]> = {};- const unsupported = stylexUnsupported(top.styleFactories);- for (const [symbol, factory] of top.styleFactories)- for (const adapter of options.adapters)- if (adapter.recognizeFactory(factory)) {- rules.push(...(adapter.rulesOf?.(symbol, factory) ?? []));- Object.assign(slotProperties, adapter.propertiesOf?.(symbol, factory));- Object.assign(slotConditions, adapter.conditionsOf?.(symbol, factory));- }- const globalClasses = new Set<string>();- for (const { binding, source } of top.stylesheets) {- const css = options.readStylesheet?.(file, source);- if (css === undefined) {- gaps.push(`STYLESHEET_UNREADABLE:${source}`);- continue;- }- const parsed = parseRules(css);- if (parsed.error) gaps.push(`STYLESHEET_UNPARSEABLE:${source}`);- const classes = new Set(parsed.rules.flatMap((rule) => classNamesIn(rule.selector)));- const owned =- binding.kind === 'module'- ? Object.fromEntries([...classes].map((name) => [name, `${binding.symbol}.${name}`]))- : {};- if (binding.kind === 'global') classes.forEach((name) => globalClasses.add(name));- for (const rule of parsed.rules) rules.push({ ...rule, owned, stylesheet: source });- }- for (const [local, imported] of top.importedClasses) {- if (!imported.factories.size && !imported.tokens.some((token) => globalClasses.has(token)))- continue;- derived.set(local, imported.expansion);- for (const [symbol, factory] of imported.factories) {- top.styleSymbols.add(symbol);- for (const adapter of options.adapters)- if (adapter.recognizeFactory(factory)) {- rules.push(...(adapter.rulesOf?.(symbol, factory) ?? []));- Object.assign(slotProperties, adapter.propertiesOf?.(symbol, factory));- Object.assign(slotConditions, adapter.conditionsOf?.(symbol, factory));- }- }- }- for (const statement of ast.statements)- if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const)- for (const declaration of statement.declarationList.declarations) {- const value = declaration.initializer;- if (!ts.isIdentifier(declaration.name) || !value || !ts.isStringLiteralLike(value))- continue;- if (value.text.split(/\s+/).some((token) => globalClasses.has(token)))- derived.set(declaration.name.text, JSON.stringify(value.text));- }- const memberOf = (node: ts.Identifier, expansion: string) => {- if (!ts.isPropertyAccessExpression(node.parent) || node.parent.expression !== node) return;- const parsed = ts.createSourceFile('x.ts', `(${expansion});`, ts.ScriptTarget.Latest, true);- const [statement] = parsed.statements;- let value = statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;- while (value && ts.isParenthesizedExpression(value)) value = value.expression;- if (!value || !ts.isObjectLiteralExpression(value)) return;- const name = node.parent.name.text;- const property = value.properties.find(- (item): item is ts.PropertyAssignment =>- ts.isPropertyAssignment(item) &&- (ts.isIdentifier(item.name) || ts.isStringLiteral(item.name)) &&- item.name.text === name,- );- return property?.initializer.getText(parsed);- };+ const { gaps, globalClasses, rules, slotConditions, slotProperties, unsupported } = collectRules(+ ast,+ file,+ top,+ options,+ derived,+ );const expandedOf = (expression: ts.Expression) => {const start = expression.getStart(ast);let text = expression.getText(ast);@@ -245,6 +163,8 @@ export const extractFile = (const literalProps: Record<string, LiteralValue> = {};const attributes: Record<string, string> = {};const attributeNames: ts.Identifier[] = [];+ const evaluated: Array<{ expression: ts.Expression; values: Record<string, string> }> = [];+ let modeledSpreads = 0;let iconNode: ts.Node | undefined;const slots = new Set<string>();const expressions: ts.Expression[] = [];@@ -282,6 +202,12 @@ export const extractFile = (if (ts.isJsxSpreadAttribute(attribute)) {const spread = styledConst(attribute.expression, '...');if (!referencesStyle(spread, '...')) {+ const values = spreadAttributes(attribute.expression, ast);+ if (values) {+ evaluated.push({ expression: attribute.expression, values });+ modeledSpreads++;+ continue;+ }lastForeign = position;continue;}@@ -337,6 +263,8 @@ export const extractFile = () {attributes[name] = expression.text;attributeNames.push(expression);+ } else if (isStateAttribute(name) && evaluableAttribute(expression)) {+ evaluated.push({ expression, values: { [name]: expression.getText(ast) } });} else if (name === 'style' &&!(ts.isIdentifier(expression) && GLOBALS.has(expression.text))@@ -381,6 +309,23 @@ export const extractFile = (names.add(node.text);kinds.set(node.text, [...(kinds.get(node.text) ?? []), 'boolean']);}+ for (const { expression, values } of evaluated) {+ const own = valueIdentifierNodes(expression, { skipJsx: true }).filter(+ (node) =>+ !GLOBALS.has(node.text) &&+ (declaredLocally(node) ||+ (!top.styleSymbols.has(node.text) && !top.require(node.text))),+ );+ const found = usageKinds(expression, new Set(own.map((node) => node.text)));+ if ([...found.values()].flat().includes('unknown')) continue;+ Object.assign(attributes, values);+ for (const node of own) {+ names.add(node.text);+ const condition = localCondition(node);+ if (condition) derivedConditions[node.text] = condition;+ }+ for (const [name, list] of found) kinds.set(name, [...(kinds.get(name) ?? []), ...list]);+ }const real = isReal(tag);const guards = renderGuards(node);if (layout.has(tag) || real) top.require(tag);@@ -400,6 +345,7 @@ export const extractFile = (classTokens.set(id, tokens);const element: StyleElement = {bindings,+ ...componentFields(tag, opening, ast, top.importOf),flags: [],id,literalProps,@@ -415,7 +361,8 @@ export const extractFile = (: {}),slots: [...slots].sort(),...(styleExpr ? { styleExpr } : {}),- ...(opening.attributes.properties.filter(ts.isJsxSpreadAttribute).length >+ ...(opening.attributes.properties.filter(ts.isJsxSpreadAttribute).length -+ modeledSpreads >bindings.filter((binding) => binding.spread).length? { foreignSpread: true }: {}),@@ -451,11 +398,23 @@ export const extractFile = (visit(statement, undefined);}- const plain = collectChildren(styled, ast, (tag) => {- const real = isReal(tag);- if (layout.has(tag) || real) top.require(tag);- return real;- });+ const wrappers = localWrappers(ast, styled);+ const plain = collectChildren(+ styled,+ ast,+ (tag) => {+ const real = isReal(tag);+ if (layout.has(tag) || real) top.require(tag);+ return real;+ },+ (tag, opening) => {+ const wrapped = wrappers.get(tag);+ if (wrapped) top.require(tag);+ return wrapped+ ? wrapperFields(wrapped, opening, ast)+ : componentFields(tag, opening, ast, top.importOf);+ },+ );const outsideReferences: string[] = [];for (const statement of ast.statements) {@@ -515,6 +474,7 @@ export const extractFile = (...(globalRules.length ? { globalRules } : {}),...(literalClasses.size ? { literalClasses: [...literalClasses].sort() } : {}),...(Object.keys(unsupported).length ? { unsupported } : {}),+ moduleNames: top.moduleNames(),outsideReferences,...(plain.length ? { plain } : {}),prelude: top.prelude(),diff --git a/packages/style-equivalence/src/extract/owner.ts b/packages/style-equivalence/src/extract/owner.tsnew file mode 100644index 00000000000..70912d179fa--- /dev/null+++ b/packages/style-equivalence/src/extract/owner.ts@@ -0,0 +1,9 @@+import ts from 'typescript';++export const ownerOf = (statement: ts.Statement, ast: ts.SourceFile) => {+ if (ts.isVariableStatement(statement))+ return statement.declarationList.declarations.map((d) => d.name.getText(ast)).join(',');+ if (ts.isFunctionDeclaration(statement)) return statement.name?.text ?? 'default';+ if (ts.isExportAssignment(statement)) return 'default';+ return `statement@${ast.getLineAndCharacterOfPosition(statement.getStart(ast)).line + 1}`;+};diff --git a/packages/style-equivalence/src/extract/rules.ts b/packages/style-equivalence/src/extract/rules.tsnew file mode 100644index 00000000000..8999aa291c1--- /dev/null+++ b/packages/style-equivalence/src/extract/rules.ts@@ -0,0 +1,83 @@+import ts from 'typescript';++import { parseRules } from './css';+import { classNamesIn } from './selectors';+import type { TopLevel } from './topLevel';+import type { ExtractOptions, StyleRule } from './types';+import { stylexUnsupported } from './unsupported';++export const memberOf = (node: ts.Identifier, expansion: string) => {+ if (!ts.isPropertyAccessExpression(node.parent) || node.parent.expression !== node) return;+ const parsed = ts.createSourceFile('x.ts', `(${expansion});`, ts.ScriptTarget.Latest, true);+ const [statement] = parsed.statements;+ let value = statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;+ while (value && ts.isParenthesizedExpression(value)) value = value.expression;+ if (!value || !ts.isObjectLiteralExpression(value)) return;+ const name = node.parent.name.text;+ const property = value.properties.find(+ (item): item is ts.PropertyAssignment =>+ ts.isPropertyAssignment(item) &&+ (ts.isIdentifier(item.name) || ts.isStringLiteral(item.name)) &&+ item.name.text === name,+ );+ return property?.initializer.getText(parsed);+};++export const collectRules = (+ ast: ts.SourceFile,+ file: string,+ top: TopLevel,+ options: ExtractOptions,+ derived: Map<string, string>,+) => {+ const gaps: string[] = [];+ const rules: StyleRule[] = [];+ const slotProperties: Record<string, string[]> = {};+ const slotConditions: Record<string, string[]> = {};+ const unsupported = stylexUnsupported(top.styleFactories);+ const addFactory = (symbol: string, factory: ts.CallExpression) => {+ for (const adapter of options.adapters)+ if (adapter.recognizeFactory(factory)) {+ rules.push(...(adapter.rulesOf?.(symbol, factory) ?? []));+ Object.assign(slotProperties, adapter.propertiesOf?.(symbol, factory));+ Object.assign(slotConditions, adapter.conditionsOf?.(symbol, factory));+ }+ };+ for (const [symbol, factory] of top.styleFactories) addFactory(symbol, factory);+ const globalClasses = new Set<string>();+ for (const { binding, source } of top.stylesheets) {+ const css = options.readStylesheet?.(file, source);+ if (css === undefined) {+ gaps.push(`STYLESHEET_UNREADABLE:${source}`);+ continue;+ }+ const parsed = parseRules(css);+ if (parsed.error) gaps.push(`STYLESHEET_UNPARSEABLE:${source}`);+ const classes = new Set(parsed.rules.flatMap((rule) => classNamesIn(rule.selector)));+ const owned =+ binding.kind === 'module'+ ? Object.fromEntries([...classes].map((name) => [name, `${binding.symbol}.${name}`]))+ : {};+ if (binding.kind === 'global') classes.forEach((name) => globalClasses.add(name));+ for (const rule of parsed.rules) rules.push({ ...rule, owned, stylesheet: source });+ }+ for (const [local, imported] of top.importedClasses) {+ if (!imported.factories.size && !imported.tokens.some((token) => globalClasses.has(token)))+ continue;+ derived.set(local, imported.expansion);+ for (const [symbol, factory] of imported.factories) {+ top.styleSymbols.add(symbol);+ addFactory(symbol, factory);+ }+ }+ for (const statement of ast.statements)+ if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const)+ for (const declaration of statement.declarationList.declarations) {+ const value = declaration.initializer;+ if (!ts.isIdentifier(declaration.name) || !value || !ts.isStringLiteralLike(value))+ continue;+ if (value.text.split(/\s+/).some((token) => globalClasses.has(token)))+ derived.set(declaration.name.text, JSON.stringify(value.text));+ }+ return { gaps, globalClasses, rules, slotConditions, slotProperties, unsupported };+};diff --git a/packages/style-equivalence/src/extract/topLevel.ts b/packages/style-equivalence/src/extract/topLevel.tsindex 5b58746a963..4fc831441ea 100644--- a/packages/style-equivalence/src/extract/topLevel.ts+++ b/packages/style-equivalence/src/extract/topLevel.ts@@ -1,5 +1,6 @@import ts from 'typescript';+import { CSS_TAG_SOURCES, cssConstantFactory, cssTemplatesOf } from './cssConstants';import { valueIdentifiers } from './identifiers';import { type ImportedClass, importedClassOf } from './importedClasses';import type { StyleAdapter, StylesheetBinding } from './types';@@ -7,9 +8,11 @@ import type { StyleAdapter, StylesheetBinding } from './types';const STYLESHEET = /\.css$/;export interface TopLevel {+ cssConstants: Set<string>;importedClasses: Map<string, ImportedClass>;importOf: Map<string, ts.ImportDeclaration>;keptStatements: Set<ts.Statement>;+ moduleNames: () => string[];prelude: () => string;require: (name: string) => boolean;sideEffectCss: string[];@@ -54,8 +57,24 @@ export const collectTopLevel = (const declarations = new Map<string, ts.Statement>();const styleSymbols = new Set<string>();const styleFactories = new Map<string, ts.CallExpression>();+ const cssConstants = new Set<string>();const importedClasses = new Map<string, ImportedClass>();const sideEffectCss: string[] = [];+ const isCssTag = (name: string) => {+ const statement = importOf.get(name);+ const named = statement?.importClause?.namedBindings;+ return (+ !!statement &&+ ts.isStringLiteral(statement.moduleSpecifier) &&+ CSS_TAG_SOURCES.has(statement.moduleSpecifier.text) &&+ !!named &&+ ts.isNamedImports(named) &&+ named.elements.some(+ (element) =>+ element.name.text === name && (element.propertyName ?? element.name).text === 'css',+ )+ );+ };const stylesheets: TopLevel['stylesheets'] = [];for (const statement of ast.statements) {@@ -116,6 +135,14 @@ export const collectTopLevel = () {styleSymbols.add(declaration.name.text);styleFactories.set(declaration.name.text, initializer);+ continue;+ }+ const templates = initializer && cssTemplatesOf(initializer, isCssTag);+ const factory = templates && cssConstantFactory(ast, declaration.name.text, templates);+ if (factory) {+ styleSymbols.add(declaration.name.text);+ styleFactories.set(declaration.name.text, factory);+ cssConstants.add(declaration.name.text);}}if (ts.isFunctionDeclaration(statement) && statement.name)@@ -168,10 +195,14 @@ export const collectTopLevel = (return lines.join('\n');};+ const moduleNames = () => [...new Set([...importOf.keys(), ...declarations.keys()])].sort();+return {+ cssConstants,importedClasses,importOf,keptStatements,+ moduleNames,prelude,require,sideEffectCss,diff --git a/packages/style-equivalence/src/extract/types.ts b/packages/style-equivalence/src/extract/types.tsindex 319bc37d368..338cb9db6c0 100644--- a/packages/style-equivalence/src/extract/types.ts+++ b/packages/style-equivalence/src/extract/types.ts@@ -18,11 +18,17 @@ export interface StyleBinding {spread: boolean;}+export interface ComponentImport {+ imported: string;+ source: string;+}+export interface StyleElement {aliases?: Record<string, string>;attributes?: Record<string, string>;bindings: StyleBinding[];children?: string[];+ component?: ComponentImport;derived?: Record<string, string>;flags: string[];foreignSpread?: boolean;@@ -35,6 +41,7 @@ export interface StyleElement {literalProps: Record<string, LiteralValue>;owner: string;parent?: string;+ propTexts?: string[];real?: boolean;runtimeStyle?: string;slots: string[];@@ -44,6 +51,7 @@ export interface StyleElement {subtreeTags?: Record<string, number>;tag: string;variables: VariableUse[];+ wraps?: string;}export interface StyleRule {@@ -65,6 +73,7 @@ export interface FileExtraction {gaps: string[];globalRules?: StyleRule[];literalClasses?: string[];+ moduleNames?: string[];outsideReferences: string[];plain?: StyleElement[];prelude: string;diff --git a/packages/style-equivalence/src/extract/wrappers.ts b/packages/style-equivalence/src/extract/wrappers.tsnew file mode 100644index 00000000000..a451424a16a--- /dev/null+++ b/packages/style-equivalence/src/extract/wrappers.ts@@ -0,0 +1,66 @@+import ts from 'typescript';++import { propTextsOf } from './components';+import { componentOfStatement } from './forward';+import { ownerOf } from './owner';+import type { StyleElement } from './types';++const unwrap = (node: ts.Expression): ts.Expression =>+ ts.isParenthesizedExpression(node) ? unwrap(node.expression) : node;++const returned = (body: ts.ConciseBody) => {+ if (!ts.isBlock(body)) return unwrap(body);+ const [statement, ...rest] = body.statements;+ return !rest.length && statement && ts.isReturnStatement(statement) && statement.expression+ ? unwrap(statement.expression)+ : undefined;+};++const forwardingRoot = (statement: ts.Statement, ast: ts.SourceFile) => {+ const fn = componentOfStatement(ast, statement);+ const [param, ...others] = fn?.parameters ?? [];+ if (!fn?.body || others.length || !param || !ts.isIdentifier(param.name)) return undefined;+ const root = returned(fn.body);+ if (!root || !ts.isJsxSelfClosingElement(root)) return undefined;+ const [first] = root.attributes.properties;+ return first &&+ ts.isJsxSpreadAttribute(first) &&+ ts.isIdentifier(first.expression) &&+ first.expression.text === param.name.text+ ? root+ : undefined;+};++export const localWrappers = (ast: ts.SourceFile, styled: Map<ts.Node, StyleElement>) => {+ const wrappers = new Map<string, StyleElement>();+ for (const statement of ast.statements) {+ const root = forwardingRoot(statement, ast);+ const element = root && styled.get(root);+ if (+ !root ||+ !element?.component ||+ element.parent ||+ Object.keys(element.literalProps).length ||+ element.propTexts?.length ||+ element.attributes ||+ element.inlineStyle ||+ root.attributes.properties.length !== element.bindings.length + 1+ )+ continue;+ wrappers.set(ownerOf(statement, ast), element);+ }+ return wrappers;+};++export const wrapperFields = (+ wrapped: StyleElement,+ opening: ts.JsxOpeningLikeElement,+ ast: ts.SourceFile,+) => {+ const propTexts = propTextsOf(opening, ast);+ return {+ ...(propTexts.length ? { propTexts } : {}),+ slots: wrapped.slots,+ wraps: wrapped.id,+ };+};diff --git a/packages/style-equivalence/src/generate/module.ts b/packages/style-equivalence/src/generate/module.tsindex 4955c7c3af6..5e199ae38e0 100644--- a/packages/style-equivalence/src/generate/module.ts+++ b/packages/style-equivalence/src/generate/module.ts@@ -28,9 +28,13 @@ interface ChainContext {forward?: { application?: string; element: ForwardElement };inner?: Record<string, InnerNode[]>;layout: Set<string>;+ masks?: Array<{ index: number; style: string }>;omitted?: number[];+ pairId?: string;probed: Set<string>;real?: Record<string, RealComponent>;+ realIds?: Set<string>;+ realLeaf?: boolean;samples?: InnerNode[];}@@ -58,10 +62,13 @@ const renderChain = (chain: StyleElement[], context: ChainContext, depth = 0): sconst [element, ...rest] = chain;if (!rest.length && context.forward)return renderForward(element.id, context.forward.element, context.forward.application);- const real = rendersReal(element, !rest.length, context.real);+ const learned = !!context.realIds?.has(element.id);+ const real = rendersReal(element, !rest.length, context.real) || learned;const tag = real ? element.tag : placementTag(element, layout);const substituted = tag !== element.tag;const attributes = [`data-synthetic-element=${JSON.stringify(element.id)}`];+ if (learned && context.pairId)+ attributes.push(`data-synthetic-pair=${JSON.stringify(context.pairId)}`);for (const [name, value] of Object.entries(element.literalProps))if (keepLiteral(name, substituted)) attributes.push(renderLiteral(name, value));if (element.inlineStyle) attributes.push(`style={(${element.inlineStyle})}`);@@ -77,10 +84,13 @@ const renderChain = (chain: StyleElement[], context: ChainContext, depth = 0): s}if (element.runtimeStyle && probed.has(element.runtimeStyle))attributes.push(`style={${element.runtimeStyle}}`);+ const mask = context.masks?.find((item) => item.index === depth);+ if (mask) attributes.push(`style={(${mask.style})}`);const component = real ? context.real?.[element.tag] : undefined;if (component?.sample) attributes.push(component.sample(sampleContent(context.samples)));const open = `<${tag} ${attributes.join(' ')}`;- if (VOID_TAGS.has(tag) || component?.leaf) return `<>${open} />${neutral.join('')}</>`;+ if (VOID_TAGS.has(tag) || component?.leaf || (learned && context.realLeaf))+ return `<>${open} />${neutral.join('')}</>`;const inner = rest.length? renderChain(rest, context, depth + 1): `{${JSON.stringify(SAMPLE_TEXT)}}`;@@ -178,6 +188,27 @@ const preludeNames = (prelude: string) => {return names;};+const componentImports = (+ plan: FilePlan,+ side: Side,+ byId: Map<string, StyleElement>,+ prelude: Set<string>,+) =>+ plan.cases.flatMap((entry) =>+ (entry.realElements?.[side] ?? []).flatMap((id) => {+ const element = byId.get(id);+ const component = element?.component;+ if (!element || !component || prelude.has(element.tag)) return [];+ const source = JSON.stringify(component.source);+ if (component.imported === 'default') return [`import ${element.tag} from ${source};`];+ const name =+ component.imported === element.tag+ ? element.tag+ : `${component.imported} as ${element.tag}`;+ return [`import { ${name} } from ${source};`];+ }),+ );+const counterpartEntries = (plan: FilePlan,side: Side,@@ -298,9 +329,13 @@ export const generateModule = (},inner: entry.inner,layout,+ masks: entry.inlineMasks?.[side],omitted: entry.neutralOmitted,probed,real: config.realComponents,+ pairId: entry.realElements ? entry.elementIds.base : undefined,+ realIds: new Set(entry.realElements?.[side]),+ realLeaf: entry.realLeaf,samples: entry.samples,};return `${JSON.stringify(entry.key)}: (__v: Record<string, boolean | string>) => { ${lines.join(' ')} return (${renderChain(chain, context)}); }`;@@ -315,17 +350,12 @@ export const generateModule = (config,),);- const counterparts = counterpartEntries(- plan,- side,- byId,- preludeNames(extraction.prelude),- config,- );+ const prelude = preludeNames(extraction.prelude);+ const counterparts = counterpartEntries(plan, side, byId, prelude, config);unpaired.push(...counterparts.entries);return [extraction.prelude,- ...counterparts.imports,+ ...new Set([...counterparts.imports, ...componentImports(plan, side, byId, prelude)]),...forwardImports(plan.cases, side),config.cxFallback? `import { ${config.cxFallback.name} as __cx } from ${JSON.stringify(config.cxFallback.source)};`diff --git a/packages/style-equivalence/src/mutation/operators.ts b/packages/style-equivalence/src/mutation/operators.tsindex ab316765655..16014315b61 100644--- a/packages/style-equivalence/src/mutation/operators.ts+++ b/packages/style-equivalence/src/mutation/operators.ts@@ -212,8 +212,8 @@ const templateMutations = (code: string, sf: ts.SourceFile, template: ts.Templatexport const declarationMutations = (code: string, symbol: string, member: string): Mutation[] => {const sf = parseSource(code, 'styles.tsx');const property = findStyleMember(sf, symbol, member);- if (!property) return [];- const value = property.initializer;+ const value = property?.initializer;+ if (!value) return [];if (ts.isObjectLiteralExpression(value)) return firstOf(objectMutations(code, sf, value));if (ts.isTaggedTemplateExpression(value))return firstOf(templateMutations(code, sf, value.template));diff --git a/packages/style-equivalence/src/pipeline/synthesize.ts b/packages/style-equivalence/src/pipeline/synthesize.tsindex 528f4571213..9a6312ed9cc 100644--- a/packages/style-equivalence/src/pipeline/synthesize.ts+++ b/packages/style-equivalence/src/pipeline/synthesize.ts@@ -8,6 +8,7 @@ import { generateHost, HOST_HTML } from '../generate/host';import { generateModule } from '../generate/module';import { carriedClasses, globalRulesChanged } from '../plan/globalRules';import { type FilePlan, planFile, type Side } from '../plan/planFile';+import type { ShapeBook } from '../plan/shapes';import { packageFile } from '../source/aliases';import { resolveSpecifier } from '../source/declarations';import type { ScopeFile } from '../source/scope';@@ -54,6 +55,7 @@ export const synthesize = async (scope: ScopeFile[],roots: Record<Side, string>,config: ProjectConfig,+ shapes?: ShapeBook,): Promise<Synthesis> => {const extractions: Synthesis['extractions'] = {};const plans: FilePlan[] = [];@@ -75,7 +77,7 @@ export const synthesize = async (});};const pair = { base: await read('base'), head: await read('head') };- const plan = planFile(file, pair.base, pair.head, config);+ const plan = planFile(file, pair.base, pair.head, { ...config, shapes });attachCounterparts(plan, { code, extractions: pair, real: config.realComponents });markUnchangedChains(plan, pair, {aliases: config.aliases,diff --git a/packages/style-equivalence/src/plan/descendants.ts b/packages/style-equivalence/src/plan/descendants.tsindex 380ac1a6d54..b265b717ee3 100644--- a/packages/style-equivalence/src/plan/descendants.ts+++ b/packages/style-equivalence/src/plan/descendants.ts@@ -1,11 +1,9 @@import type { FileExtraction, StyleElement, StyleRule } from '../extract';import { targetsInnerTag } from '../extract/selectors';import { parseSelectorList, type SelectorNode } from './selectorTree';+import { reachesShape, type ShapeBook, shapeOf, shapePaired, type ShapeStep } from './shapes';-interface Step {- child: boolean;- tag: string;-}+type Step = ShapeStep;const sortedJson = (value: Record<string, unknown>) =>JSON.stringify(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));@@ -52,6 +50,9 @@ const targets = (parent: StyleElement, tag: string, rules: StyleRule[]) =>stepsOf(rule, scopes)?.some((step) => step.tag === '*' || step.tag === tag),);+const allSteps = (parent: StyleElement, rules: StyleRule[]) =>+ rulesOf(parent, rules).flatMap(({ rule, scopes }) => stepsOf(rule, scopes) ?? []);+export const innerSteps = (parent: StyleElement, rules: StyleRule[]) => {const steps: Step[] = [];for (const { rule, scopes } of rulesOf(parent, rules)) {@@ -71,8 +72,10 @@ export const counterparts = (const baseById = new Map(elementsOf(base).map((element) => [element.id, element]));const headById = new Map(elementsOf(head).map((element) => [element.id, element]));const pairedParent = new Map(pairs.map(([left, right]) => [right.id, left]));+ const tagOf = (element: StyleElement | undefined) =>+ element?.wraps ? headById.get(element.wraps)?.tag : element?.tag;const tagsOf = (ids: string[], byId: Map<string, StyleElement>) =>- JSON.stringify(ids.map((id) => byId.get(id)?.tag));+ JSON.stringify(ids.map((id) => tagOf(byId.get(id))));return (element: StyleElement) => {const parent = element.parent ? pairedParent.get(element.parent) : undefined;const headParent = element.parent ? headById.get(element.parent) : undefined;@@ -84,7 +87,7 @@ export const counterparts = (return counterpart &&!counterpart.bindings.length &&!counterpart.flags.length &&- counterpart.tag === element.tag &&+ counterpart.tag === tagOf(element) &&sortedJson(counterpart.literalProps) === sortedJson(element.literalProps) &&sortedJson(counterpart.attributes ?? {}) === sortedJson(element.attributes ?? {})? { counterpart, parent }@@ -97,33 +100,85 @@ export const replacedDescendants = (head: FileExtraction,pairs: Array<[StyleElement, StyleElement]>,unpairedHead: StyleElement[],+ shapes?: ShapeBook,) => {const lookup = counterparts(base, head, pairs);const replaced: Array<[StyleElement, StyleElement]> = [];+ const learned = new Set<StyleElement>();for (const element of unpairedHead) {const found = lookup(element);- if (found && targets(found.parent, found.counterpart.tag, base.rules))+ if (!found) continue;+ if (targets(found.parent, found.counterpart.tag, base.rules))+ replaced.push([found.counterpart, element]);+ else if (shapePaired(found.counterpart, element, allSteps(found.parent, base.rules), shapes)) {replaced.push([found.counterpart, element]);+ learned.add(element);+ }+ }+ const headById = new Map(elementsOf(head).map((element) => [element.id, element]));+ const usages = new Map<StyleElement, StyleElement[]>();+ for (const usage of head.plain ?? []) {+ const wrapped = usage.wraps ? headById.get(usage.wraps) : undefined;+ if (!wrapped) continue;+ usages.set(wrapped, [...(usages.get(wrapped) ?? []), usage]);+ const found = lookup(usage);+ const effective = { ...usage, bindings: wrapped.bindings, component: wrapped.component };+ if (+ found &&+ shapePaired(found.counterpart, effective, allSteps(found.parent, base.rules), shapes)+ ) {+ replaced.push([found.counterpart, usage]);+ learned.add(usage);+ }}- return replaced;+ const wrapped = new Set(+ [...usages]+ .filter(([, list]) => list.every((usage) => learned.has(usage)))+ .map(([item]) => item),+ );+ return { learned, replaced, wrapped };+};++const shapeReached = (child: StyleElement | undefined, step: Step, shapes?: ShapeBook) => {+ const shape = child && shapeOf(child, 'base', shapes);+ return !!shape && reachesShape(step, shape);};export const parentCovered = (parent: StyleElement,base: FileExtraction,rendered: Set<string>,+ shapes?: ShapeBook,) => {const steps = innerSteps(parent, base.rules);if (!steps?.length) return false;const byId = new Map(elementsOf(base).map((element) => [element.id, element]));const children = (parent.children ?? []).map((id) => byId.get(id));return steps.every((step) => {- const direct = children.filter((child) => child?.tag === step.tag);+ const literal = children.filter((child) => child?.tag === step.tag);+ const learned = children.filter((child) => shapeReached(child, step, shapes));+ const direct = [...literal, ...learned];if (direct.some((child) => !rendered.has(child!.id))) return false;- return step.child || (parent.subtreeTags?.[step.tag] ?? 0) === direct.length;+ return step.child || (parent.subtreeTags?.[step.tag] ?? 0) === literal.length;});};+export const childrenLearned = (+ parent: StyleElement,+ base: FileExtraction,+ shapes: ShapeBook | undefined,+) => {+ const byId = new Map(elementsOf(base).map((element) => [element.id, element]));+ const children = (parent.children ?? []).map((id) => byId.get(id));+ const deep = innerSteps(parent, base.rules)?.some((step) => !step.child) ?? true;+ return children.every(+ (child) =>+ !!child &&+ (/^[a-z]/.test(child.tag) || (!!child.component && !!shapeOf(child, 'base', shapes))) &&+ !(deep && child.subtreeComponents?.length),+ );+};+export const childCovered = (parent: StyleElement, child: StyleElement, rules: StyleRule[]) => {const steps = innerSteps(parent, rules);return (diff --git a/packages/style-equivalence/src/plan/inlineStyle.test.ts b/packages/style-equivalence/src/plan/inlineStyle.test.tsindex a7ba6f5b553..b859822869e 100644--- a/packages/style-equivalence/src/plan/inlineStyle.test.ts+++ b/packages/style-equivalence/src/plan/inlineStyle.test.ts@@ -42,16 +42,20 @@ const plan = (after: string, before = base) => {};describe('an inline style moved from the style prop into sx', () => {- it('renders neither side with it when the expression is the same', () => {+ it('renders both sides with the same unset mask when the expression is the same', () => {const { pair, plan: result } = plan(head());const [entry] = result.cases;expect(entry.flags).toEqual([]);expect(entry.variables).toEqual([]);expect(entry.inlineStyles?.head).toEqual([- { binding: 0, index: 0, without: 'sx([styles.divider], undefined, undefined)' },+ { binding: 0, index: 0, without: "sx([styles.divider], undefined, { left: 'unset' })" },]);- const module = generateModule(pair.head, result, 'head', { layoutComponents: [] });- expect(module).not.toContain('view.ratio');+ expect(entry.inlineMasks?.base).toEqual([{ index: 0, style: "{ left: 'unset' }" }]);+ const headModule = generateModule(pair.head, result, 'head', { layoutComponents: [] });+ expect(headModule).not.toContain('view.ratio');+ const baseModule = generateModule(pair.base, result, 'base', { layoutComponents: [] });+ expect(baseModule).toContain("style={({ left: 'unset' })}");+ expect(baseModule).not.toContain('view.ratio');});it('keeps the variable when the style expression changed', () => {@@ -89,7 +93,80 @@ describe('an inline style moved from the style prop into sx', () => {const [entry] = plan(headWith(`sx(styles.divider, ${style}, 'caller')`)).plan.cases;expect(entry.flags).toEqual([]);expect(entry.inlineStyles?.head).toEqual([- { binding: 0, index: 0, without: "sx(styles.divider, undefined, 'caller')" },+ { binding: 0, index: 0, without: "sx(styles.divider, { left: 'unset' }, 'caller')" },+ ]);+ });+});++const limitBase = (style: string) => `import { createStaticStyles } from '@lobehub/ui';++import { LIMIT, widthOf } from './layout';++const styles = createStaticStyles(({ css }) => ({ column: css\`max-width: 1280px;\` }));++export const Column = ({ size, tab }) => <div className={styles.column} style={${style}} />;+`;++const limitHead = (style: string) => `import * as stylex from '@stylexjs/stylex';++import { sx } from '@/styles/sx';++import { LIMIT, widthOf } from './layout';++const styles = stylex.create({ column: { width: '100%' } });++export const Column = ({ size, tab }) => <div {...sx([styles.column], undefined, ${style})} />;+`;++const limitCase = (style: string) => plan(limitHead(style), limitBase(style)).plan.cases[0];++describe('a shared inline style that overrides the class on both sides', () => {+ it('masks a module constant without flagging it', () => {+ const entry = limitCase('{ maxWidth: LIMIT }');+ expect(entry.flags).toEqual([]);+ expect(entry.inlineMasks?.base).toEqual([{ index: 0, style: "{ maxWidth: 'unset' }" }]);+ });++ it('masks literals, member reads of constants and arithmetic without flagging them', () => {+ const entry = limitCase("{ maxWidth: LIMIT.wide * 2, minWidth: 'min-content', margin: 0 }");+ expect(entry.flags).toEqual([]);+ expect(entry.inlineMasks?.base).toEqual([+ { index: 0, style: "{ maxWidth: 'unset', minWidth: 'unset', margin: 'unset' }" },+ ]);+ });++ it('compares a call that may return nothing both with and without the mask', () => {+ const entry = limitCase("{ maxWidth: tab === 'flow' ? 1500 : widthOf(tab) }");+ expect(entry.flags).toEqual([]);+ expect(entry.combos).toEqual([{ __inlineStyle: true }, { __inlineStyle: false }]);+ expect(entry.inlineMasks?.base).toEqual([+ { index: 0, style: "__v.__inlineStyle ? { maxWidth: 'unset' } : undefined" },+ ]);+ expect(entry.inlineStyles?.head?.[0].without).toBe(+ "sx([styles.column], undefined, __v.__inlineStyle ? { maxWidth: 'unset' } : undefined)",+ );+ });++ it('toggles the mask for a prop that may be absent', () => {+ expect(limitCase('{ width: size }').combos).toEqual([+ { __inlineStyle: true },+ { __inlineStyle: false },+ ]);+ });++ it('toggles the mask for a value that can short-circuit to nothing', () => {+ expect(limitCase('{ maxWidth: LIMIT ?? undefined }').combos).toHaveLength(2);+ });++ it('renders a certain mask in every combination without toggling it', () => {+ expect(limitCase('{ maxWidth: LIMIT }').combos).toEqual([{}]);+ });++ it('drops a style it cannot name every property of, as before', () => {+ const entry = limitCase('{ ...LIMIT, maxWidth: 1 }');+ expect(entry.inlineMasks).toBeUndefined();+ expect(entry.inlineStyles?.head).toEqual([+ { binding: 0, index: 0, without: 'sx([styles.column], undefined, undefined)' },]);});});diff --git a/packages/style-equivalence/src/plan/inlineStyle.ts b/packages/style-equivalence/src/plan/inlineStyle.tsindex cd46222efc9..a64403a2189 100644--- a/packages/style-equivalence/src/plan/inlineStyle.ts+++ b/packages/style-equivalence/src/plan/inlineStyle.ts@@ -7,12 +7,87 @@ const compact = (text: string) => text.replaceAll(/\s+/g, '').replaceAll(/,(?=[)interface SxStyle {binding: number;+ certain?: boolean;+ mask?: string;names: string[];style: string;without: string;}-const sxStyleOf = (element: StyleElement, styleExpr: string): SxStyle | undefined => {+const unwrap = (node: ts.Expression): ts.Expression =>+ ts.isParenthesizedExpression(node) ||+ ts.isAsExpression(node) ||+ ts.isSatisfiesExpression(node) ||+ ts.isNonNullExpression(node) ||+ ts.isTypeAssertionExpression(node)+ ? unwrap(node.expression)+ : node;++const ARITHMETIC = new Set([+ ts.SyntaxKind.AsteriskToken,+ ts.SyntaxKind.MinusToken,+ ts.SyntaxKind.PercentToken,+ ts.SyntaxKind.PlusToken,+ ts.SyntaxKind.SlashToken,+]);++const neverEmpty = (input: ts.Expression, constants: ReadonlySet<string>): boolean => {+ const node = unwrap(input);+ if (+ ts.isNumericLiteral(node) ||+ ts.isStringLiteral(node) ||+ ts.isNoSubstitutionTemplateLiteral(node) ||+ ts.isTemplateExpression(node)+ )+ return true;+ if (ts.isIdentifier(node)) return constants.has(node.text);+ if (ts.isPrefixUnaryExpression(node)) return neverEmpty(node.operand, constants);+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))+ return !node.questionDotToken && neverEmpty(node.expression, constants);+ if (ts.isBinaryExpression(node))+ return (+ ARITHMETIC.has(node.operatorToken.kind) &&+ neverEmpty(node.left, constants) &&+ neverEmpty(node.right, constants)+ );+ if (ts.isConditionalExpression(node))+ return neverEmpty(node.whenTrue, constants) && neverEmpty(node.whenFalse, constants);+ return false;+};++const IDENTIFIER = /^[$A-Z_a-z][\w$]*$/;++export const INLINE_MASK = '__inlineStyle';++const maskOf = (input: ts.Expression, constants: ReadonlySet<string>) => {+ const node = unwrap(input);+ if (!ts.isObjectLiteralExpression(node) || !node.properties.length) return undefined;+ const keys: string[] = [];+ let certain = true;+ for (const property of node.properties) {+ if (ts.isShorthandPropertyAssignment(property)) {+ keys.push(property.name.text);+ certain &&= neverEmpty(property.name, constants);+ continue;+ }+ if (+ !ts.isPropertyAssignment(property) ||+ !(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))+ )+ return undefined;+ keys.push(property.name.text);+ certain &&= neverEmpty(property.initializer, constants);+ }+ const entries = keys.map((key) => `${IDENTIFIER.test(key) ? key : JSON.stringify(key)}: 'unset'`);+ const mask = `{ ${entries.join(', ')} }`;+ return { certain, mask: certain ? mask : `__v.${INLINE_MASK} ? ${mask} : undefined` };+};++const sxStyleOf = (+ element: StyleElement,+ styleExpr: string,+ constants: ReadonlySet<string>,+): SxStyle | undefined => {for (const [index, binding] of element.bindings.entries()) {if (!binding.spread) continue;const source = ts.createSourceFile('t.ts', `(${binding.expr});`, ts.ScriptTarget.Latest, true);@@ -29,7 +104,8 @@ const sxStyleOf = (element: StyleElement, styleExpr: string): SxStyle | undefineconst offset = 1;const start = style.getStart(source) - offset;const end = style.end - offset;- const without = `${binding.expr.slice(0, start)}undefined${binding.expr.slice(end)}`;+ const masked = maskOf(style, constants);+ const without = `${binding.expr.slice(0, start)}${masked?.mask ?? 'undefined'}${binding.expr.slice(end)}`;const kept = new Set(call.arguments.filter((_, index) => index !== position)@@ -37,6 +113,7 @@ const sxStyleOf = (element: StyleElement, styleExpr: string): SxStyle | undefine);return {binding: index,+ ...masked,names: [...valueIdentifiers(style)].filter((name) => !kept.has(name)),style: compact(style.getText(source)),without,@@ -47,13 +124,18 @@ const sxStyleOf = (element: StyleElement, styleExpr: string): SxStyle | undefineexport interface SharedStyle {binding: number;+ certain?: boolean;index: number;+ mask?: string;names: string[];reordered: boolean;without: string;}-export const sharedInlineStyles = (chains: Record<'base' | 'head', StyleElement[]>) => {+export const sharedInlineStyles = (+ chains: Record<'base' | 'head', StyleElement[]>,+ moduleNames: Partial<Record<'base' | 'head', readonly string[]>> = {},+) => {const found: Partial<Record<'base' | 'head', SharedStyle[]>> = {};if (chains.base.length !== chains.head.length) return found;chains.base.forEach((left, index) => {@@ -63,10 +145,16 @@ export const sharedInlineStyles = (chains: Record<'base' | 'head', StyleElement[['base', left, right],] as const) {if (!other.styleExpr || other.runtimeStyle || other.inlineStyle) continue;- const sx = sxStyleOf(own, other.styleExpr);+ const variables = new Set([...own.variables, ...other.variables].map(({ name }) => name));+ const inBase = new Set(moduleNames.base ?? []);+ const constants = new Set(+ (moduleNames.head ?? []).filter((name) => inBase.has(name) && !variables.has(name)),+ );+ const sx = sxStyleOf(own, other.styleExpr, constants);if (!sx) continue;(found[side] ??= []).push({binding: sx.binding,+ ...(sx.mask ? { certain: sx.certain, mask: sx.mask } : {}),index,names: sx.names,reordered:diff --git a/packages/style-equivalence/src/plan/planFile.ts b/packages/style-equivalence/src/plan/planFile.tsindex d745e23bfd5..84e8c80c002 100644--- a/packages/style-equivalence/src/plan/planFile.ts+++ b/packages/style-equivalence/src/plan/planFile.ts@@ -8,14 +8,20 @@ import type {} from '../extract';import { mergeKinds, valueIdentifiers } from '../extract/identifiers';import { type Combo, combosFor, DOMAIN_COMBO_LIMIT } from './combos';-import { childCovered, elementsOf, parentCovered, replacedDescendants } from './descendants';+import {+ childCovered,+ childrenLearned,+ elementsOf,+ parentCovered,+ replacedDescendants,+} from './descendants';import {forwardedDescendants,forwardedInside,type ForwardPlan,partlyForwarded,} from './forwarded';-import { sharedInlineStyles } from './inlineStyle';+import { INLINE_MASK, sharedInlineStyles, type SharedStyle } from './inlineStyle';import type { InnerNode } from './inner';import { keptEmotionRules } from './kept';import { bindKnobs, parseExpression } from './knobs';@@ -31,6 +37,7 @@ import {import { runtimeStyleProbe, styleDropped } from './probes';import { reachableCombos } from './reachable';import { realItemsOf, rendersReal, sampleTargets, standInsOf } from './real';+import { type ShapeBook, shapeOf } from './shapes';import { tableDomain } from './tables';export { isIntrinsicTag } from './placement';@@ -62,11 +69,14 @@ export interface PlanCase {flags: string[];forward?: ForwardPlan;forwardedParam?: string;+ inlineMasks?: Partial<Record<Side, Array<{ index: number; style: string }>>>;inlineStyles?: Partial<Record<Side, Array<{ binding: number; index: number; without: string }>>>;inner?: Record<string, InnerNode[]>;key: string;knobs?: string[];neutralOmitted?: number[];+ realElements?: Record<Side, string[]>;+ realLeaf?: true;samples?: InnerNode[];standIns?: Partial<Record<Side, string[]>>;variables: PlanVariable[];@@ -93,6 +103,7 @@ export interface UnpairedCounterpart {export interface PlanConfig {layoutComponents: string[];realComponents?: Record<string, RealComponent>;+ shapes?: ShapeBook;}const declarationFree = (element: StyleElement) =>@@ -194,9 +205,19 @@ export const planFile = (}for (const [owner, elements] of headOwners)if (!baseOwners.has(owner)) unpairedHead.push(...elements);- const replaced = replacedDescendants(base, head, pairs, unpairedHead);+ const { learned, replaced, wrapped } = replacedDescendants(+ base,+ head,+ pairs,+ unpairedHead,+ config.shapes,+ );const replacedHead = new Set(replaced.map(([, right]) => right));- unpairedHead.splice(0, unpairedHead.length, ...unpairedHead.filter((e) => !replacedHead.has(e)));+ unpairedHead.splice(+ 0,+ unpairedHead.length,+ ...unpairedHead.filter((e) => !replacedHead.has(e) && !wrapped.has(e)),+ );pairs.push(...replaced);const forwarded = forwardedDescendants(base, head, pairs, unpairedHead, config.realComponents);const forwardOf = new Map(forwarded.map((entry) => [entry.pair[1], entry.forward]));@@ -212,9 +233,14 @@ export const planFile = ();pairs.push(...forwarded.map((entry) => entry.pair), ...inside.map((entry) => entry.pair));const rendered = new Set(pairs.map(([left]) => left.id));+ const learnedParents = new Set(+ replaced.filter(([, right]) => learned.has(right)).map(([left]) => left.parent!),+ );const covered = new Set(- [...new Set(replaced.map(([left]) => left.parent!))].filter((id) =>- parentCovered(byId.base.get(id)!, base, rendered),+ [...new Set(replaced.map(([left]) => left.parent!))].filter(+ (id) =>+ parentCovered(byId.base.get(id)!, base, rendered, config.shapes) &&+ (!learnedParents.has(id) || childrenLearned(byId.base.get(id)!, base, config.shapes)),),);const moved = movedStylesheets(base, head, pairs);@@ -252,11 +278,14 @@ export const planFile = (.filter(({ proof }) => proof.exhaustive).flatMap(({ index }) => [chains.base[index], chains.head[index]]),);- if (left.tag !== right.tag) flags.add('TAG_CHANGED');+ if (left.tag !== (right.wraps ? byId.head.get(right.wraps)?.tag : right.tag))+ flags.add('TAG_CHANGED');for (const item of chains.head)for (const slot of item.slots)for (const key of head.unsupported?.[slot] ?? []) flags.add(`STYLEX_UNSUPPORTED:${key}`);const realItems = realItemsOf(chains, config.realComponents);+ const realElements = learned.has(right) ? { base: [left.id], head: [right.id] } : undefined;+ if (realElements) [left, right].forEach((item) => realItems.add(item));for (const item of [...chains.base, ...chains.head]) {const real = realItems.has(item) || resolved.has(item);if (!isIntrinsicTag(item.tag) && !layout.has(item.tag) && !real)@@ -276,6 +305,7 @@ export const planFile = (item.flags.forEach((flag) => !cleared(flag) && flags.add(flag));}if (isReplaced) evidence.push('DESCENDANT_REPLACED');+ if (realElements) evidence.push('COMPONENT_SHAPE_LEARNED');if (forward) evidence.push('FORWARDED_RENDERED');if (param) evidence.push('FORWARDED_PROP_ABSENT');const partialFlag = partial.get(left.id);@@ -318,7 +348,21 @@ export const planFile = (for (const { index, proof } of [...movedAt, ...keptAt])if (proof.nodes.length) inner[index] = [...(inner[index] ?? []), ...proof.nodes];const structural = flags.size > 0;- const shared = sharedInlineStyles(chains);+ const shared = sharedInlineStyles(chains, {+ base: base.moduleNames,+ head: head.moduleNames,+ });+ const inlineMasks: NonNullable<PlanCase['inlineMasks']> = {};+ for (const [side, list] of Object.entries(shared) as Array<[Side, SharedStyle[]]>)+ for (const { index, mask } of list)+ if (mask)+ (inlineMasks[side === 'base' ? 'head' : 'base'] ??= []).push({ index, style: mask });+ const toggled = Object.values(shared).some((list) =>+ list.some((style) => style.mask && !style.certain),+ );+ const targetShared = Object.values(shared).some((list) =>+ list.some((style) => style.index === chains.base.length - 1),+ );const variables = new Map<string, PlanVariable>();for (const side of ['base', 'head'] as const)for (const [itemIndex, item] of chains[side].entries())@@ -377,10 +421,16 @@ export const planFile = (if (Object.keys(modeling.used).length && modeling.combos.length > DOMAIN_COMBO_LIMIT)modeling = model({});const { knobs, modeled, pairwise } = modeling;- const combos = knobs ? modeling.combos : reachableCombos(modeling.combos, chains);- if (combos.length < modeling.combos.length) evidence.push('COMBOS_UNREACHABLE_DROPPED');+ const reached = knobs ? modeling.combos : reachableCombos(modeling.combos, chains);+ const combos = toggled+ ? reached.flatMap((combo) => [+ { ...combo, [INLINE_MASK]: true },+ { ...combo, [INLINE_MASK]: false },+ ])+ : reached;+ if (reached.length < modeling.combos.length) evidence.push('COMBOS_UNREACHABLE_DROPPED');modeling.added.forEach((flag) => flags.add(flag));- if (styleDropped(left, right, probes)) flags.add('RUNTIME_STYLE_DROPPED');+ if (!targetShared && styleDropped(left, right, probes)) flags.add('RUNTIME_STYLE_DROPPED');if (knobs) evidence.push('CONDITION_KNOBS');if (Object.keys(modeling.used).length) evidence.push('TABLE_KEYS');if (modeled.some((variable) => variable.probe)) evidence.push('RUNTIME_STYLE_PROBED');@@ -395,6 +445,7 @@ export const planFile = (flags: [...flags].sort(),...(forward ? { forward } : {}),...(param ? { forwardedParam: param } : {}),+ ...(Object.keys(inlineMasks).length ? { inlineMasks } : {}),...(Object.keys(shared).length? {inlineStyles: Object.fromEntries(@@ -410,6 +461,10 @@ export const planFile = (key: `${file}|${left.id}`,...(knobs ? { knobs } : {}),...(omitted.length ? { neutralOmitted: omitted } : {}),+ ...(realElements ? { realElements } : {}),+ ...(realElements && shapeOf(left, 'base', config.shapes)?.leaf+ ? { realLeaf: true as const }+ : {}),...(samples.length ? { samples } : {}),...(Object.keys(standIns).length ? { standIns } : {}),variables: modeled,diff --git a/packages/style-equivalence/src/plan/shapes.test.ts b/packages/style-equivalence/src/plan/shapes.test.tsnew file mode 100644index 00000000000..e8c1c30e581--- /dev/null+++ b/packages/style-equivalence/src/plan/shapes.test.ts@@ -0,0 +1,367 @@+import { describe, expect, it } from 'vitest';++import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';+import { stylexAdapter } from '../extract/adapters/stylex';+import { extractFile } from '../extract/index';+import { generateModule } from '../generate/module';+import { planFile } from './planFile';+import { type ComponentShape, type ShapeBook, shapeKey } from './shapes';++const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };++const buttonBase = (children = '<Button>a</Button><Button type="primary">b</Button>') => `+import { Button, createStaticStyles } from '@lobehub/ui';++const styles = createStaticStyles(({ css }) => ({+ actions: css\`+ display: flex;++ > button {+ flex: 1;+ min-height: 44px;+ }+ \`,+}));++export const View = () => <div className={styles.actions}>${children}</div>;+`;++const buttonHead = (+ children = '<Button {...stylex.props(styles.actionButton)}>a</Button><Button type="primary" {...stylex.props(styles.actionButton)}>b</Button>',+) => `+import { Button } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ actions: { display: 'flex' },+ actionButton: { flex: '1', minHeight: '44px' },+});++export const View = () => <div {...stylex.props(styles.actions)}>${children}</div>;+`;++const imageBase = `+import { createStaticStyles, Image } from '@lobehub/ui';++const styles = createStaticStyles(({ css }) => ({+ thumb: css\`+ width: 56px;++ img {+ width: 100%;+ object-fit: cover;+ }+ \`,+}));++export const Thumb = ({ url }) => (+ <div className={styles.thumb}>+ <Image alt="" preview={false} src={url} />+ </div>+);+`;++const imageHead = `+import { Image } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ thumb: { width: '56px' },+ thumbImage: { width: '100%', objectFit: 'cover' },+});++export const Thumb = ({ url }) => (+ <div {...stylex.props(styles.thumb)}>+ <Image+ alt=""+ classNames={{ image: stylex.props(styles.thumbImage).className }}+ preview={false}+ src={url}+ />+ </div>+);+`;++const BUTTON = { imported: 'Button', source: '@lobehub/ui' };+const IMAGE = { imported: 'Image', source: '@lobehub/ui' };++const button: ComponentShape = {+ className: { path: [], tag: 'button' },+ root: 'button',+ slots: {},+ tags: ['button', 'span'],+};++const image: ComponentShape = {+ className: { path: [], tag: 'div' },+ root: 'div',+ slots: { image: { path: [0, 0], tag: 'img' } },+ tags: ['div', 'img'],+};++const both = (shape: ComponentShape, head: ComponentShape = shape) => ({ base: shape, head });++const buttonBook = (base = button, head = base): ShapeBook => ({+ [shapeKey(BUTTON, {})]: both(base, head),+ [shapeKey(BUTTON, { type: 'primary' })]: both(base, head),+});++const plan = (before: string, after: string, shapes?: ShapeBook) => {+ const pair = {+ base: extractFile(before, 'a.tsx', options),+ head: extractFile(after, 'a.tsx', options),+ };+ return {+ pair,+ result: planFile('a.tsx', pair.base, pair.head, { layoutComponents: ['Flexbox'], shapes }),+ };+};++describe('a component child paired through its learned shape', () => {+ it('records the import of a component tag and its non-style props', () => {+ const { pair } = plan(buttonBase('<Button icon={Pencil}>a</Button>'), buttonHead());+ expect(pair.base.plain?.[0]).toMatchObject({+ component: BUTTON,+ propTexts: ['icon={Pencil}'],+ });+ expect(pair.head.elements[1]).toMatchObject({ component: BUTTON });+ expect(pair.head.elements[1].propTexts).toBeUndefined();+ });++ it('leaves the children unpaired without a learned shape', () => {+ expect(plan(buttonBase(), buttonHead()).result.unpaired).toEqual([+ { elementId: 'View#1', side: 'head' },+ { elementId: 'View#2', side: 'head' },+ ]);+ });++ it('pairs a child step on the tag the component root renders and renders it for real', () => {+ const { result } = plan(buttonBase(), buttonHead(), buttonBook());+ expect(result.unpaired).toEqual([]);+ const child = result.cases.find((entry) => entry.key === 'a.tsx|View#0/0');+ expect(child?.elementIds).toEqual({ base: 'View#0/0', head: 'View#1' });+ expect(child?.flags).toEqual([]);+ expect(child?.evidence).toEqual([+ 'DESCENDANT_REPLACED',+ 'COMPONENT_SHAPE_LEARNED',+ 'REAL_COMPONENT_RENDERED',+ ]);+ expect(child?.realElements).toEqual({ base: ['View#0/0'], head: ['View#1'] });+ expect(child?.standIns).toBeUndefined();+ });++ it('clears the parent once every child the rule reaches is rendered', () => {+ const parent = plan(buttonBase(), buttonHead(), buttonBook()).result.cases[0];+ expect(parent.key).toBe('a.tsx|View#0');+ expect(parent.flags).toEqual([]);+ expect(parent.evidence).toEqual(['DESCENDANT_RENDERED']);+ });++ it('renders the real component with an import on both sides', () => {+ const { pair, result } = plan(buttonBase(), buttonHead(), buttonBook());+ const config = { layoutComponents: ['Flexbox'] };+ const base = generateModule(pair.base, result, 'base', config);+ const head = generateModule(pair.head, result, 'head', config);+ expect(base).toContain('import { Button } from "@lobehub/ui";');+ expect(base).toContain(+ '<Button data-synthetic-element="View#0/1" data-synthetic-pair="View#0/1" type="primary">',+ );+ expect(head).toContain('import { Button } from "@lobehub/ui";');+ expect(head).toContain(+ '<Button data-synthetic-element="View#2" data-synthetic-pair="View#0/1" type="primary" {...(stylex.props(styles.actionButton))}>',+ );+ });++ it('imports a renamed component under its local name once', () => {+ const renamed = (source: string) =>+ source.replace(+ "import { Button } from '@lobehub/ui';",+ "import { Button as Btn } from '@lobehub/ui';",+ );+ const { pair, result } = plan(+ buttonBase()+ .replaceAll('<Button', '<Btn')+ .replaceAll('</Button>', '</Btn>')+ .replace(+ 'import { Button, createStaticStyles }',+ 'import { Button as Btn, createStaticStyles }',+ ),+ renamed(buttonHead().replaceAll('<Button', '<Btn').replaceAll('</Button>', '</Btn>')),+ buttonBook(),+ );+ expect(result.unpaired).toEqual([]);+ const head = generateModule(pair.head, result, 'head', { layoutComponents: ['Flexbox'] });+ expect(head.match(/import \{ Button as Btn \} from "@lobehub\/ui";/g)).toHaveLength(1);+ });++ it('keeps the stand-in pairing out when the root renders another tag', () => {+ const anchor = { ...button, className: { path: [], tag: 'a' }, root: 'a', tags: ['a'] };+ expect(plan(buttonBase(), buttonHead(), buttonBook(anchor)).result.unpaired).toHaveLength(2);+ });++ it('keeps a child step unpaired when the class lands below the root', () => {+ const inner = { ...button, className: { path: [0], tag: 'button' } };+ expect(+ plan(buttonBase(), buttonHead(), buttonBook(button, inner)).result.unpaired,+ ).toHaveLength(2);+ });++ it('keeps it unpaired when the two revisions render different roots', () => {+ const anchor = { ...button, className: { path: [], tag: 'a' }, root: 'a', tags: ['a'] };+ expect(+ plan(buttonBase(), buttonHead(), buttonBook(button, anchor)).result.unpaired,+ ).toHaveLength(2);+ });++ it('keeps it unpaired when the props it cannot render differ', () => {+ const { result } = plan(+ buttonBase('<Button icon={A}>a</Button>'),+ buttonHead('<Button icon={B} {...stylex.props(styles.actionButton)}>a</Button>'),+ buttonBook(),+ );+ expect(result.unpaired).toEqual([{ elementId: 'View#1', side: 'head' }]);+ });++ it('keeps it unpaired when the head spreads props it cannot read', () => {+ const { result } = plan(+ buttonBase('<Button>a</Button>'),+ buttonHead('<Button {...rest} {...stylex.props(styles.actionButton)}>a</Button>'),+ buttonBook(),+ );+ expect(result.unpaired).toEqual([{ elementId: 'View#1', side: 'head' }]);+ });++ it('pairs a descendant step on the element a classNames slot lands on', () => {+ const { pair, result } = plan(imageBase, imageHead, {+ [shapeKey(IMAGE, { alt: '', preview: false })]: both(image),+ });+ expect(result.unpaired).toEqual([]);+ const child = result.cases.find((entry) => entry.key === 'a.tsx|Thumb#0/0');+ expect(child?.flags).toEqual([]);+ expect(child?.realElements).toEqual({ base: ['Thumb#0/0'], head: ['Thumb#1'] });+ const head = generateModule(pair.head, result, 'head', { layoutComponents: ['Flexbox'] });+ expect(head).toContain('import { Image } from "@lobehub/ui";');+ expect(head).toContain('classNames={{ image: stylex.props(styles.thumbImage).className }}');+ expect(head).not.toContain('__neutral("classNames"');+ });++ it('renders a component that takes no children closed on both sides', () => {+ const { pair, result } = plan(imageBase, imageHead, {+ [shapeKey(IMAGE, { alt: '', preview: false })]: both({ ...image, leaf: true }),+ });+ const config = { layoutComponents: ['Flexbox'] };+ expect(generateModule(pair.base, result, 'base', config)).toContain(+ '<Image data-synthetic-element="Thumb#0/0" data-synthetic-pair="Thumb#0/0" alt="" preview={false} />',+ );+ expect(generateModule(pair.head, result, 'head', config)).toContain(+ '<Image data-synthetic-element="Thumb#1" data-synthetic-pair="Thumb#0/0" alt="" preview={false} classNames={{ image: stylex.props(styles.thumbImage).className }} />',+ );+ });++ it('keeps it unpaired when only one revision takes children', () => {+ const key = shapeKey(IMAGE, { alt: '', preview: false });+ expect(+ plan(imageBase, imageHead, { [key]: both(image, { ...image, leaf: true }) }).result.unpaired,+ ).toHaveLength(1);+ });++ it('keeps a slot unpaired when the slot was not learned or lands on another tag', () => {+ const key = shapeKey(IMAGE, { alt: '', preview: false });+ const missing = { ...image, slots: {} };+ const wrapper = { ...image, slots: { image: { path: [0], tag: 'div' } } };+ expect(plan(imageBase, imageHead, { [key]: both(missing) }).result.unpaired).toHaveLength(1);+ expect(plan(imageBase, imageHead, { [key]: both(wrapper) }).result.unpaired).toHaveLength(1);+ });+});++const wrapperBase = `+import { Button, createStaticStyles } from '@lobehub/ui';++const styles = createStaticStyles(({ css }) => ({+ actions: css\`+ display: flex;++ > button {+ flex: none;+ }+ \`,+}));++export const Bar = ({ reason }) => (+ <div className={styles.actions}>+ <Button disabled title={reason} type="text">a</Button>+ <Button type="fill">b</Button>+ </div>+);+`;++const wrapperHead = (body = '<Button {...props} {...stylex.props(styles.actionButton)} />') => `+import type { ButtonProps } from '@lobehub/ui';+import { Button } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ actions: { display: 'flex' },+ actionButton: { flex: 'none' },+});++const ActionButton = (props: ButtonProps) => ${body};++export const Bar = ({ reason }) => (+ <div {...stylex.props(styles.actions)}>+ <ActionButton disabled title={reason} type="text">a</ActionButton>+ <ActionButton type="fill">b</ActionButton>+ </div>+);+`;++const wrapperBook: ShapeBook = {+ [shapeKey(BUTTON, { disabled: true, type: 'text' })]: both(button),+ [shapeKey(BUTTON, { type: 'fill' })]: both(button),+};++describe('a local wrapper that forwards every prop to a library component', () => {+ it('stays unpaired without a learned shape', () => {+ expect(plan(wrapperBase, wrapperHead()).result.unpaired).toEqual([+ { elementId: 'ActionButton#0', side: 'head' },+ ]);+ });++ it('pairs each usage with the child the parent rule reached and renders the wrapper', () => {+ const { pair, result } = plan(wrapperBase, wrapperHead(), wrapperBook);+ expect(result.unpaired).toEqual([]);+ const first = result.cases.find((entry) => entry.key === 'a.tsx|Bar#0/0');+ expect(first?.elementIds).toEqual({ base: 'Bar#0/0', head: 'Bar#0/0' });+ expect(first?.flags).toEqual([]);+ expect(first?.evidence).toEqual([+ 'DESCENDANT_REPLACED',+ 'COMPONENT_SHAPE_LEARNED',+ 'REAL_COMPONENT_RENDERED',+ ]);+ expect(first?.realElements).toEqual({ base: ['Bar#0/0'], head: ['Bar#0/0'] });+ expect(result.cases[0].flags).toEqual([]);+ const head = generateModule(pair.head, result, 'head', { layoutComponents: ['Flexbox'] });+ expect(head).toContain('const ActionButton = (props: ButtonProps) =>');+ expect(head).toContain(+ '<ActionButton data-synthetic-element="Bar#0/0" data-synthetic-pair="Bar#0/0" disabled={true} type="text">',+ );+ });++ it('keeps the wrapper unpaired when it adds props of its own', () => {+ const { result } = plan(+ wrapperBase,+ wrapperHead('<Button {...props} size="small" {...stylex.props(styles.actionButton)} />'),+ wrapperBook,+ );+ expect(result.unpaired).toEqual([{ elementId: 'ActionButton#0', side: 'head' }]);+ });++ it('keeps the wrapper unpaired when the forwarded props come after its style', () => {+ const { result } = plan(+ wrapperBase,+ wrapperHead('<Button {...stylex.props(styles.actionButton)} {...props} />'),+ wrapperBook,+ );+ expect(result.unpaired).toEqual([{ elementId: 'ActionButton#0', side: 'head' }]);+ });+});diff --git a/packages/style-equivalence/src/plan/shapes.ts b/packages/style-equivalence/src/plan/shapes.tsnew file mode 100644index 00000000000..2391a96e50b--- /dev/null+++ b/packages/style-equivalence/src/plan/shapes.ts@@ -0,0 +1,109 @@+import ts from 'typescript';++import type { ComponentImport, LiteralValue, StyleElement } from '../extract';++type Side = 'base' | 'head';++export interface ShapeTarget {+ path: number[];+ tag: string;+}++export interface ComponentShape {+ className?: ShapeTarget;+ leaf?: true;+ root: string;+ slots: Record<string, ShapeTarget>;+ tags: string[];+}++export type ShapeBook = Record<string, Partial<Record<Side, ComponentShape>>>;++export interface ShapeStep {+ child: boolean;+ tag: string;+}++const sorted = (value: Record<string, LiteralValue>) =>+ Object.entries(value).sort(([a], [b]) => a.localeCompare(b));++export const shapeKey = (component: ComponentImport, props: Record<string, LiteralValue>) =>+ JSON.stringify([component.source, component.imported, sorted(props)]);++export const shapeOf = (element: StyleElement, side: Side, shapes: ShapeBook | undefined) =>+ element.component+ ? shapes?.[shapeKey(element.component, element.literalProps)]?.[side]+ : undefined;++export const slotNames = (expr: string) => {+ const parsed = ts.createSourceFile('slots.ts', `(${expr});`, ts.ScriptTarget.Latest, true);+ const [statement] = parsed.statements;+ let value = statement && ts.isExpressionStatement(statement) ? statement.expression : undefined;+ while (value && ts.isParenthesizedExpression(value)) value = value.expression;+ if (!value || !ts.isObjectLiteralExpression(value)) return undefined;+ const names: string[] = [];+ for (const property of value.properties) {+ if (!ts.isPropertyAssignment(property)) return undefined;+ const { name } = property;+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name)) return undefined;+ names.push(name.text);+ }+ return names.length ? names : undefined;+};++export const requestedSlots = (element: StyleElement) =>+ element.bindings.flatMap((binding) =>+ binding.prop === 'classNames' ? (slotNames(binding.expr) ?? []) : [],+ );++const styledTargets = (element: StyleElement, shape: ComponentShape) => {+ const targets: ShapeTarget[] = [];+ for (const binding of element.bindings) {+ if (binding.spread || binding.prop === 'className') {+ if (!shape.className) return undefined;+ targets.push(shape.className);+ continue;+ }+ if (binding.prop !== 'classNames') return undefined;+ const names = slotNames(binding.expr);+ if (!names) return undefined;+ for (const name of names) {+ const target = shape.slots[name];+ if (!target) return undefined;+ targets.push(target);+ }+ }+ return targets.length ? targets : undefined;+};++const sameTexts = (left: StyleElement, right: StyleElement) =>+ JSON.stringify(left.propTexts ?? []) === JSON.stringify(right.propTexts ?? []);++export const reachesShape = (step: ShapeStep, shape: ComponentShape) =>+ step.tag !== '*' && (step.child ? shape.root === step.tag : shape.tags.includes(step.tag));++export const shapePaired = (+ counterpart: StyleElement,+ element: StyleElement,+ steps: ShapeStep[],+ shapes: ShapeBook | undefined,+) => {+ const base = shapeOf(counterpart, 'base', shapes);+ const head = shapeOf(element, 'head', shapes);+ if (!base || !head || base.root !== head.root || element.foreignSpread) return false;+ if (!!base.leaf !== !!head.leaf) return false;+ if (JSON.stringify(counterpart.component) !== JSON.stringify(element.component)) return false;+ if (!sameTexts(counterpart, element)) return false;+ const targets = styledTargets(element, head);+ return (+ !!targets &&+ targets.every((target) =>+ steps.some(+ (step) =>+ reachesShape(step, base) &&+ target.tag === step.tag &&+ (!step.child || target.path.length === 0),+ ),+ )+ );+};diff --git a/packages/style-equivalence/src/plan/stateAttribute.test.ts b/packages/style-equivalence/src/plan/stateAttribute.test.tsindex 48a6969a745..ee7185fad22 100644--- a/packages/style-equivalence/src/plan/stateAttribute.test.ts+++ b/packages/style-equivalence/src/plan/stateAttribute.test.ts@@ -69,3 +69,96 @@ describe('a state attribute driven by the variable a StyleX condition reads', ()expect(tokens?.flags).toContain('ASYMMETRIC_CONDITION');});});++const disclosure = (attribute: string, head = attribute) => {+ const before = `import { createStaticStyles } from '@lobehub/ui';++const styles = createStaticStyles(({ css }) => ({+ header: css\`+ padding: 4px;++ &:not([data-expanded]):hover {+ background: gray;+ }+ \`,+}));++export const Row = ({ open, status, check }) => (+ <div className={styles.header} ${attribute}>+ x+ </div>+);+`;+ const after = `import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ header: { padding: '4px' },+ headerCollapsed: { backgroundColor: { default: null, ':hover': 'gray' } },+});++export const Row = ({ open, status, check }) => (+ <div ${head} {...stylex.props(styles.header, !open && styles.headerCollapsed)}>+ x+ </div>+);+`;+ const pair = {+ base: extractFile(before, 'b.tsx', options),+ head: extractFile(after, 'b.tsx', options),+ };+ const result = planFile('b.tsx', pair.base, pair.head, { layoutComponents: [] });+ return {+ entry: result.cases.find((item) => item.key === 'b.tsx|Row#0'),+ module: (side: 'base' | 'head') =>+ generateModule(pair[side], result, side, { layoutComponents: [] }),+ pair,+ };+};++describe('a state attribute whose value is evaluable from the case variables', () => {+ it('renders a conditional presence attribute with its condition as a variable on both sides', () => {+ const { entry, module } = disclosure(`data-expanded={open ? '' : undefined}`);+ expect(entry?.flags).not.toContain('ASYMMETRIC_CONDITION');+ expect(entry?.variables).toEqual([+ { kinds: { base: 'boolean', head: 'boolean' }, name: 'open' },+ ]);+ expect(module('base')).toContain(`data-expanded={open ? '' : undefined}`);+ expect(module('base')).toContain('const open = __v["open"];');+ expect(module('head')).toContain(`data-expanded={open ? '' : undefined}`);+ });++ it('renders a value chosen by a compound condition', () => {+ const { entry, module } = disclosure(`data-expanded={open || status ? 'yes' : undefined}`);+ expect(entry?.variables.map((variable) => variable.name)).toEqual(['open', 'status']);+ expect(entry?.variables[1].kinds).toEqual({ base: 'boolean', head: 'boolean' });+ expect(module('base')).toContain(`data-expanded={open || status ? 'yes' : undefined}`);+ });++ it('renders state attributes spread from a conditional object', () => {+ const attribute = `{...(open ? { 'data-expanded': '' } : {})}`;+ const { entry, module, pair } = disclosure(attribute);+ expect(entry?.variables).toEqual([+ { kinds: { base: 'boolean', head: 'boolean' }, name: 'open' },+ ]);+ expect(pair.base.elements[0].foreignSpread).toBeUndefined();+ expect(module('base')).toContain(+ `data-expanded={(open ? { 'data-expanded': '' } : {})?.["data-expanded"]}`,+ );+ });++ it('leaves an attribute it cannot evaluate unrendered without inventing a variable', () => {+ const { entry, module } = disclosure(+ `data-expanded={status === 'done' ? '' : undefined} data-check={check.id}`,+ '',+ );+ expect(entry?.variables).toEqual([{ kinds: { head: 'boolean' }, name: 'open' }]);+ expect(module('base')).not.toContain('data-expanded=');+ expect(module('base')).not.toContain('data-check=');+ });++ it('keeps a spread carrying non-state props foreign', () => {+ const { module, pair } = disclosure(`{...(open ? { 'data-expanded': '', title: 'x' } : {})}`);+ expect(pair.base.elements[0].foreignSpread).toBe(true);+ expect(module('base')).not.toContain('data-expanded=');+ });+});diff --git a/packages/style-equivalence/src/report/labels.test.ts b/packages/style-equivalence/src/report/labels.test.tsindex d3d961f2023..b3e178e7b66 100644--- a/packages/style-equivalence/src/report/labels.test.ts+++ b/packages/style-equivalence/src/report/labels.test.ts@@ -13,6 +13,11 @@ describe('flag labels', () => {expect(flagExplanation('RUNTIME_STYLE_DROPPED')).toContain('style=');});+ it('names a masked inline style whose value may be empty', () => {+ expect(flagLabel('INLINE_STYLE_MASKED')).toBe('两侧同一个 style 盖住了类样式');+ expect(flagExplanation('INLINE_STYLE_MASKED')).toContain('空值');+ });+it('names the components a partly forwarded descendant rule still reaches', () => {const flag = 'INNER_TARGET_PARTLY_FORWARDED:h1|AcceptanceGoal,AcceptanceIdentity';expect(flagLabel(flag)).toBe('只证明了传进组件的那个 h1');diff --git a/packages/style-equivalence/src/report/labels.ts b/packages/style-equivalence/src/report/labels.tsindex 1ec630abf4c..db9b9b496fe 100644--- a/packages/style-equivalence/src/report/labels.ts+++ b/packages/style-equivalence/src/report/labels.ts@@ -28,6 +28,7 @@ export const FLAG_LABELS: Record<string, string> = {CONTAINER_UNMODELED: '容器查询未建模',CROSS_COMPONENT: '跨组件选择器',DIFFERENCE_NOT_REPRODUCED: '差异没有复现',+ INLINE_STYLE_MASKED: '两侧同一个 style 盖住了类样式',INLINE_STYLE_SPREAD_ORDER: 'style 与展开属性顺序变了',INNER_TARGET: '命中组件内部',MEDIA_UNMODELED: '媒体条件未建模',@@ -103,6 +104,8 @@ export const FLAG_EXPLANATIONS: Record<string, string> = {'别的组件的选择器会命中这个元素(比如 .muted .control-label),合成环境里没有那个外层组件,这条规则的效果没有被比较。',DIFFERENCE_NOT_REPRODUCED:'一些条件下出现过差异,单独重跑这些用例时没有复现。可能是渲染时序造成的抖动,也可能只在整页组合下出现,需要人工确认。',+ INLINE_STYLE_MASKED:+ '两侧给这个元素传了同一个 style={…},它盖住了类样式里的同名属性。有这个值时两侧一样;只有这个值在运行时为空值(属性没传、函数返回 undefined、?? / && 短路)时,露出来的类样式不一样。确认一下它不会是空值。',INLINE_STYLE_SPREAD_ORDER:'两侧传的 style={…} 写法一样,但它和 {...props} 这类展开属性的先后顺序两侧不同,或者只有一侧有展开属性。展开对象里如果带 style,两侧谁覆盖谁就不同;工具不知道展开对象里有什么。',INNER_TARGET:diff --git a/packages/style-equivalence/src/report/plain.ts b/packages/style-equivalence/src/report/plain.tsindex 36ae1c8a550..cbd021f6841 100644--- a/packages/style-equivalence/src/report/plain.ts+++ b/packages/style-equivalence/src/report/plain.ts@@ -116,6 +116,10 @@ export const askSentence = (item: { category: string; flags: string[] }, contextlines.push('改之前和改之后只有一侧给这个元素传了 style={…},另一侧把它去掉了。截图里看不出运行时样式,看一下代码里是不是漏传了。',);+ if (names.has('INLINE_STYLE_MASKED'))+ lines.push(+ '两侧传了同一个 style={…},有值时两侧一样;只有它为空值时露出来的类样式不一样。看一下这个值会不会是空的。',+ );if (names.has('INLINE_STYLE_SPREAD_ORDER'))lines.push('两侧的 style 一样,只是和 {...展开属性} 的先后顺序换了,或者只有一侧有展开属性。确认展开的对象里没有 style,就没有影响。',diff --git a/packages/style-equivalence/src/review/state.test.ts b/packages/style-equivalence/src/review/state.test.tsindex b2776d26680..1452258d062 100644--- a/packages/style-equivalence/src/review/state.test.ts+++ b/packages/style-equivalence/src/review/state.test.ts@@ -1,7 +1,14 @@import { describe, expect, it } from 'vitest';import { decideVerdict, type VerdictItem } from '../verdict';-import { passRecord, resolvedReworks, reviewItems, reworkRecord } from './state';+import {+ agentPassRecord,+ asksAgentNote,+ passRecord,+ resolvedReworks,+ reviewItems,+ reworkRecord,+} from './state';import type { Reviews, ReworkRecord } from './store';const item = (overrides: Partial<VerdictItem> = {}): VerdictItem => ({@@ -181,3 +188,56 @@ describe('review state', () => {expect(resolved).toMatchObject([{ key: 'src/A.tsx|A#0', resolvedAt: 'now' }]);});});++describe('agentPassRecord', () => {+ const reviewed = (items: VerdictItem[], reviews = empty()) =>+ reviewItems(verdictOf(items, reviews).items, reviews, context())[0];++ it('signs an item the tool rendered equal once the agent confirms the uncovered part', () => {+ const record = agentPassRecord(reviewed([item()]), '两边一致', 'now');+ const reviews = empty();+ reviews.passes.set(record!.key, record!);++ expect(record).toMatchObject({ hash: 'h1', note: '两边一致', signer: 'agent' });+ expect(stateOf([item()], reviews)).toBe('passed');+ });++ it('signs an item that was waiting for the agent note', () => {+ const waiting = reviewed([item({ flags: ['STATE_UNMODELED'] })]);+ expect(waiting.state).toBe('waiting-agent');+ expect(agentPassRecord(waiting, '两边一致', 'now')).toMatchObject({ signer: 'agent' });+ });++ it('leaves rendered differences and one-sided elements to a person', () => {+ expect(+ agentPassRecord(reviewed([item({ category: 'difference' })]), '两边一致', 'now'),+ ).toBeUndefined();+ expect(+ agentPassRecord(+ reviewed([item({ category: 'unpaired', flags: ['UNPAIRED'] })]),+ '两边一致',+ 'now',+ ),+ ).toBeUndefined();+ });++ it('does not override a send-back from a person', () => {+ const reviews = empty();+ reviews.reworks.set('src/A.tsx|A#0', rework());+ expect(agentPassRecord(reviewed([item()], reviews), '两边一致', 'now')).toBeUndefined();+ });+});++describe('asksAgentNote', () => {+ it('asks the agent about every rendered-equal item still waiting for a person', () => {+ expect(asksAgentNote({ category: 'needs-signoff', state: 'todo' })).toBe(true);+ expect(asksAgentNote({ category: 'needs-signoff', state: 'waiting-agent' })).toBe(true);+ });++ it('leaves differences, one-sided elements and decided items alone', () => {+ expect(asksAgentNote({ category: 'difference', state: 'todo' })).toBe(false);+ expect(asksAgentNote({ category: 'unpaired', state: 'todo' })).toBe(false);+ expect(asksAgentNote({ category: 'needs-signoff', state: 'passed' })).toBe(false);+ expect(asksAgentNote({ category: 'needs-signoff', state: 'reworked' })).toBe(false);+ });+});diff --git a/packages/style-equivalence/src/review/state.ts b/packages/style-equivalence/src/review/state.tsindex 06d7cbd0522..33679da054d 100644--- a/packages/style-equivalence/src/review/state.ts+++ b/packages/style-equivalence/src/review/state.ts@@ -114,6 +114,26 @@ export const passRecord = (};};+export const AGENT_SIGNER = 'agent';++export const agentPassRecord = (+ item: ReviewItem,+ finding: string,+ now: string,+): SignoffRecord | undefined => {+ if (item.category !== 'needs-signoff') return undefined;+ if (item.state !== 'todo' && item.state !== 'waiting-agent') return undefined;+ return {+ hash: item.hash,+ key: item.key,+ note: finding.trim(),+ reason: REVIEW_PASS,+ reasons: allowedReasons(item).sort(),+ signedAt: now,+ signer: AGENT_SIGNER,+ };+};+export interface ReworkMeta {base: string;head: string;@@ -151,3 +171,6 @@ export const resolvedReworks = (items: VerdictEntry[], reviews: Reviews, now: st}).map((rework) => ({ ...rework, resolvedAt: now }));};++export const asksAgentNote = (item: { category: string; state: ReviewState }) =>+ item.category === 'needs-signoff' && (item.state === 'todo' || item.state === 'waiting-agent');diff --git a/packages/style-equivalence/src/run.ts b/packages/style-equivalence/src/run.tsindex 163e975ad92..071f8eab4e9 100644--- a/packages/style-equivalence/src/run.ts+++ b/packages/style-equivalence/src/run.ts@@ -18,11 +18,14 @@ import { planMutations } from './mutation/plan';import { type MutationReport, runMutations } from './mutation/run';import { synthesize, writeHost } from './pipeline/synthesize';import type { FilePlan, PlanCase } from './plan/planFile';+import type { ShapeBook } from './plan/shapes';+import { learnShapes } from './shape/learn';+import { shapeRequests } from './shape/requests';import { resolveScope } from './source/scope';import { prepareRevisions } from './source/worktrees';import type { Verdict } from './verdict';import { assembleVerdict } from './verdict/assemble';-import { type CaseCategory, categorizeCase } from './verdict/categorize';+import { type CaseCategory, categorizeCase, differsOnlyUnmasked } from './verdict/categorize';const run = promisify(execFile);@@ -97,8 +100,23 @@ export const runComparison = async (options: RunOptions): Promise<RunResult> =>repo: options.repo,restrictTo: options.restrictTo,});- const synthesis = await synthesize(scope, roots, config);const configDir = path.dirname(options.configFile);+ let synthesis = await synthesize(scope, roots, config);+ const requests = shapeRequests(synthesis, config.aliases);+ let shapes: ShapeBook = {};+ if (requests.length) {+ browser ??= await launchBrowser();+ shapes = await learnShapes({+ browser,+ config,+ configDir,+ configFile: options.configFile,+ requests,+ roots,+ runDir,+ });+ if (Object.keys(shapes).length) synthesis = await synthesize(scope, roots, config, shapes);+ }const hosts = {base: await writeHost('base', roots.base, synthesis, scope, config, configDir),head: await writeHost('head', roots.head, synthesis, scope, config, configDir),@@ -188,7 +206,13 @@ export const runComparison = async (options: RunOptions): Promise<RunResult> =>status: 'error',unstableConditions: [],} satisfies CaseResult);- return { category: categorizeCase(entry, result), key: entry.key, plan: entry, result };+ const masked = differsOnlyUnmasked(entry, result);+ return {+ category: categorizeCase(entry, result),+ key: entry.key,+ plan: entry,+ result: masked ? { ...result, gaps: [...result.gaps, 'INLINE_STYLE_MASKED'] } : result,+ };}),);const count = options.mutations ?? DEFAULT_MUTATIONS;@@ -275,6 +299,7 @@ export const runComparison = async (options: RunOptions): Promise<RunResult> =>widths: capture.widths,});await writeEvidence(runDir, 'plan.json', synthesis.plans);+ await writeEvidence(runDir, 'shapes.json', { requests, shapes });await writeEvidence(runDir, 'extractions.json', synthesis.extractions);await writeEvidence(runDir, 'mutation.json', mutation);await writeEvidence(runDir, 'calibration.json', calibration);diff --git a/packages/style-equivalence/src/server/review.test.ts b/packages/style-equivalence/src/server/review.test.tsindex 8581ca20bb3..4aedee72ff1 100644--- a/packages/style-equivalence/src/server/review.test.ts+++ b/packages/style-equivalence/src/server/review.test.ts@@ -326,16 +326,26 @@ describe('rework and annotate commands', () => {expect(text).toContain('颜色变红了');});- it('lists agent-read items and stores notes bound to the current hash', async () => {+ it('lists agent-read items and keeps a rework note for a person', async () => {const stored = await loadRun(runDir);const list = await annotateList(stored);expect(list.map((entry) => entry.key)).toEqual(['src/A.tsx|A#2']);expect(list[0]).toMatchObject({ component: 'SkillsIcon', hash: 'hash-A#2' });await applyNotes(stored, [- { finding: 'className 落在根 svg 上', key: 'src/A.tsx|A#2', suggestion: 'pass' },+ { finding: '图标颜色变了', key: 'src/A.tsx|A#2', suggestion: 'rework' },]);const item = (await queue()).items.find((entry: any) => entry.key === 'src/A.tsx|A#2');expect(item).toMatchObject({ canPass: true, state: 'todo' });+ expect(item.note.finding).toBe('图标颜色变了');+ });++ it('signs a rendered-equal item when the agent note confirms it', async () => {+ const stored = await loadRun(runDir);+ await applyNotes(stored, [+ { finding: 'className 落在根 svg 上', key: 'src/A.tsx|A#2', suggestion: 'pass' },+ ]);+ const item = (await queue()).items.find((entry: any) => entry.key === 'src/A.tsx|A#2');+ expect(item).toMatchObject({ state: 'passed' });expect(item.note.finding).toBe('className 落在根 svg 上');});});diff --git a/packages/style-equivalence/src/shape/book.ts b/packages/style-equivalence/src/shape/book.tsnew file mode 100644index 00000000000..dcc9a13082f--- /dev/null+++ b/packages/style-equivalence/src/shape/book.ts@@ -0,0 +1,20 @@+import type { ComponentShape, ShapeBook } from '../plan/shapes';++export type ShapeReading = Record<string, ComponentShape>;++export const mergeWidths = (readings: ShapeReading[]): ShapeReading => {+ const [first, ...rest] = readings;+ if (!first) return {};+ return Object.fromEntries(+ Object.entries(first).filter(([key, shape]) =>+ rest.every((reading) => JSON.stringify(reading[key]) === JSON.stringify(shape)),+ ),+ );+};++export const bookOf = (sides: Partial<Record<'base' | 'head', ShapeReading>>): ShapeBook => {+ const book: ShapeBook = {};+ for (const side of ['base', 'head'] as const)+ for (const [key, shape] of Object.entries(sides[side] ?? {})) (book[key] ??= {})[side] = shape;+ return book;+};diff --git a/packages/style-equivalence/src/shape/inPage.ts b/packages/style-equivalence/src/shape/inPage.tsnew file mode 100644index 00000000000..bcfcaa86982--- /dev/null+++ b/packages/style-equivalence/src/shape/inPage.ts@@ -0,0 +1,53 @@+import type { ComponentShape, ShapeTarget } from '../plan/shapes';++// Self-contained: the learn step serializes this function into the probe page.+export const readShapesInPage = (marks: { className: string; slotPrefix: string }) => {+ const skip = (element: Element) =>+ ['LINK', 'META', 'NOSCRIPT', 'SCRIPT', 'STYLE', 'TEMPLATE'].includes(element.tagName);+ const result: Record<string, ComponentShape> = {};+ const sections = [...document.querySelectorAll('[data-shape-probe]')].sort(+ (a, b) => Number(a.hasAttribute('data-shape-leaf')) - Number(b.hasAttribute('data-shape-leaf')),+ );+ for (const section of sections) {+ const key = section.getAttribute('data-shape-probe')!;+ const leaf = section.hasAttribute('data-shape-leaf');+ if (result[key] || section.querySelector('[data-shape-error]')) continue;+ const roots = [...section.children].filter((element) => !skip(element));+ if (roots.length !== 1) continue;+ const [root] = roots;+ const all = [root, ...root.querySelectorAll('*')].filter((element) => !skip(element));+ const pathOf = (element: Element) => {+ const path: number[] = [];+ for (let node = element; node !== root; node = node.parentElement!)+ path.unshift(+ [...node.parentElement!.children].filter((child) => !skip(child)).indexOf(node),+ );+ return path;+ };+ const locate = (name: string): ShapeTarget | undefined => {+ const found = all.filter((element) => element.classList.contains(name));+ return found.length === 1+ ? { path: pathOf(found[0]), tag: found[0].tagName.toLowerCase() }+ : undefined;+ };+ const slots: Record<string, ShapeTarget> = {};+ const names = new Set(+ all.flatMap((element) =>+ [...element.classList].filter((name) => name.startsWith(marks.slotPrefix)),+ ),+ );+ for (const name of [...names].sort()) {+ const target = locate(name);+ if (target) slots[name.slice(marks.slotPrefix.length)] = target;+ }+ const className = locate(marks.className);+ result[key] = {+ ...(className ? { className } : {}),+ ...(leaf ? { leaf: true as const } : {}),+ root: root.tagName.toLowerCase(),+ slots,+ tags: [...new Set(all.map((element) => element.tagName.toLowerCase()))].sort(),+ };+ }+ return result;+};diff --git a/packages/style-equivalence/src/shape/learn.test.ts b/packages/style-equivalence/src/shape/learn.test.tsnew file mode 100644index 00000000000..696ec9cfd48--- /dev/null+++ b/packages/style-equivalence/src/shape/learn.test.ts@@ -0,0 +1,101 @@+import { execFileSync } from 'node:child_process';+import { cp, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { runComparison } from '../run';++const fixtures = path.resolve(import.meta.dirname, '../../test/fixtures');+const rootModules = path.resolve(import.meta.dirname, '../../../../node_modules');+let repo: string;+let records: string;++const git = (...args: string[]) =>+ execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim();++const HEAD_FILES: Record<string, string> = {+ 'src/Actions.module.css':+ '.actions {\n display: flex;\n}\n\n.actionButton {\n flex: 1;\n min-height: 44px;\n}\n',+ 'src/Actions.tsx': `import { Button, Image } from 'fixture-ui';++import actions from './Actions.module.css';+import footer from './Footer.module.css';+import thumb from './Thumb.module.css';++export const Actions = () => (+ <div className={actions.actions}>+ <Button className={actions.actionButton}>Go</Button>+ </div>+);++export const Footer = () => (+ <div className={footer.footer}>+ <Button className={footer.footerButton}>Send</Button>+ </div>+);++export const Thumb = () => (+ <div className={thumb.thumb}>+ <Image alt="" classNames={{ image: thumb.thumbImage }} />+ </div>+);+`,+ 'src/Footer.module.css':+ '.footer {\n display: block;\n}\n\n.footerButton {\n min-height: 40px;\n}\n',+ 'src/Thumb.module.css':+ '.thumb {\n width: 56px;\n}\n\n.thumbImage {\n width: 100%;\n object-fit: cover;\n}\n',+};++beforeAll(async () => {+ repo = await mkdtemp(path.join(tmpdir(), 'style-eq-shape-'));+ records = await mkdtemp(path.join(tmpdir(), 'style-eq-shape-records-'));+ await cp(path.join(fixtures, 'shape-repo'), repo, { recursive: true });+ await symlink(rootModules, path.join(repo, 'node_modules'));+ await writeFile(path.join(repo, '.gitignore'), 'node_modules\n');+ git('init', '-q');+ git('config', 'user.email', 't@t');+ git('config', 'user.name', 't');+ git('add', '.');+ git('commit', '-qm', 'base');+ for (const [file, content] of Object.entries(HEAD_FILES))+ await writeFile(path.join(repo, file), content);+ git('commit', '-qam', 'head');+}, 30_000);++afterAll(async () => {+ await rm(repo, { force: true, recursive: true });+ await rm(records, { force: true, recursive: true });+});++describe('a library component the parent rule reached through its rendered DOM', () => {+ it('learns the shape, pairs the moved class and compares the real components', async () => {+ const result = await runComparison({+ base: 'HEAD~1',+ calibrate: false,+ configFile: path.join(fixtures, 'shape-project/style-equivalence.config.ts'),+ head: 'HEAD',+ mutations: 0,+ recordsDir: records,+ repo,+ });+ expect(result.plans[0].unpaired).toEqual([]);+ const byKey = Object.fromEntries(result.cases.map((entry) => [entry.key, entry]));+ const actions = byKey['src/Actions.tsx|Actions#0/0'];+ expect(actions.plan.evidence).toContain('COMPONENT_SHAPE_LEARNED');+ expect(actions.plan.standIns).toBeUndefined();+ expect(actions.category).toBe('equal');+ expect(byKey['src/Actions.tsx|Thumb#0/0'].category).toBe('equal');+ const footer = byKey['src/Actions.tsx|Footer#0/0'];+ expect(footer.category).toBe('difference');+ expect(+ footer.result.rootCauses.map((cause) => [cause.property, cause.before, cause.after]),+ ).toContainEqual(['min-block-size', '44px', '40px']);+ const stored = JSON.parse(await readFile(path.join(result.runDir, 'shapes.json'), 'utf8'));+ expect(Object.values(stored.shapes)).toContainEqual({+ base: expect.objectContaining({ root: 'button' }),+ head: expect.objectContaining({ className: { path: [], tag: 'button' }, root: 'button' }),+ });+ }, 240_000);+});diff --git a/packages/style-equivalence/src/shape/learn.ts b/packages/style-equivalence/src/shape/learn.tsnew file mode 100644index 00000000000..f5ceb07247c--- /dev/null+++ b/packages/style-equivalence/src/shape/learn.ts@@ -0,0 +1,106 @@+import { mkdir, rm, writeFile } from 'node:fs/promises';+import path from 'node:path';++import type { Browser } from '@playwright/test';++import { buildSide } from '../build/viteBuild';+import { serveDirectories } from '../capture/staticServer';+import type { ProjectConfig } from '../config';+import { HOST_HTML } from '../generate/host';+import type { ShapeBook } from '../plan/shapes';+import { bookOf, mergeWidths, type ShapeReading } from './book';+import { readShapesInPage } from './inPage';+import { generateProbeEntry, SHAPE_CLASS, SHAPE_SLOT_PREFIX } from './probe';+import type { ShapeRequest } from './requests';++export const SHAPE_HOST_DIR = '.style-equivalence-shapes';++type Side = 'base' | 'head';++export interface LearnOptions {+ browser: Browser;+ config: ProjectConfig;+ configDir: string;+ configFile: string;+ requests: ShapeRequest[];+ roots: Record<Side, string>;+ runDir: string;+}++const READ = `(() => {+ const __name = (target) => target;+ return (${readShapesInPage.toString()})(${JSON.stringify({ className: SHAPE_CLASS, slotPrefix: SHAPE_SLOT_PREFIX })});+})()`;++const buildProbes = async (side: Side, options: LearnOptions) => {+ const host = path.join(options.roots[side], SHAPE_HOST_DIR);+ await rm(host, { force: true, recursive: true });+ await mkdir(host, { recursive: true });+ await writeFile(path.join(host, 'index.html'), HOST_HTML);+ await writeFile(+ path.join(host, 'entry.tsx'),+ generateProbeEntry({+ hostWrapper: path.resolve(options.configDir, options.config.hostWrapper),+ requests: options.requests,+ }),+ );+ const outDir = path.join(options.runDir, `shapes-${side}`);+ try {+ await buildSide({+ configFile: options.configFile,+ hostDir: host,+ logFile: path.join(options.runDir, `build-shapes-${side}.log`),+ outDir,+ root: options.roots[side],+ });+ return outDir;+ } catch (error) {+ await writeFile(+ path.join(options.runDir, `build-shapes-${side}.log`),+ error instanceof Error ? error.message : String(error),+ );+ return undefined;+ }+};++const readAt = async (browser: Browser, url: string, width: number) => {+ const page = await browser.newPage({ viewport: { height: 900, width } });+ try {+ await page.goto(url);+ await page.waitForSelector('[data-synthetic-ready]', { state: 'attached', timeout: 30_000 });+ await page.evaluate(() => document.fonts.ready);+ await page.evaluate(+ () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),+ );+ return (await page.evaluate(READ)) as ShapeReading;+ } finally {+ await page.close();+ }+};++export const learnShapes = async (options: LearnOptions): Promise<ShapeBook> => {+ if (!options.requests.length) return {};+ const dists = await Promise.all(+ (['base', 'head'] as const).map((side) => buildProbes(side, options)),+ );+ const server = await serveDirectories(options.runDir);+ try {+ const sides: Partial<Record<Side, ShapeReading>> = {};+ for (const [index, side] of (['base', 'head'] as const).entries()) {+ const dist = dists[index];+ if (!dist) continue;+ const url = `${server.url}/${path.relative(options.runDir, dist)}/`;+ const readings: ShapeReading[] = [];+ try {+ for (const width of options.config.conditions.widths)+ readings.push(await readAt(options.browser, url, width));+ } catch {+ continue;+ }+ sides[side] = mergeWidths(readings);+ }+ return bookOf(sides);+ } finally {+ await server.close();+ }+};diff --git a/packages/style-equivalence/src/shape/probe.ts b/packages/style-equivalence/src/shape/probe.tsnew file mode 100644index 00000000000..129fdfb8f1f--- /dev/null+++ b/packages/style-equivalence/src/shape/probe.ts@@ -0,0 +1,78 @@+import { renderLiteral, SAMPLE_TEXT } from '../generate/literal';+import type { ShapeRequest } from './requests';++export const SHAPE_CLASS = '__style_eq_shape__';+export const SHAPE_SLOT_PREFIX = '__style_eq_shape_slot__';++const importOf = (request: ShapeRequest, name: string) => {+ const source = JSON.stringify(request.component.source);+ return request.component.imported === 'default'+ ? `import ${name} from ${source};`+ : `import { ${request.component.imported} as ${name} } from ${source};`;+};++const probeOf = (request: ShapeRequest, name: string, leaf: boolean) => {+ const attributes = [`className=${JSON.stringify(SHAPE_CLASS)}`];+ if (request.slots.length)+ attributes.push(+ `classNames={${JSON.stringify(Object.fromEntries(request.slots.map((slot) => [slot, `${SHAPE_SLOT_PREFIX}${slot}`])))}}`,+ );+ for (const [prop, value] of Object.entries(request.props))+ attributes.push(renderLiteral(prop, value));+ const open = `<${name} ${attributes.join(' ')}`;+ return leaf ? `${open} />` : `${open}>{${JSON.stringify(SAMPLE_TEXT)}}</${name}>`;+};++export const generateProbeEntry = ({+ hostWrapper,+ requests,+}: {+ hostWrapper: string;+ requests: ShapeRequest[];+}) => {+ const names = requests.map((_, index) => `__shape${index}`);+ return `import { Host } from ${JSON.stringify(hostWrapper)};+import { Component, type ReactNode } from 'react';+import { createRoot } from 'react-dom/client';+${requests.map((request, index) => importOf(request, names[index])).join('\n')}++class Boundary extends Component<{ children: ReactNode }, { failed: boolean }> {+ state = { failed: false };++ static getDerivedStateFromError() {+ return { failed: true };+ }++ render() {+ return this.state.failed ? <div data-shape-error="" /> : this.props.children;+ }+}++class Ready extends Component {+ componentDidMount() {+ document.getElementById('app')!.setAttribute('data-synthetic-ready', 'true');+ }++ render() {+ return null;+ }+}++document.body.style.margin = '0';+createRoot(document.getElementById('app')!).render(+ <Host>+ <main>+${requests+ .flatMap((request, index) =>+ [false, true].map(+ (leaf) =>+ ` <section ${leaf ? 'data-shape-leaf="" ' : ''}data-shape-probe={${JSON.stringify(request.key)}}><Boundary>${probeOf(request, names[index], leaf)}</Boundary></section>`,+ ),+ )+ .join('\n')}+ </main>+ <Ready />+ </Host>,+);+`;+};diff --git a/packages/style-equivalence/src/shape/requests.ts b/packages/style-equivalence/src/shape/requests.tsnew file mode 100644index 00000000000..dbe2ffa7cdd--- /dev/null+++ b/packages/style-equivalence/src/shape/requests.ts@@ -0,0 +1,73 @@+import type { ComponentImport, FileExtraction, LiteralValue, StyleElement } from '../extract';+import { counterparts, elementsOf } from '../plan/descendants';+import type { FilePlan } from '../plan/planFile';+import { requestedSlots, shapeKey } from '../plan/shapes';++export interface ShapeRequest {+ component: ComponentImport;+ key: string;+ props: Record<string, LiteralValue>;+ slots: string[];+}++export interface ShapeSource {+ extractions: Record<string, Record<'base' | 'head', FileExtraction>>;+ plans: FilePlan[];+}++export const isPackage = (source: string, aliases: Record<string, string>) =>+ !source.startsWith('.') &&+ !source.startsWith('/') &&+ !Object.keys(aliases).some((prefix) => source.startsWith(prefix));++export const shapeRequests = (synthesis: ShapeSource, aliases: Record<string, string>) => {+ const requests = new Map<string, ShapeRequest>();+ const add = (element: StyleElement, slots: string[]) => {+ const { component } = element;+ if (!component || !isPackage(component.source, aliases)) return;+ const key = shapeKey(component, element.literalProps);+ const entry = requests.get(key) ?? { component, key, props: element.literalProps, slots: [] };+ entry.slots = [...new Set([...entry.slots, ...slots])].sort();+ requests.set(key, entry);+ };+ for (const plan of synthesis.plans) {+ const extraction = synthesis.extractions[plan.file];+ if (!extraction) continue;+ const byId = {+ base: new Map(elementsOf(extraction.base).map((element) => [element.id, element])),+ head: new Map(elementsOf(extraction.head).map((element) => [element.id, element])),+ };+ const pairs = plan.cases.flatMap((entry): Array<[StyleElement, StyleElement]> => {+ const left = byId.base.get(entry.elementIds.base);+ const right = byId.head.get(entry.elementIds.head);+ return left && right ? [[left, right]] : [];+ });+ const lookup = counterparts(extraction.base, extraction.head, pairs);+ const unpaired = new Set(+ plan.unpaired.flatMap(({ elementId, side }) => (side === 'head' ? [elementId] : [])),+ );+ const candidates = [...byId.head.values()].flatMap((element) => {+ const wrapped = element.wraps ? byId.head.get(element.wraps) : undefined;+ if (wrapped)+ return unpaired.has(wrapped.id)+ ? [+ {+ effective: { ...element, bindings: wrapped.bindings, component: wrapped.component },+ element,+ },+ ]+ : [];+ return unpaired.has(element.id) ? [{ effective: element, element }] : [];+ });+ for (const { effective, element } of candidates) {+ const found = lookup(element);+ if (!found?.counterpart.component || !effective.component) continue;+ add(effective, requestedSlots(effective));+ for (const id of found.parent.children ?? []) {+ const child = byId.base.get(id);+ if (child && !/^[a-z]/.test(child.tag)) add(child, []);+ }+ }+ }+ return [...requests.values()];+};diff --git a/packages/style-equivalence/src/shape/shape.test.ts b/packages/style-equivalence/src/shape/shape.test.tsnew file mode 100644index 00000000000..7b01a3cf5fc--- /dev/null+++ b/packages/style-equivalence/src/shape/shape.test.ts@@ -0,0 +1,200 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import { launchBrowser } from '../capture/browser';+import { emotionStaticAdapter } from '../extract/adapters/emotionStatic';+import { stylexAdapter } from '../extract/adapters/stylex';+import { extractFile } from '../extract/index';+import { planFile } from '../plan/planFile';+import { shapeKey } from '../plan/shapes';+import { mergeWidths } from './book';+import { readShapesInPage } from './inPage';+import { generateProbeEntry, SHAPE_CLASS, SHAPE_SLOT_PREFIX } from './probe';+import { shapeRequests } from './requests';++const options = { adapters: [emotionStaticAdapter, stylexAdapter], layoutComponents: ['Flexbox'] };++const base = (source: string) => `+import { createStaticStyles } from '@lobehub/ui';+import { Button, Image } from '${source}';++const styles = createStaticStyles(({ css }) => ({+ row: css\`+ > button { flex: 1; }+ img { width: 100%; }+ \`,+}));++export const View = () => (+ <div className={styles.row}>+ <Button type="primary">a</Button>+ <Image alt="" />+ </div>+);+`;++const head = (source: string) => `+import * as stylex from '@stylexjs/stylex';+import { Button, Image } from '${source}';++const styles = stylex.create({+ row: {},+ button: { flex: '1' },+ image: { width: '100%' },+});++export const View = () => (+ <div {...stylex.props(styles.row)}>+ <Button type="primary" {...stylex.props(styles.button)}>a</Button>+ <Image alt="" classNames={{ image: stylex.props(styles.image).className }} />+ </div>+);+`;++const synthesis = (source: string) => {+ const pair = {+ base: extractFile(base(source), 'a.tsx', options),+ head: extractFile(head(source), 'a.tsx', options),+ };+ const plan = planFile('a.tsx', pair.base, pair.head, { layoutComponents: ['Flexbox'] });+ return { extractions: { 'a.tsx': pair }, plans: [plan] };+};++const BUTTON = { imported: 'Button', source: '@lobehub/ui' };+const IMAGE = { imported: 'Image', source: '@lobehub/ui' };++describe('the components whose shape a pairing needs', () => {+ it('requests each package component child with its props and the slots the head styles', () => {+ expect(shapeRequests(synthesis('@lobehub/ui'), { '@/': 'src/' })).toEqual([+ {+ component: BUTTON,+ key: shapeKey(BUTTON, { type: 'primary' }),+ props: { type: 'primary' },+ slots: [],+ },+ { component: IMAGE, key: shapeKey(IMAGE, { alt: '' }), props: { alt: '' }, slots: ['image'] },+ ]);+ });++ it('requests the library component a local wrapper forwards its usage to', () => {+ const wrapperHead = head('@lobehub/ui')+ .replace(+ 'export const View',+ 'const Primary = (props) => <Button {...props} {...stylex.props(styles.button)} />;\n\nexport const View',+ )+ .replace(+ '<Button type="primary" {...stylex.props(styles.button)}>a</Button>',+ '<Primary type="primary">a</Primary>',+ )+ .replace('classNames={{ image: stylex.props(styles.image).className }} ', '');+ const pair = {+ base: extractFile(base('@lobehub/ui'), 'a.tsx', options),+ head: extractFile(wrapperHead, 'a.tsx', options),+ };+ const plan = planFile('a.tsx', pair.base, pair.head, { layoutComponents: ['Flexbox'] });+ expect(plan.unpaired).toEqual([{ elementId: 'Primary#0', side: 'head' }]);+ expect(+ shapeRequests({ extractions: { 'a.tsx': pair }, plans: [plan] }, {}).map(+ (request) => request.key,+ ),+ ).toContain(shapeKey(BUTTON, { type: 'primary' }));+ });++ it('requests nothing for components from the project itself', () => {+ const aliases = { '@/': 'src/' };+ expect(shapeRequests(synthesis('./ui'), aliases)).toEqual([]);+ expect(shapeRequests(synthesis('@/ui'), aliases)).toEqual([]);+ });+});++describe('the probe page that renders each component once', () => {+ it('renders every request with marker classes under its key', () => {+ const entry = generateProbeEntry({+ hostWrapper: '/repo/host.tsx',+ requests: shapeRequests(synthesis('@lobehub/ui'), {}),+ });+ expect(entry).toContain('import { Host } from "/repo/host.tsx";');+ expect(entry).toContain('import { Button as __shape0 } from "@lobehub/ui";');+ expect(entry).toContain(+ `<__shape0 className="${SHAPE_CLASS}" type="primary">{"Ag 文本 Text"}</__shape0>`,+ );+ expect(entry).toContain(`classNames={{"image":"${SHAPE_SLOT_PREFIX}image"}}`);+ expect(entry).toContain(`data-shape-probe={${JSON.stringify(shapeKey(IMAGE, { alt: '' }))}}`);+ expect(entry).toContain(+ `<section data-shape-leaf="" data-shape-probe={${JSON.stringify(shapeKey(BUTTON, { type: 'primary' }))}}><Boundary><__shape0 className="${SHAPE_CLASS}" type="primary" /></Boundary></section>`,+ );+ });++ it('imports a default export under its probe name', () => {+ const entry = generateProbeEntry({+ hostWrapper: '/repo/host.tsx',+ requests: [+ { component: { imported: 'default', source: 'ui-kit' }, key: 'k', props: {}, slots: [] },+ ],+ });+ expect(entry).toContain('import __shape0 from "ui-kit";');+ });+});++describe('reading a rendered component shape', () => {+ let browser: Awaited<ReturnType<typeof launchBrowser>>;+ beforeAll(async () => {+ browser = await launchBrowser();+ });+ afterAll(() => browser?.close());++ it('records the root tag, where the class and each slot land, and the tags inside', async () => {+ const page = await browser.newPage();+ await page.setContent(`+ <section data-shape-probe="button"><style></style><button class="${SHAPE_CLASS}"><span>a</span></button></section>+ <section data-shape-probe="image"><div class="${SHAPE_CLASS}"><div><img class="${SHAPE_SLOT_PREFIX}image"></div></div></section>+ <section data-shape-probe="portal"></section>+ <section data-shape-probe="twice"><b class="${SHAPE_CLASS}"><i class="${SHAPE_CLASS}"></i></b></section>+ <section data-shape-probe="broken"><div data-shape-error=""></div></section>+ <section data-shape-probe="void"><div data-shape-error=""></div></section>+ <section data-shape-leaf="" data-shape-probe="void"><img class="${SHAPE_CLASS}"></section>+ <section data-shape-leaf="" data-shape-probe="button"><button class="${SHAPE_CLASS}"></button></section>+ `);+ const shapes = await page.evaluate(readShapesInPage, {+ className: SHAPE_CLASS,+ slotPrefix: SHAPE_SLOT_PREFIX,+ });+ expect(shapes).toEqual({+ button: {+ className: { path: [], tag: 'button' },+ root: 'button',+ slots: {},+ tags: ['button', 'span'],+ },+ image: {+ className: { path: [], tag: 'div' },+ root: 'div',+ slots: { image: { path: [0, 0], tag: 'img' } },+ tags: ['div', 'img'],+ },+ twice: { root: 'b', slots: {}, tags: ['b', 'i'] },+ void: {+ className: { path: [], tag: 'img' },+ leaf: true,+ root: 'img',+ slots: {},+ tags: ['img'],+ },+ });+ await page.close();+ });+});++describe('a shape learned at several widths', () => {+ const shape = { root: 'button', slots: {}, tags: ['button'] };+ it('keeps a shape only when every width rendered it the same', () => {+ expect(+ mergeWidths([+ { a: shape, b: shape },+ { a: shape, b: { ...shape, root: 'a' } },+ ]),+ ).toEqual({+ a: shape,+ });+ expect(mergeWidths([{ a: shape }, {}])).toEqual({});+ });+});diff --git a/packages/style-equivalence/src/source/declarations.test.ts b/packages/style-equivalence/src/source/declarations.test.tsnew file mode 100644index 00000000000..5496e9a041f--- /dev/null+++ b/packages/style-equivalence/src/source/declarations.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { declarationText } from './declarations';++const site = (code: string, symbol: string, member: string) => ({+ code,+ css: false,+ kind: 'source' as const,+ member,+ path: 'a.tsx',+ symbol,+});++describe('declarationText', () => {+ it('reads a member of a style factory', () => {+ const code = `const styles = createStaticStyles(({ css }) => ({ item: css\`width: 1px;\` }));`;+ expect(declarationText(site(code, 'styles', 'item'))).toBe('item: css`width: 1px;`');+ });++ it('reads a standalone css constant as its own slot', () => {+ const code = `import { css, cx } from '@lobehub/ui';+const hotArea = css\`width: 32px;\`;+const ghost = cx(css\`opacity: 0.5;\`);+`;+ expect(declarationText(site(code, 'hotArea', 'hotArea'))).toBe('hotArea = css`width: 32px;`');+ expect(declarationText(site(code, 'ghost', 'ghost'))).toBe('ghost = cx(css`opacity: 0.5;`)');+ });+});diff --git a/packages/style-equivalence/src/source/declarations.ts b/packages/style-equivalence/src/source/declarations.tsindex 287b4d410f4..65e46bda0a0 100644--- a/packages/style-equivalence/src/source/declarations.ts+++ b/packages/style-equivalence/src/source/declarations.ts@@ -4,6 +4,7 @@ import path from 'node:path';import postcss from 'postcss';import ts from 'typescript';+import { cssTemplatesOf } from '../extract/cssConstants';import { NAMESPACE } from '../extract/importedClasses';import { classNamesIn } from '../extract/selectors';import { aliasCandidates } from './aliases';@@ -21,21 +22,25 @@ export const parseSource = (code: string, file = 'source.tsx') =>ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);export const findStyleMember = (sf: ts.SourceFile, symbol: string, member: string) => {- let call: ts.CallExpression | undefined;+ let declaration: ts.VariableDeclaration | undefined;const visit = (node: ts.Node) => {if (- !call &&+ !declaration &&ts.isVariableDeclaration(node) &&ts.isIdentifier(node.name) &&node.name.text === symbol &&- node.initializer &&- ts.isCallExpression(node.initializer)+ node.initializer)- call = node.initializer;+ declaration = node;ts.forEachChild(node, visit);};visit(sf);- if (!call) return undefined;+ const initializer = declaration?.initializer;+ if (!initializer) return undefined;+ if (member === symbol && cssTemplatesOf(initializer, (name) => name === 'css'))+ return declaration;+ if (!ts.isCallExpression(initializer)) return undefined;+ const call = initializer;let queue: ts.Node[] = [...call.arguments];while (queue.length) {const next: ts.Node[] = [];diff --git a/packages/style-equivalence/src/verdict/categorize.test.ts b/packages/style-equivalence/src/verdict/categorize.test.tsindex c335f0be272..de7f058dfc9 100644--- a/packages/style-equivalence/src/verdict/categorize.test.ts+++ b/packages/style-equivalence/src/verdict/categorize.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { categorizeCase } from './categorize';+import { categorizeCase, differsOnlyUnmasked } from './categorize';const plan = (flags: string[] = []) => ({ flags }) as never;@@ -28,4 +28,21 @@ describe('categorizeCase', () => {).toBe('needs-signoff');expect(categorizeCase(unchanged, { gaps: [], status: 'difference' })).toBe('difference');});++ it('sends a difference that appears only with the inline style absent to sign-off', () => {+ const masked = {+ combos: [{ __inlineStyle: true }, { __inlineStyle: false }],+ flags: [],+ };+ const only = (combo: number) => ({+ comboDifferences: [{ combo }],+ gaps: [],+ status: 'difference' as const,+ });+ expect(categorizeCase(masked, only(1) as never)).toBe('needs-signoff');+ expect(differsOnlyUnmasked(masked, only(1) as never)).toBe(true);+ expect(categorizeCase(masked, only(0) as never)).toBe('difference');+ expect(differsOnlyUnmasked(masked, only(0) as never)).toBe(false);+ expect(differsOnlyUnmasked({ combos: [{}], flags: [] }, only(0) as never)).toBe(false);+ });});diff --git a/packages/style-equivalence/src/verdict/categorize.ts b/packages/style-equivalence/src/verdict/categorize.tsindex 6feeeb7289f..c83f98997eb 100644--- a/packages/style-equivalence/src/verdict/categorize.ts+++ b/packages/style-equivalence/src/verdict/categorize.ts@@ -1,14 +1,22 @@import type { CaseResult } from '../analyze/diff';+import { INLINE_MASK } from '../plan/inlineStyle';import type { PlanCase } from '../plan/planFile';export type CaseCategory = 'blocking' | 'difference' | 'equal' | 'needs-signoff';-export const categorizeCase = (- plan: Pick<PlanCase, 'evidence' | 'flags'>,- result: Pick<CaseResult, 'gaps' | 'status'>,-): CaseCategory => {+type CategorizedPlan = Pick<PlanCase, 'evidence' | 'flags'> & Partial<Pick<PlanCase, 'combos'>>;+type CategorizedResult = Pick<CaseResult, 'gaps' | 'status'> &+ Partial<Pick<CaseResult, 'comboDifferences'>>;++export const differsOnlyUnmasked = (plan: CategorizedPlan, result: CategorizedResult) =>+ result.status === 'difference' &&+ Boolean(result.comboDifferences?.length) &&+ result.comboDifferences!.every((item) => plan.combos?.[item.combo]?.[INLINE_MASK] === false);++export const categorizeCase = (plan: CategorizedPlan, result: CategorizedResult): CaseCategory => {if (result.status === 'error' || result.status === 'unstable') return 'blocking';if (plan.flags.some((flag) => flag.startsWith('STYLEX_UNSUPPORTED:'))) return 'blocking';+ if (differsOnlyUnmasked(plan, result)) return 'needs-signoff';if (result.status === 'difference') return 'difference';const unchanged = ['STYLE_CHAIN_UNCHANGED', 'FILE_RULES_UNCHANGED'].every((item) =>plan.evidence?.includes(item),diff --git a/packages/style-equivalence/test/fixtures/shape-project/host.tsx b/packages/style-equivalence/test/fixtures/shape-project/host.tsxnew file mode 100644index 00000000000..87021afd3fd--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-project/host.tsx@@ -0,0 +1,3 @@+import type { ReactNode } from 'react';++export const Host = ({ children }: { children: ReactNode }) => <div data-host="">{children}</div>;diff --git a/packages/style-equivalence/test/fixtures/shape-project/style-equivalence.config.ts b/packages/style-equivalence/test/fixtures/shape-project/style-equivalence.config.tsnew file mode 100644index 00000000000..53ee81315a3--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-project/style-equivalence.config.ts@@ -0,0 +1,26 @@+import path from 'node:path';++import react from '@vitejs/plugin-react';++import type { ProjectConfig } from '../../../src/config';+import { cssModulesAdapter } from '../../../src/extract/adapters/cssModules';++const config: ProjectConfig = {+ adapters: [cssModulesAdapter],+ aliases: {},+ conditions: { themeAttribute: 'data-theme', themes: ['light'], widths: [375, 1280] },+ hostWrapper: 'host.tsx',+ layoutComponents: [],+ vite: async () => ({+ alias: [+ {+ find: 'fixture-ui',+ replacement: path.resolve(import.meta.dirname, '../shape-ui/index.tsx'),+ },+ ],+ dedupe: ['react', 'react-dom'],+ plugins: [react()],+ }),+};++export default config;diff --git a/packages/style-equivalence/test/fixtures/shape-repo/package.json b/packages/style-equivalence/test/fixtures/shape-repo/package.jsonnew file mode 100644index 00000000000..b296ade9a55--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/package.json@@ -0,0 +1,4 @@+{+ "name": "shape-repo",+ "private": true+}diff --git a/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.module.css b/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.module.cssnew file mode 100644index 00000000000..15b7dd8f033--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.module.css@@ -0,0 +1,8 @@+.actions {+ display: flex;+}++.actions > button {+ flex: 1;+ min-height: 44px;+}diff --git a/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.tsx b/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.tsxnew file mode 100644index 00000000000..ed8d5a72112--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/src/Actions.tsx@@ -0,0 +1,23 @@+import { Button, Image } from 'fixture-ui';++import actions from './Actions.module.css';+import footer from './Footer.module.css';+import thumb from './Thumb.module.css';++export const Actions = () => (+ <div className={actions.actions}>+ <Button>Go</Button>+ </div>+);++export const Footer = () => (+ <div className={footer.footer}>+ <Button>Send</Button>+ </div>+);++export const Thumb = () => (+ <div className={thumb.thumb}>+ <Image alt="" />+ </div>+);diff --git a/packages/style-equivalence/test/fixtures/shape-repo/src/Footer.module.css b/packages/style-equivalence/test/fixtures/shape-repo/src/Footer.module.cssnew file mode 100644index 00000000000..70d3df34f6a--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/src/Footer.module.css@@ -0,0 +1,7 @@+.footer {+ display: block;+}++.footer > button {+ min-height: 44px;+}diff --git a/packages/style-equivalence/test/fixtures/shape-repo/src/Thumb.module.css b/packages/style-equivalence/test/fixtures/shape-repo/src/Thumb.module.cssnew file mode 100644index 00000000000..99bc1c213dc--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/src/Thumb.module.css@@ -0,0 +1,8 @@+.thumb {+ width: 56px;+}++.thumb img {+ width: 100%;+ object-fit: cover;+}diff --git a/packages/style-equivalence/test/fixtures/shape-repo/src/fixture-ui.d.ts b/packages/style-equivalence/test/fixtures/shape-repo/src/fixture-ui.d.tsnew file mode 100644index 00000000000..bb28c8b9375--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-repo/src/fixture-ui.d.ts@@ -0,0 +1,6 @@+declare module 'fixture-ui' {+ import type { ReactNode } from 'react';++ export const Button: (props: { children?: ReactNode; className?: string }) => ReactNode;+ export const Image: (props: { alt?: string; classNames?: { image?: string } }) => ReactNode;+}diff --git a/packages/style-equivalence/test/fixtures/shape-ui/index.tsx b/packages/style-equivalence/test/fixtures/shape-ui/index.tsxnew file mode 100644index 00000000000..859f8d2082a--- /dev/null+++ b/packages/style-equivalence/test/fixtures/shape-ui/index.tsx@@ -0,0 +1,35 @@+import type { ReactNode } from 'react';++const sheet = document.createElement('style');+sheet.textContent = `@layer ui {+ .ui-button { flex: none; min-height: 32px; padding: 4px; }+ .ui-image-img { width: 10px; height: 10px; object-fit: fill; }+}`;+document.head.append(sheet);++export const Button = ({+ children,+ className,+ ...rest+}: {+ children?: ReactNode;+ className?: string;+}) => (+ <button className={['ui-button', className].filter(Boolean).join(' ')} {...rest}>+ <span>{children}</span>+ </button>+);++export const Image = ({+ classNames,+ ...rest+}: {+ alt?: string;+ classNames?: { image?: string };+}) => (+ <div className="ui-image" {...rest}>+ <div className="ui-image-wrapper">+ <img alt="" className={['ui-image-img', classNames?.image].filter(Boolean).join(' ')} />+ </div>+ </div>+);