Skip to content

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

✨ feat(style-equivalence): show where a migrated descendant rule moved in the review page (#22658)

Innei73ae38e2c1ca
diff --git a/packages/style-equivalence/src/extract/aliases.ts b/packages/style-equivalence/src/extract/aliases.ts
index 214adab9245..8bcf10cf482 100644
--- a/packages/style-equivalence/src/extract/aliases.ts
+++ b/packages/style-equivalence/src/extract/aliases.ts
@@ -23,3 +23,16 @@ export const aliasOf = (node: ts.Identifier, symbols: Set<string>) => {
}
return undefined;
};
+
+export const constInitializer = (node: ts.Identifier) => {
+ for (let scope: ts.Node = node.parent; scope; scope = scope.parent) {
+ if (!ts.isBlock(scope) && !ts.isSourceFile(scope)) continue;
+ for (const statement of scope.statements)
+ if (ts.isVariableStatement(statement) && statement.declarationList.flags & ts.NodeFlags.Const)
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === node.text)
+ return declaration.initializer;
+ if (ts.isSourceFile(scope)) return undefined;
+ }
+ return undefined;
+};
diff --git a/packages/style-equivalence/src/extract/extract.test.ts b/packages/style-equivalence/src/extract/extract.test.ts
index ab72ebe60ac..e45cc67dc96 100644
--- a/packages/style-equivalence/src/extract/extract.test.ts
+++ b/packages/style-equivalence/src/extract/extract.test.ts
@@ -64,6 +64,40 @@ describe('extractFile', () => {
}
});
+ it('binds a spread of a local const that holds stylex.props', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({ video: { maxHeight: '360px' }, flat: { width: '100%' } });
+export const Item = ({ flat }: { flat?: boolean }) => {
+ const videoProps = stylex.props(styles.video, flat && styles.flat);
+ return <video controls {...videoProps} />;
+};
+`;
+ const { elements } = extractFile(code, 'a.tsx', options);
+ expect(elements).toHaveLength(1);
+ expect(elements[0]).toMatchObject({
+ bindings: [
+ { expr: 'stylex.props(styles.video, flat && styles.flat)', prop: '...', spread: true },
+ ],
+ slots: ['styles.flat', 'styles.video'],
+ tag: 'video',
+ variables: [{ kind: 'boolean', name: 'flat' }],
+ });
+ });
+
+ it('leaves a spread of an unrelated local const alone', () => {
+ const code = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({ a: { color: 'red' } });
+export const Item = () => {
+ const rest = { title: 'x' };
+ return <span {...rest} {...stylex.props(styles.a)} />;
+};
+`;
+ const { elements } = extractFile(code, 'a.tsx', options);
+ expect(elements[0].bindings).toEqual([
+ { expr: 'stylex.props(styles.a)', prop: '...', spread: true },
+ ]);
+ });
+
it('keeps only the style declaration closure in the prelude', () => {
const { prelude } = extractFile(base, 'a.tsx', options);
expect(prelude).toContain("import { createStaticStyles, cx, Flexbox } from '@lobehub/ui';");
@@ -108,6 +142,26 @@ export const A = () => <div className={styles.box}><span {...stylex.props(atomic
expect(result.elements[0].flags).toEqual(['CROSS_COMPONENT']);
});
+ it('takes only the accessed member of an imported style object', () => {
+ const modules: Record<string, string> = {
+ './Card': `import * as stylex from '@stylexjs/stylex';
+const mediaStyles = stylex.create({ image: { width: '100%' }, video: { display: 'block' } });
+export const media = {
+ image: { classNames: { image: stylex.props(mediaStyles.image).className } },
+ video: mediaStyles.video,
+};
+`,
+ };
+ const code = `import { media } from './Card';
+export const A = ({ flat }) => <Image {...(flat ? media.image : { variant: 'outlined' })} />;
+`;
+ const [element] = extractFile(code, 'src/A.tsx', {
+ ...options,
+ readModule: (_from, specifier) => modules[specifier],
+ }).elements;
+ expect(element.slots).toEqual(['media$mediaStyles.image']);
+ });
+
it('imports JSX tags used by a kept top-level statement', () => {
const code = `import { Spin } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
diff --git a/packages/style-equivalence/src/extract/index.ts b/packages/style-equivalence/src/extract/index.ts
index 08ed744429b..a1b52d13e53 100644
--- a/packages/style-equivalence/src/extract/index.ts
+++ b/packages/style-equivalence/src/extract/index.ts
@@ -1,6 +1,6 @@
import ts from 'typescript';
-import { aliasDeclaration, aliasOf } from './aliases';
+import { aliasDeclaration, aliasOf, constInitializer } from './aliases';
import { booleanAttribute, isStateAttribute } from './attributes';
import { collectChildren, literalOf } from './children';
import { localCondition, renderGuards } from './constraints';
@@ -32,7 +32,7 @@ import { stylexUnsupported } from './unsupported';
export type * from './types';
-const GLOBALS = new Set([
+export const GLOBALS = new Set([
'Array',
'Boolean',
'JSON',
@@ -94,6 +94,13 @@ export const extractFile = (
!!aliasOf(identifier, top.styleSymbols) ||
(CLASS_PROPS.has(prop ?? '') && derived.has(identifier.text)),
);
+ const styledConst = (expression: ts.Expression, prop: string) => {
+ if (!ts.isIdentifier(expression) || referencesStyle(expression, prop)) return expression;
+ const initializer = constInitializer(expression);
+ return initializer && !ts.isIdentifier(initializer) && referencesStyle(initializer, prop)
+ ? initializer
+ : expression;
+ };
const slotsOf = (node: ts.Node) => {
const slots = new Set<string>();
const visit = (current: ts.Node) => {
@@ -166,6 +173,22 @@ export const extractFile = (
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 expandedOf = (expression: ts.Expression) => {
const start = expression.getStart(ast);
let text = expression.getText(ast);
@@ -173,8 +196,11 @@ export const extractFile = (
.filter((node) => derived.has(node.text) && !declaredLocally(node))
.sort((a, b) => b.getStart(ast) - a.getStart(ast));
if (!found.length) return undefined;
- for (const node of found)
- text = `${text.slice(0, node.getStart(ast) - start)}(${derived.get(node.text)})${text.slice(node.end - start)}`;
+ for (const node of found) {
+ const member = memberOf(node, derived.get(node.text)!);
+ const target = member ? node.parent : node;
+ text = `${text.slice(0, target.getStart(ast) - start)}(${member ?? derived.get(node.text)})${text.slice(target.end - start)}`;
+ }
const parsed = ts.createSourceFile(
'x.tsx',
`(${text});`,
@@ -254,12 +280,13 @@ export const extractFile = (
let lastForeign = -1;
for (const [position, attribute] of opening.attributes.properties.entries()) {
if (ts.isJsxSpreadAttribute(attribute)) {
- if (!referencesStyle(attribute.expression, '...')) {
+ const spread = styledConst(attribute.expression, '...');
+ if (!referencesStyle(spread, '...')) {
lastForeign = position;
continue;
}
lastStyle = position;
- bindingOf(attribute.expression, '...', true);
+ bindingOf(spread, '...', true);
continue;
}
const name = attribute.name.getText(ast);
diff --git a/packages/style-equivalence/src/generate/counterpart.test.ts b/packages/style-equivalence/src/generate/counterpart.test.ts
new file mode 100644
index 00000000000..8ffa0005466
--- /dev/null
+++ b/packages/style-equivalence/src/generate/counterpart.test.ts
@@ -0,0 +1,121 @@
+import { mkdir, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import { renderToStaticMarkup } from 'react-dom/server';
+import { afterAll, describe, expect, it } from 'vitest';
+
+import type { FileExtraction } from '../extract';
+import type { FilePlan } from '../plan/planFile';
+import type { CaseModules } from './hostRuntime';
+import { generateModule } from './module';
+
+const tmp = path.join(import.meta.dirname, '.generated-counterpart-test');
+afterAll(() => rm(tmp, { force: true, recursive: true }));
+
+const extraction: FileExtraction = {
+ elements: [
+ {
+ bindings: [{ expr: 'open ? styles.open : styles.row', prop: 'className', spread: false }],
+ flags: [],
+ id: 'Row#0',
+ literalProps: {},
+ owner: 'Row',
+ slots: ['styles.open', 'styles.row'],
+ tag: 'div',
+ variables: [{ kind: 'boolean', name: 'open' }],
+ },
+ ],
+ file: 'a.tsx',
+ gaps: [],
+ outsideReferences: [],
+ prelude: `const styles = { open: 'open', row: 'row' };
+const Text = ({ as: Tag = 'div', children, ...rest }) => <Tag data-text="" {...rest}>{children}</Tag>;`,
+ rules: [],
+ styleSymbols: ['styles'],
+};
+
+const plan: FilePlan = {
+ cases: [],
+ file: 'a.tsx',
+ gaps: [],
+ unpaired: [
+ {
+ counterpart: {
+ ancestors: ['Row#0'],
+ inlineStyle: "flat ? { borderRadius: 0 } : { maxWidth: '100%' }",
+ literalProps: { 'data-kind': 'shot', 'title': 'x' },
+ props: "{ \"variant\": (flat ? 'borderless' : 'outlined') }",
+ tag: 'Image',
+ variables: [{ kind: 'boolean', name: 'flat' }],
+ },
+ elementId: 'Row#3',
+ side: 'head',
+ },
+ {
+ counterpart: {
+ ancestors: ['Row#0'],
+ literalProps: {},
+ props: '{ "alt": (item.label), "src": (url(item)), "width": (size ?? 24) }',
+ tag: 'img',
+ variables: [
+ { kind: 'unknown', name: 'item' },
+ { kind: 'unknown', name: 'size' },
+ { kind: 'call', name: 'url' },
+ { kind: 'unknown', name: 'styles' },
+ ],
+ },
+ elementId: 'Row#4',
+ side: 'head',
+ },
+ {
+ counterpart: {
+ ancestors: [],
+ literalProps: { as: 'span' },
+ props: '{ "title": (label) }',
+ real: true,
+ tag: 'Text',
+ variables: [{ kind: 'unknown', name: 'label' }],
+ },
+ elementId: 'Row#5',
+ side: 'head',
+ },
+ ],
+};
+
+const load = async () => {
+ await mkdir(tmp, { recursive: true });
+ const file = path.join(tmp, `module-${Date.now()}.tsx`);
+ await writeFile(
+ file,
+ generateModule(extraction, plan, 'base', {
+ layoutComponents: [],
+ realComponents: { Text: { source: '@lobehub/ui' } },
+ }),
+ );
+ return (await import(file)) as Required<Pick<CaseModules[string], 'unpaired'>>;
+};
+
+const render = (node: unknown) => renderToStaticMarkup(node as never);
+
+describe('generateModule for the other side of an unpaired element', () => {
+ it('renders the unstyled counterpart inside the paired ancestors with every condition off', async () => {
+ const { unpaired } = await load();
+ expect(render(unpaired['a.tsx|unpaired:head:Row#3']())).toBe(
+ '<div data-synthetic-element="Row#0" class="row"><div data-synthetic-element="Row#3" data-kind="shot" style="max-width:100%">Ag 文本 Text</div></div>',
+ );
+ });
+
+ it('passes the dynamic props of an intrinsic counterpart without redeclaring module names', async () => {
+ const { unpaired } = await load();
+ expect(render(unpaired['a.tsx|unpaired:head:Row#4']())).toBe(
+ '<div data-synthetic-element="Row#0" class="row"><img data-synthetic-element="Row#4" width="24"/></div>',
+ );
+ });
+
+ it('renders a real component counterpart with its props', async () => {
+ const { unpaired } = await load();
+ expect(render(unpaired['a.tsx|unpaired:head:Row#5']())).toBe(
+ '<span data-text="" data-synthetic-element="Row#5">Ag 文本 Text</span>',
+ );
+ });
+});
diff --git a/packages/style-equivalence/src/generate/module.ts b/packages/style-equivalence/src/generate/module.ts
index e1f1dfb75c2..4955c7c3af6 100644
--- a/packages/style-equivalence/src/generate/module.ts
+++ b/packages/style-equivalence/src/generate/module.ts
@@ -1,3 +1,5 @@
+import ts from 'typescript';
+
import type { FileExtraction, RealComponent, StyleBinding, StyleElement } from '../extract';
import type { ForwardElement } from '../extract/forward';
import { elementsOf } from '../plan/descendants';
@@ -121,7 +123,10 @@ const unpairedEntry = (
layout: Set<string>,
config: GenerateConfig,
) => {
- const expressions = chain.flatMap((item) => item.bindings.map((binding) => binding.expr));
+ const expressions = chain.flatMap((item) => [
+ ...item.bindings.map((binding) => binding.expr),
+ ...(item.inlineStyle ? [item.inlineStyle] : []),
+ ]);
const declared = new Set<string>();
const lines: string[] = [];
for (const [alias, symbol] of chain.flatMap((item) => Object.entries(item.aliases ?? {}))) {
@@ -142,6 +147,77 @@ const unpairedEntry = (
return `${JSON.stringify(key)}: () => { ${lines.join(' ')} return (${renderChain(chain, { exprOf: (binding) => binding.expr, layout, probed: new Set(), real: config.realComponents })}); }`;
};
+const preludeNames = (prelude: string) => {
+ const sf = ts.createSourceFile(
+ 'prelude.tsx',
+ prelude,
+ ts.ScriptTarget.Latest,
+ false,
+ ts.ScriptKind.TSX,
+ );
+ const names = new Set<string>();
+ for (const statement of sf.statements) {
+ if (ts.isImportDeclaration(statement)) {
+ const clause = statement.importClause;
+ if (clause?.name) names.add(clause.name.text);
+ const bindings = clause?.namedBindings;
+ if (bindings && ts.isNamespaceImport(bindings)) names.add(bindings.name.text);
+ if (bindings && ts.isNamedImports(bindings))
+ bindings.elements.forEach((element) => names.add(element.name.text));
+ } else if (ts.isVariableStatement(statement)) {
+ for (const declaration of statement.declarationList.declarations)
+ if (ts.isIdentifier(declaration.name)) names.add(declaration.name.text);
+ } else if (
+ (ts.isFunctionDeclaration(statement) ||
+ ts.isClassDeclaration(statement) ||
+ ts.isEnumDeclaration(statement)) &&
+ statement.name
+ )
+ names.add(statement.name.text);
+ }
+ return names;
+};
+
+const counterpartEntries = (
+ plan: FilePlan,
+ side: Side,
+ byId: Map<string, StyleElement>,
+ prelude: Set<string>,
+ config: GenerateConfig,
+) => {
+ const imports = new Set<string>();
+ const entries = plan.unpaired.flatMap(({ counterpart, elementId, side: own }) => {
+ if (own === side || !counterpart) return [];
+ const component = counterpart.real ? config.realComponents?.[counterpart.tag] : undefined;
+ const layout = new Set(
+ config.layoutComponents.filter((tag) => tag !== counterpart.tag || prelude.has(tag)),
+ );
+ const leaf: StyleElement = {
+ bindings: [],
+ flags: [],
+ id: elementId,
+ ...(counterpart.inlineStyle ? { inlineStyle: counterpart.inlineStyle } : {}),
+ literalProps: counterpart.literalProps,
+ owner: '',
+ ...(component ? { real: true } : {}),
+ slots: [],
+ tag: counterpart.tag,
+ variables: counterpart.variables.filter((variable) => !prelude.has(variable.name)),
+ };
+ const substituted =
+ !rendersReal(leaf, true, config.realComponents) && placementTag(leaf, layout) !== leaf.tag;
+ if (counterpart.props && !substituted)
+ leaf.bindings.push({ expr: counterpart.props, prop: '...', spread: true });
+ if (component && !prelude.has(counterpart.tag))
+ imports.add(`import { ${counterpart.tag} } from ${JSON.stringify(component.source)};`);
+ const ancestors = counterpart.ancestors.flatMap((id) => byId.get(id) ?? []);
+ return [
+ unpairedEntry(unpairedKey(plan.file, own, elementId), [...ancestors, leaf], layout, config),
+ ];
+ });
+ return { entries, imports: [...imports] };
+};
+
export const generateModule = (
extraction: FileExtraction,
plan: FilePlan,
@@ -239,8 +315,17 @@ export const generateModule = (
config,
),
);
+ const counterparts = counterpartEntries(
+ plan,
+ side,
+ byId,
+ preludeNames(extraction.prelude),
+ config,
+ );
+ unpaired.push(...counterparts.entries);
return [
extraction.prelude,
+ ...counterparts.imports,
...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/pipeline/counterparts.test.ts b/packages/style-equivalence/src/pipeline/counterparts.test.ts
new file mode 100644
index 00000000000..ea58b16848d
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/counterparts.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FileExtraction, StyleElement } from '../extract';
+import type { FilePlan } from '../plan/planFile';
+import { attachCounterparts } from './counterparts';
+
+const base = `export const Row = ({ flat }) => (
+ <div className={styles.row}>
+ <Image preview style={flat ? { borderRadius: 0 } : { maxWidth: '100%' }} />
+ </div>
+);
+`;
+
+const head = `export const Row = ({ flat }) => (
+ <div {...stylex.props(styles.row)}>
+ <Image preview {...stylex.props(flat && styles.image)} />
+ </div>
+);
+`;
+
+const element = (id: string, tag: string, expr: string, parent?: string): StyleElement => ({
+ bindings: [{ expr, prop: '...', spread: true }],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: 'Row',
+ ...(parent ? { parent } : {}),
+ slots: [],
+ tag,
+ variables: [],
+});
+
+const extraction = (elements: StyleElement[]) => ({ elements }) as unknown as FileExtraction;
+
+const plan = (): FilePlan => ({
+ cases: [
+ {
+ combos: [],
+ elementIds: { base: 'Row#0', head: 'Row#0' },
+ file: 'a.tsx',
+ flags: [],
+ key: 'a.tsx|Row#0',
+ variables: [],
+ },
+ ],
+ file: 'a.tsx',
+ gaps: [],
+ unpaired: [{ elementId: 'Row#1', side: 'head' }],
+});
+
+describe('attachCounterparts', () => {
+ it('records the other-side element under the paired ancestors of an unpaired element', () => {
+ const target = plan();
+ attachCounterparts(target, {
+ code: { base, head },
+ extractions: {
+ base: extraction([element('Row#0', 'div', 'styles.row')]),
+ head: extraction([
+ element('Row#0', 'div', 'stylex.props(styles.row)'),
+ element('Row#1', 'Image', 'stylex.props(flat && styles.image)', 'Row#0'),
+ ]),
+ },
+ });
+
+ expect(target.unpaired[0].counterpart).toEqual({
+ ancestors: ['Row#0'],
+ inlineStyle: "flat ? { borderRadius: 0 } : { maxWidth: '100%' }",
+ literalProps: { preview: true },
+ tag: 'Image',
+ variables: [{ kind: 'boolean', name: 'flat' }],
+ });
+ });
+
+ it('leaves an unpaired element alone when the other side has no such file', () => {
+ const target = plan();
+ attachCounterparts(target, {
+ code: { head },
+ extractions: {
+ base: extraction([]),
+ head: extraction([element('Row#1', 'Image', 'stylex.props(flat && styles.image)')]),
+ },
+ });
+
+ expect(target.unpaired[0].counterpart).toBeUndefined();
+ });
+});
diff --git a/packages/style-equivalence/src/pipeline/counterparts.ts b/packages/style-equivalence/src/pipeline/counterparts.ts
new file mode 100644
index 00000000000..eb8e1553dd9
--- /dev/null
+++ b/packages/style-equivalence/src/pipeline/counterparts.ts
@@ -0,0 +1,42 @@
+import type { FileExtraction, RealComponent } from '../extract';
+import { elementsOf } from '../plan/descendants';
+import { chainOf, type FilePlan, type Side } from '../plan/planFile';
+import { counterpartLeafOf } from '../source/counterpart';
+
+export interface CounterpartSources {
+ code: Partial<Record<Side, string>>;
+ extractions: Record<Side, FileExtraction>;
+ real?: Record<string, RealComponent>;
+}
+
+export const attachCounterparts = (plan: FilePlan, sources: CounterpartSources) => {
+ for (const entry of plan.unpaired) {
+ const other: Side = entry.side === 'base' ? 'head' : 'base';
+ const from = sources.code[entry.side];
+ const to = sources.code[other];
+ if (!from || !to) continue;
+ const byId = new Map(
+ elementsOf(sources.extractions[entry.side]).map((element) => [element.id, element]),
+ );
+ const element = byId.get(entry.elementId);
+ if (!element) continue;
+ const leaf = counterpartLeafOf({
+ expr: element.bindings[0]?.expr ?? '',
+ from,
+ owner: element.owner,
+ real: sources.real,
+ tag: element.tag,
+ to,
+ });
+ if (!leaf) continue;
+ const ancestors = chainOf(element, byId)
+ .slice(0, -1)
+ .flatMap(
+ (item) =>
+ plan.cases.find((planCase) => planCase.elementIds[entry.side] === item.id)?.elementIds[
+ other
+ ] ?? [],
+ );
+ entry.counterpart = { ancestors, ...leaf };
+ }
+};
diff --git a/packages/style-equivalence/src/pipeline/synthesize.ts b/packages/style-equivalence/src/pipeline/synthesize.ts
index 0f0644c2609..528f4571213 100644
--- a/packages/style-equivalence/src/pipeline/synthesize.ts
+++ b/packages/style-equivalence/src/pipeline/synthesize.ts
@@ -12,6 +12,7 @@ import { packageFile } from '../source/aliases';
import { resolveSpecifier } from '../source/declarations';
import type { ScopeFile } from '../source/scope';
import { fileFlags } from '../verdict/fileItems';
+import { attachCounterparts } from './counterparts';
import { fileReader, flagUncheckedCallers, gitGrepWord } from './forwardCallers';
import { markUnchangedChains } from './unchanged';
@@ -59,11 +60,12 @@ export const synthesize = async (
const planned: Array<{ file: string; pair: Record<Side, FileExtraction>; plan: FilePlan }> = [];
for (const entry of scope) {
const file = entry.head ?? entry.base!;
+ const code: Partial<Record<Side, string>> = {};
const read = async (side: Side) => {
const source = entry[side];
if (!source) return empty(file);
- const code = await readFile(path.join(roots[side], source), 'utf8');
- return extractFile(code, source, {
+ code[side] = await readFile(path.join(roots[side], source), 'utf8');
+ return extractFile(code[side], source, {
adapters: config.adapters,
layoutComponents: config.layoutComponents,
readBaseModule: side === 'head' ? moduleReader(roots.base, config.aliases) : undefined,
@@ -74,6 +76,7 @@ export const synthesize = async (
};
const pair = { base: await read('base'), head: await read('head') };
const plan = planFile(file, pair.base, pair.head, config);
+ attachCounterparts(plan, { code, extractions: pair, real: config.realComponents });
markUnchangedChains(plan, pair, {
aliases: config.aliases,
roots,
@@ -115,7 +118,7 @@ export const writeHost = async (
const written: string[] = [];
for (const plan of synthesis.plans) {
const source = scope.find((entry) => (entry.head ?? entry.base) === plan.file)?.[side];
- if (!source || !plan.cases.length) continue;
+ if (!source || (!plan.cases.length && !plan.unpaired.length)) continue;
const target = path.join(root, syntheticPath(source));
await writeFile(
target,
diff --git a/packages/style-equivalence/src/plan/planFile.ts b/packages/style-equivalence/src/plan/planFile.ts
index 9da21ec0dd5..d745e23bfd5 100644
--- a/packages/style-equivalence/src/plan/planFile.ts
+++ b/packages/style-equivalence/src/plan/planFile.ts
@@ -1,4 +1,11 @@
-import type { FileExtraction, RealComponent, StyleElement, VariableKind } from '../extract';
+import type {
+ FileExtraction,
+ LiteralValue,
+ RealComponent,
+ StyleElement,
+ VariableKind,
+ VariableUse,
+} from '../extract';
import { mergeKinds, valueIdentifiers } from '../extract/identifiers';
import { type Combo, combosFor, DOMAIN_COMBO_LIMIT } from './combos';
import { childCovered, elementsOf, parentCovered, replacedDescendants } from './descendants';
@@ -70,7 +77,17 @@ export interface FilePlan {
file: string;
gaps: string[];
standIns?: Record<string, string[]>;
- unpaired: Array<{ elementId: string; side: Side }>;
+ unpaired: Array<{ counterpart?: UnpairedCounterpart; elementId: string; side: Side }>;
+}
+
+export interface UnpairedCounterpart {
+ ancestors: string[];
+ inlineStyle?: string;
+ literalProps: Record<string, LiteralValue>;
+ props?: string;
+ real?: true;
+ tag: string;
+ variables: VariableUse[];
}
export interface PlanConfig {
diff --git a/packages/style-equivalence/src/report/api.ts b/packages/style-equivalence/src/report/api.ts
index 653f6e9bf74..33f63f71ecc 100644
--- a/packages/style-equivalence/src/report/api.ts
+++ b/packages/style-equivalence/src/report/api.ts
@@ -194,11 +194,17 @@ export interface ReviewView {
before: string[];
differs: boolean;
label: string;
+ movedTo?: string[];
oneSided: boolean;
}>;
slot: string;
standIn?: string;
}>;
+ counterpart?: 'base' | 'head';
+ moved: Record<
+ string,
+ Array<{ selectors: string[]; slot: string; tags: string[]; text: string }>
+ >;
source: Partial<Record<'base' | 'head', Record<string, string>>>;
usage: Partial<Record<'base' | 'head', string[]>>;
};
diff --git a/packages/style-equivalence/src/report/review.test.ts b/packages/style-equivalence/src/report/review.test.ts
index a59ce02af86..57b4f44f08a 100644
--- a/packages/style-equivalence/src/report/review.test.ts
+++ b/packages/style-equivalence/src/report/review.test.ts
@@ -14,6 +14,7 @@ import {
nextSelection,
reviewGrid,
shotNotes,
+ showsAgentNote,
standInNote,
} from './review';
@@ -200,6 +201,12 @@ describe('cellVerdict', () => {
tone: 'neutral',
});
});
+
+ it('points at the unstyled same-position element when the other side has one', () => {
+ expect(cellVerdict('a.tsx|unpaired:head:A#2', { differs: false, summary: [] }, 'base')).toEqual(
+ { text: '改之前同一位置的元素没有样式类,左右对照看', tone: 'neutral' },
+ );
+ });
});
describe('standInNote', () => {
@@ -375,3 +382,20 @@ describe('rework reason', () => {
expect(defaultReworkNote(view())).toBe('');
});
});
+
+describe('showsAgentNote', () => {
+ it('shows a written agent note even when the item did not wait for one', () => {
+ expect(showsAgentNote({ needsAgent: false, note: { finding: 'x', suggestion: 'pass' } })).toBe(
+ true,
+ );
+ });
+
+ it('asks for an agent note only on an item that waits for one', () => {
+ expect(showsAgentNote({ needsAgent: true })).toBe(true);
+ expect(showsAgentNote({ needsAgent: false })).toBe(false);
+ });
+
+ it('shows only written notes on the case page', () => {
+ expect(showsAgentNote({ needsAgent: true }, 'written')).toBe(false);
+ });
+});
diff --git a/packages/style-equivalence/src/report/review.ts b/packages/style-equivalence/src/report/review.ts
index 6914baa6d5e..7d78967c326 100644
--- a/packages/style-equivalence/src/report/review.ts
+++ b/packages/style-equivalence/src/report/review.ts
@@ -103,8 +103,17 @@ const TOOL_REASONS: Array<[RegExp, (count: string) => string]> = [
],
];
-export const cellVerdict = (key: string, cell: { differs: boolean; summary: string[] }) => {
+export const cellVerdict = (
+ key: string,
+ cell: { differs: boolean; summary: string[] },
+ counterpart?: 'base' | 'head',
+) => {
const side = /\|unpaired:(base|head):/.exec(key)?.[1];
+ if (side && counterpart)
+ return {
+ text: `${counterpart === 'base' ? '改之前' : '改之后'}同一位置的元素没有样式类,左右对照看`,
+ tone: 'neutral' as const,
+ };
if (side === 'head') return { text: '只有改之后,没有可对比的', tone: 'neutral' as const };
if (side === 'base') return { text: '只有改之前,改之后不见了', tone: 'neutral' as const };
return cell.differs
@@ -220,3 +229,8 @@ export const defaultReworkNote = (item: DifferenceView) => {
const rest = groups.length - parts.length;
return `不一样:${parts.join(';')}${rest > 0 ? `;另有 ${rest} 种差异` : ''}`;
};
+
+export const showsAgentNote = (
+ item: { needsAgent: boolean; note?: unknown },
+ notes: 'needed' | 'written' = 'needed',
+) => Boolean(item.note) || (notes === 'needed' && item.needsAgent);
diff --git a/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx b/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx
index dec681cbaeb..5d053cc87b1 100644
--- a/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx
+++ b/packages/style-equivalence/src/report/ui/ReviewEvidence.tsx
@@ -3,7 +3,7 @@ import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import type { ReviewView } from '../api';
-import { hasScreenshots, reviewGrid } from '../review';
+import { hasScreenshots, reviewGrid, showsAgentNote } from '../review';
import { RestDifferences } from './RestDifferences';
import { Legend, ShotGrid } from './ShotGrid';
import { StyleDetails } from './StyleDetails';
@@ -40,7 +40,7 @@ export const ReviewEvidence = ({
}) => {
const grid = reviewGrid(item.combos, conditions, item.comboDifferences);
const visual = hasScreenshots(item);
- const note = notes === 'needed' ? item.needsAgent : Boolean(item.note);
+ const note = showsAgentNote(item, notes);
return (
<Flexbox gap={24}>
{item.category === 'blocking' && (
diff --git a/packages/style-equivalence/src/report/ui/ShotGrid.tsx b/packages/style-equivalence/src/report/ui/ShotGrid.tsx
index a30c19506ef..14b4e632bc0 100644
--- a/packages/style-equivalence/src/report/ui/ShotGrid.tsx
+++ b/packages/style-equivalence/src/report/ui/ShotGrid.tsx
@@ -78,7 +78,7 @@ const SIDE_LABELS = { base: '改之前', head: '改之后' } as const;
const sidesOf = (item: ReviewView) => {
const unpaired = /\|unpaired:(base|head):/.exec(item.key)?.[1] as 'base' | 'head' | undefined;
- return unpaired ? [unpaired] : (['base', 'head'] as const);
+ return unpaired && !item.styles.counterpart ? [unpaired] : (['base', 'head'] as const);
};
export const Pair = ({
@@ -96,7 +96,9 @@ export const Pair = ({
return (
<Flexbox gap={4} key={side} {...stylex.props(styles.side)}>
<Text fontSize={12} type="secondary">
- {SIDE_LABELS[side]}
+ {item.styles.counterpart === side
+ ? `${SIDE_LABELS[side]}:同一位置的元素,没有样式类`
+ : SIDE_LABELS[side]}
</Text>
{notes.map((note) => (
<Text fontSize={12} key={note} type="warning" {...stylex.props(styles.standIn)}>
@@ -118,12 +120,14 @@ export const Pair = ({
export const CellVerdict = ({
cell,
+ counterpart,
itemKey,
}: {
cell: { differs: boolean; summary: string[] };
+ counterpart?: 'base' | 'head';
itemKey: string;
}) => {
- const verdict = cellVerdict(itemKey, cell);
+ const verdict = cellVerdict(itemKey, cell, counterpart);
const type =
verdict.tone === 'ok' ? 'success' : verdict.tone === 'error' ? 'danger' : 'secondary';
return (
@@ -165,7 +169,7 @@ export const ShotGrid = ({
{...stylex.props(styles.cell, cell.differs && styles.diff)}
>
<Pair combo={cell.combo} condition={cell.condition} item={item} />
- <CellVerdict cell={cell} itemKey={item.key} />
+ <CellVerdict cell={cell} counterpart={item.styles.counterpart} itemKey={item.key} />
</div>
)),
])}
diff --git a/packages/style-equivalence/src/report/ui/StyleDetails.tsx b/packages/style-equivalence/src/report/ui/StyleDetails.tsx
index 418562e4c37..d221ebac59c 100644
--- a/packages/style-equivalence/src/report/ui/StyleDetails.tsx
+++ b/packages/style-equivalence/src/report/ui/StyleDetails.tsx
@@ -52,6 +52,16 @@ const styles = stylex.create({
},
line: { display: 'block' },
mono: { color: cssVar.colorText, fontFamily: cssVar.fontFamilyCode, fontSize: cssVar.fontSizeSM },
+ movedHead: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'dashed',
+ borderBlockStartWidth: 1,
+ color: cssVar.colorTextSecondary,
+ fontSize: cssVar.fontSizeSM,
+ paddingBlock: 8,
+ paddingInline: 12,
+ },
+ movedNote: { display: 'block', marginBlockStart: 4 },
pane: { minWidth: 0 },
paneHead: {
borderBlockEndColor: cssVar.colorBorderSecondary,
@@ -150,6 +160,17 @@ const DeclarationTable = ({ blocks }: { blocks: ReviewView['styles']['blocks'] }
</td>
<td {...stylex.props(styles.cell, styles.mono)}>
<Lines label={row.label} lines={row.after} />
+ {row.movedTo?.map((where) => (
+ <Text
+ as="span"
+ fontSize={12}
+ key={where}
+ type="secondary"
+ {...stylex.props(styles.movedNote)}
+ >
+ 写在子元素 {where}
+ </Text>
+ ))}
</td>
<td {...stylex.props(styles.cell)}>
<Text fontSize={12} type={result.type}>
@@ -165,18 +186,31 @@ const DeclarationTable = ({ blocks }: { blocks: ReviewView['styles']['blocks'] }
</div>
);
+type MovedSlots = ReviewView['styles']['moved'][string];
+
const SourcePane = ({
children,
label,
+ moved = [],
split,
}: {
children: string;
label: string;
+ moved?: MovedSlots;
split?: boolean;
}) => (
<div {...stylex.props(styles.pane, split && styles.paneSplit)}>
<div {...stylex.props(styles.paneHead)}>{label}</div>
<pre {...stylex.props(styles.code)}>{children}</pre>
+ {moved.map((group) => (
+ <div key={group.slot}>
+ <div {...stylex.props(styles.movedHead)}>
+ 改之前 {group.selectors.join('、')} 的规则,现在写在子元素 &lt;
+ {group.tags.join('> <')}&gt; 的 {group.slot} 上
+ </div>
+ <pre {...stylex.props(styles.code)}>{group.text}</pre>
+ </div>
+ ))}
</div>
);
@@ -186,13 +220,15 @@ const SourceCompare = ({ styles: data }: { styles: ReviewView['styles'] }) => {
].sort();
const usage = (side: 'base' | 'head') =>
(data.usage[side] ?? ['(这一侧没有这个元素)']).join('\n');
+ const label = (side: 'base' | 'head', text: string) =>
+ data.counterpart === side ? `${text}:同一位置的元素,没有样式类` : text;
return (
<Flexbox gap={12}>
<div {...stylex.props(styles.block)}>
<div {...stylex.props(styles.group)}>JSX 用法</div>
<div {...stylex.props(styles.panes)}>
- <SourcePane label="改之前">{usage('base')}</SourcePane>
- <SourcePane split label="改之后">
+ <SourcePane label={label('base', '改之前')}>{usage('base')}</SourcePane>
+ <SourcePane split label={label('head', '改之后')}>
{usage('head')}
</SourcePane>
</div>
@@ -202,7 +238,7 @@ const SourceCompare = ({ styles: data }: { styles: ReviewView['styles'] }) => {
<div {...stylex.props(styles.group)}>{slot}</div>
<div {...stylex.props(styles.panes)}>
<SourcePane label="改之前">{data.source.base?.[slot] ?? '(没有)'}</SourcePane>
- <SourcePane split label="改之后">
+ <SourcePane split label="改之后" moved={data.moved[slot]}>
{data.source.head?.[slot] ?? '(没有)'}
</SourcePane>
</div>
diff --git a/packages/style-equivalence/src/review/declarations.ts b/packages/style-equivalence/src/review/declarations.ts
index 0433f9a8bb5..187a639a927 100644
--- a/packages/style-equivalence/src/review/declarations.ts
+++ b/packages/style-equivalence/src/review/declarations.ts
@@ -1,7 +1,11 @@
import postcss, { type ChildNode } from 'postcss';
import ts from 'typescript';
+import type { MovedRule } from './moved';
+import { targetsDescendant } from './selectorText';
+
export interface Declaration {
+ descendant?: true;
property: string;
selector: string;
value: string;
@@ -12,6 +16,7 @@ export interface DeclarationRow {
before: string[];
differs: boolean;
label: string;
+ movedTo?: string[];
oneSided: boolean;
}
@@ -30,22 +35,37 @@ const token = (text: string) => {
const PLACEHOLDER = /__I(\d+)__/g;
+const normalizeSelector = (selector: string) =>
+ selector
+ .trim()
+ .replaceAll(/\s*,\s*/g, ', ')
+ .replaceAll(/\s+/g, ' ');
+
const scopeOf = (selector: string, key: string) =>
key.startsWith('@') ? `${selector} ${key}`.trim() : `${selector}${key}`;
const fromCss = (css: string, selector = '', restore = (value: string) => value): Declaration[] => {
const rows: Declaration[] = [];
- const walk = (nodes: ChildNode[], scope: string) => {
+ const walk = (nodes: ChildNode[], scope: string, descendant: boolean) => {
for (const node of nodes) {
if (node.type === 'decl')
- rows.push({ property: node.prop, selector: scope, value: restore(node.value.trim()) });
+ rows.push({
+ ...(descendant ? { descendant: true as const } : {}),
+ property: node.prop,
+ selector: scope,
+ value: restore(node.value.trim()),
+ });
else if (node.type === 'rule')
- walk(node.nodes, `${scope}${node.selector.replace(/^&/, '').trim()}`.trim());
+ walk(
+ node.nodes,
+ `${scope}${normalizeSelector(node.selector.replace(/^&/, ''))}`.trim(),
+ descendant || targetsDescendant(node.selector),
+ );
else if (node.type === 'atrule')
- walk(node.nodes ?? [], `${scope} @${node.name} ${node.params}`.trim());
+ walk(node.nodes ?? [], `${scope} @${node.name} ${node.params}`.trim(), descendant);
}
};
- walk(postcss.parse(css).nodes, selector);
+ walk(postcss.parse(css).nodes, selector, false);
return rows;
};
@@ -159,7 +179,7 @@ export const parseDeclarations = (text: string): Declaration[] => {
return fromObject(member.initializer, source);
};
-const family = (property: string) => {
+export const family = (property: string) => {
if (property.startsWith('background')) return 'background';
if (/^border(-.+)?-radius$/.test(property)) return 'border-radius';
if (property.startsWith('border')) return 'border';
@@ -177,6 +197,7 @@ export const declarationBlocks = (
before: Record<string, string> = {},
after: Record<string, string> = {},
differing: string[] = [],
+ moved: Record<string, MovedRule[]> = {},
): DeclarationBlock[] => {
const changed = new Set(differing.map(family));
const slots = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort();
@@ -199,6 +220,15 @@ export const declarationBlocks = (
};
add('before', before[slot]);
add('after', after[slot]);
+ for (const rule of moved[slot] ?? [])
+ for (const { property, selector, value } of parseDeclarations(rule.text)) {
+ const name = family(property);
+ const row = rows.get(`${rule.selector}${selector} ${name}`);
+ if (!row?.before.length) continue;
+ row.after.push(`${property}: ${value}`);
+ const where = `<${rule.tags.join('> <')}> · ${rule.slot}`;
+ row.movedTo = [...new Set([...(row.movedTo ?? []), where])];
+ }
for (const row of rows.values()) row.oneSided = !row.before.length || !row.after.length;
return {
key: slot,
diff --git a/packages/style-equivalence/src/review/moved.test.ts b/packages/style-equivalence/src/review/moved.test.ts
new file mode 100644
index 00000000000..de767788542
--- /dev/null
+++ b/packages/style-equivalence/src/review/moved.test.ts
@@ -0,0 +1,195 @@
+import { describe, expect, it } from 'vitest';
+
+import { declarationBlocks } from './declarations';
+import { movedRules } from './moved';
+
+const baseTable = `table: css\`
+ border-collapse: collapse;
+ width: 100%;
+
+ th,
+ td {
+ padding-block: 8px;
+ border-block-end: 1px solid \${cssVar.colorBorderSecondary};
+ }
+
+ th {
+ font-size: 11px;
+ }
+
+ td {
+ font-size: 12px;
+ }
+ \``;
+
+const headTexts = {
+ 'styles.cell': `cell: { paddingBlock: '8px', borderBlockEndWidth: '1px', borderBlockEndStyle: 'solid', borderBlockEndColor: cssVar.colorBorderSecondary }`,
+ 'styles.table': `table: { borderCollapse: 'collapse', width: '100%' }`,
+ 'styles.td': `td: { fontSize: '12px' }`,
+ 'styles.th': `th: { fontSize: '11px' }`,
+};
+
+const headElements = [
+ { id: 'scroll', slots: ['styles.tableScroll'], tag: 'div' },
+ { id: 'table', parent: 'scroll', slots: ['styles.table'], tag: 'table' },
+ { id: 'th', parent: 'table', slots: ['styles.cell', 'styles.th'], tag: 'th' },
+ { id: 'td', parent: 'table', slots: ['styles.cell', 'styles.td'], tag: 'td' },
+ { id: 'other', slots: ['styles.cell'], tag: 'td' },
+];
+
+const input = {
+ base: { declarations: { 'styles.table': baseTable } },
+ head: {
+ chain: [headElements[0], headElements[1]],
+ elements: headElements,
+ texts: headTexts,
+ },
+};
+
+describe('movedRules', () => {
+ it('finds the head descendants that now carry a base descendant rule', () => {
+ const moved = movedRules(input)['styles.table'];
+
+ expect(moved.map(({ selector, slot, targets }) => ({ selector, slot, targets }))).toEqual([
+ { selector: 'th, td', slot: 'styles.cell', targets: ['th', 'td'] },
+ { selector: 'th', slot: 'styles.th', targets: ['th'] },
+ { selector: 'td', slot: 'styles.td', targets: ['td'] },
+ ]);
+ expect(moved.find((entry) => entry.slot === 'styles.th')?.text).toBe(headTexts['styles.th']);
+ });
+
+ it('skips a child slot the base already used', () => {
+ const moved = movedRules({
+ ...input,
+ base: { ...input.base, slots: ['styles.td'] },
+ })['styles.table'];
+
+ expect(moved.some((entry) => entry.slot === 'styles.td')).toBe(false);
+ });
+
+ it('ignores elements outside the case element', () => {
+ const moved = movedRules(input)['styles.table'];
+
+ expect(moved.every((entry) => !entry.targets.includes('other'))).toBe(true);
+ });
+
+ it('matches an attribute selector against literal attributes', () => {
+ const moved = movedRules({
+ base: {
+ declarations: {
+ 'styles.tabs': `tabs: css\`
+ [role='tablist'] {
+ width: 100%;
+ }
+ \``,
+ },
+ },
+ head: {
+ chain: [{ id: 'tabs', slots: ['styles.tabs'], tag: 'div' }],
+ elements: [
+ { id: 'tabs', slots: ['styles.tabs'], tag: 'div' },
+ {
+ attributes: { role: 'tablist' },
+ id: 'list',
+ parent: 'tabs',
+ slots: ['styles.list'],
+ tag: 'div',
+ },
+ ],
+ texts: { 'styles.list': `list: { width: '100%' }` },
+ },
+ });
+
+ expect(moved['styles.tabs'].map((entry) => entry.slot)).toEqual(['styles.list']);
+ });
+
+ it('leaves class-only and self selectors alone', () => {
+ const moved = movedRules({
+ base: {
+ declarations: {
+ 'styles.row': `row: css\`
+ &:hover {
+ color: red;
+ }
+
+ &[data-active] {
+ color: green;
+ }
+
+ & + & {
+ margin-top: 4px;
+ }
+
+ .title {
+ color: blue;
+ }
+ \``,
+ },
+ },
+ head: {
+ chain: [{ id: 'row', slots: ['styles.row'], tag: 'div' }],
+ elements: [
+ { id: 'row', slots: ['styles.row'], tag: 'div' },
+ { id: 'title', parent: 'row', slots: ['styles.title'], tag: 'span' },
+ ],
+ texts: { 'styles.title': `title: { color: 'blue' }` },
+ },
+ });
+
+ expect(moved['styles.row'] ?? []).toEqual([]);
+ });
+
+ it('follows a descendant written after the nesting selector', () => {
+ const moved = movedRules({
+ base: {
+ declarations: {
+ 'styles.row': `row: css\`
+ &:hover > span {
+ color: red;
+ }
+ \``,
+ },
+ },
+ head: {
+ chain: [{ id: 'row', slots: ['styles.row'], tag: 'div' }],
+ elements: [
+ { id: 'row', slots: ['styles.row'], tag: 'div' },
+ { id: 'title', parent: 'row', slots: ['styles.title'], tag: 'span' },
+ ],
+ texts: { 'styles.title': `title: { color: { default: null, ':hover': 'red' } }` },
+ },
+ });
+
+ expect(moved['styles.row']?.map((entry) => entry.slot)).toEqual(['styles.title']);
+ });
+});
+
+describe('declarationBlocks with moved rules', () => {
+ it('fills a descendant row from the child that now carries it', () => {
+ const [block] = declarationBlocks(
+ { 'styles.table': baseTable },
+ { 'styles.table': headTexts['styles.table'] },
+ [],
+ movedRules(input),
+ );
+ const row = (label: string) => block.rows.find((entry) => entry.label === label);
+
+ expect(row('th, td padding')).toMatchObject({
+ after: ['padding-block: 8px'],
+ before: ['padding-block: 8px'],
+ movedTo: ['<th> <td> · styles.cell'],
+ oneSided: false,
+ });
+ expect(row('th font-size')).toMatchObject({
+ after: ['font-size: 11px'],
+ movedTo: ['<th> · styles.th'],
+ });
+ expect(row('td font-size')?.after).toEqual(['font-size: 12px']);
+ expect(row('th, td font-size')).toBeUndefined();
+ expect(row('th, td border')?.after).toEqual([
+ 'border-block-end-width: 1px',
+ 'border-block-end-style: solid',
+ 'border-block-end-color: colorBorderSecondary',
+ ]);
+ });
+});
diff --git a/packages/style-equivalence/src/review/moved.ts b/packages/style-equivalence/src/review/moved.ts
new file mode 100644
index 00000000000..02ddce2e7ea
--- /dev/null
+++ b/packages/style-equivalence/src/review/moved.ts
@@ -0,0 +1,86 @@
+import { family, parseDeclarations } from './declarations';
+import { type Compound, lastCompounds } from './selectorText';
+
+export interface MovedElement {
+ attributes?: Record<string, string>;
+ id: string;
+ parent?: string;
+ slots: string[];
+ tag: string;
+}
+
+export interface MovedRule {
+ selector: string;
+ slot: string;
+ tags: string[];
+ targets: string[];
+ text: string;
+}
+
+export interface MovedInput {
+ base: { declarations: Record<string, string>; slots?: string[] };
+ head: { chain: MovedElement[]; elements: MovedElement[]; texts: Record<string, string> };
+}
+
+const ruleSelector = (scope: string) => scope.split(' @')[0].trim();
+
+const matches = (element: MovedElement, compounds: Compound[]) =>
+ compounds.some(
+ ({ attributes, tag }) =>
+ (!tag || tag === element.tag) &&
+ attributes.every(({ name, value }) =>
+ value === undefined
+ ? element.attributes?.[name] !== undefined
+ : element.attributes?.[name] === value,
+ ),
+ );
+
+const isInside = (element: MovedElement, ancestor: string, byId: Map<string, MovedElement>) => {
+ for (let current = element.parent; current; current = byId.get(current)?.parent)
+ if (current === ancestor) return true;
+ return false;
+};
+
+export const movedRules = ({ base, head }: MovedInput): Record<string, MovedRule[]> => {
+ const byId = new Map(head.elements.map((element) => [element.id, element]));
+ const existing = new Set(base.slots);
+ const result: Record<string, MovedRule[]> = {};
+ for (const [slot, text] of Object.entries(base.declarations)) {
+ const owner =
+ head.chain.findLast((element) => element.slots.includes(slot)) ?? head.chain.at(-1);
+ if (!owner) continue;
+ const inside = head.elements.filter((element) => isInside(element, owner.id, byId));
+ const ruleFamilies = new Map<string, Set<string>>();
+ for (const row of parseDeclarations(text)) {
+ if (!row.descendant) continue;
+ const selector = ruleSelector(row.selector);
+ ruleFamilies.set(
+ selector,
+ (ruleFamilies.get(selector) ?? new Set()).add(family(row.property)),
+ );
+ }
+ const carries = (target: string, families: Set<string>) =>
+ parseDeclarations(head.texts[target] ?? '').some((row) => families.has(family(row.property)));
+ const rules: MovedRule[] = [];
+ for (const [selector, families] of ruleFamilies) {
+ const compounds = lastCompounds(selector);
+ if (!compounds) continue;
+ const targets = inside.filter((element) => matches(element, compounds));
+ const slots = [...new Set(targets.flatMap((element) => element.slots))].filter(
+ (target) => !existing.has(target) && carries(target, families),
+ );
+ for (const target of slots) {
+ const carriers = targets.filter((element) => element.slots.includes(target));
+ rules.push({
+ selector,
+ slot: target,
+ tags: [...new Set(carriers.map((element) => element.tag))],
+ targets: carriers.map((element) => element.id),
+ text: head.texts[target] ?? `UNRESOLVED:${target}`,
+ });
+ }
+ }
+ if (rules.length) result[slot] = rules;
+ }
+ return result;
+};
diff --git a/packages/style-equivalence/src/review/selectorText.ts b/packages/style-equivalence/src/review/selectorText.ts
new file mode 100644
index 00000000000..7c21b4c2065
--- /dev/null
+++ b/packages/style-equivalence/src/review/selectorText.ts
@@ -0,0 +1,54 @@
+export interface Compound {
+ attributes: Array<{ name: string; value?: string }>;
+ tag?: string;
+}
+
+const topLevel = (selector: string, isBreak: (char: string) => boolean) => {
+ const parts: string[] = [];
+ let depth = 0;
+ let current = '';
+ for (const char of selector) {
+ if (char === '[' || char === '(') depth += 1;
+ else if (char === ']' || char === ')') depth -= 1;
+ if (depth === 0 && isBreak(char)) {
+ parts.push(current);
+ current = '';
+ continue;
+ }
+ current += char;
+ }
+ parts.push(current);
+ return parts;
+};
+
+const collapseCombinators = (selector: string) =>
+ selector.replaceAll(/\s*([>+~])\s*/g, '$1').replaceAll(/\s+/g, ' ');
+
+const ATTRIBUTE = /\[\s*([\w-]+)\s*(?:=\s*(["']?)(.*?)\2\s*)?\]/g;
+
+const compoundOf = (part: string): Compound | undefined => {
+ const pieces = topLevel(collapseCombinators(part.trim()), (char) => /[ >+~]/.test(char));
+ const compound = pieces.at(-1) ?? '';
+ const bare = compound.replaceAll(/\[[^\]]*\]|\([^)]*\)/g, '');
+ if (/[.#&]/.test(bare)) return undefined;
+ const tag = /^[a-z][\w-]*/i.exec(bare)?.[0];
+ const attributes = [...compound.matchAll(ATTRIBUTE)].map(([, name, , value]) => ({
+ name,
+ value,
+ }));
+ return tag || attributes.length ? { attributes, tag } : undefined;
+};
+
+export const lastCompounds = (selector: string): Compound[] | undefined => {
+ const compounds = topLevel(selector, (char) => char === ',').map(compoundOf);
+ return compounds.every(Boolean) ? (compounds as Compound[]) : undefined;
+};
+
+export const targetsDescendant = (selector: string) =>
+ topLevel(selector, (char) => char === ',').some((raw) => {
+ const part = raw.trim();
+ const ampersands = topLevel(part, (char) => char === '&');
+ if (ampersands.length === 1) return !part.startsWith(':');
+ const rest = collapseCombinators(ampersands.at(-1)!).trimEnd();
+ return topLevel(rest, (char) => char === ' ' || char === '>').length > 1;
+ });
diff --git a/packages/style-equivalence/src/server/review.test.ts b/packages/style-equivalence/src/server/review.test.ts
index a7a23bec7b6..8581ca20bb3 100644
--- a/packages/style-equivalence/src/server/review.test.ts
+++ b/packages/style-equivalence/src/server/review.test.ts
@@ -212,7 +212,7 @@ describe('review API', () => {
base: ['<span className={styles.a}>'],
head: ['<span {...stylex.props(styles.a)}>'],
});
- expect(variable.styles).toEqual({ blocks: [], source: {}, usage: {} });
+ expect(variable.styles).toEqual({ blocks: [], moved: {}, source: {}, usage: {} });
const placed = payload.items.find((entry: any) => entry.key === 'src/A.tsx|A#2');
expect(placed.styles.blocks.map((block: any) => [block.slot, block.standIn])).toEqual([
['icon', 'SkillsIcon'],
diff --git a/packages/style-equivalence/src/server/review.ts b/packages/style-equivalence/src/server/review.ts
index 79b05b668c8..b80e84ef49c 100644
--- a/packages/style-equivalence/src/server/review.ts
+++ b/packages/style-equivalence/src/server/review.ts
@@ -1,9 +1,10 @@
import type { StyleElement } from '../extract';
import type { Combo } from '../plan/combos';
-import { isIntrinsicTag, PASS_THROUGH_VARIABLES } from '../plan/planFile';
+import { chainOf, type FilePlan, isIntrinsicTag, PASS_THROUGH_VARIABLES } from '../plan/planFile';
import { askSentence, comboLabel, differenceSummary } from '../report/plain';
import { defaultReworkNote } from '../report/review';
import { declarationBlocks } from '../review/declarations';
+import { type MovedRule, movedRules } from '../review/moved';
import {
elementSignature,
passRecord,
@@ -46,6 +47,7 @@ interface CaseEntry {
}
interface CaseEvidence {
+ counterpart?: Sides<string>;
declarations?: Partial<Record<'base' | 'head', Record<string, string>>>;
elements?: Partial<
Record<
@@ -71,10 +73,37 @@ const standIns = (evidence: CaseEvidence | undefined, layout: Set<string>) => {
return tags;
};
+interface MovedSlot {
+ selectors: string[];
+ slot: string;
+ tags: string[];
+ text: string;
+}
+
+const groupMoved = (moved: Record<string, MovedRule[]>) =>
+ Object.fromEntries(
+ Object.entries(moved).map(([baseSlot, rules]) => {
+ const bySlot = new Map<string, MovedSlot>();
+ for (const rule of rules) {
+ const group = bySlot.get(rule.slot) ?? {
+ selectors: [],
+ slot: rule.slot,
+ tags: [],
+ text: rule.text,
+ };
+ group.selectors = [...new Set([...group.selectors, rule.selector])];
+ group.tags = [...new Set([...group.tags, ...rule.tags])];
+ bySlot.set(rule.slot, group);
+ }
+ return [baseSlot, [...bySlot.values()]];
+ }),
+ );
+
const stylesOf = (
entry: CaseEntry | undefined,
evidence: CaseEvidence | undefined,
layout: Set<string>,
+ moved: Record<string, MovedRule[]> = {},
) => {
const causes = [
...(entry?.result?.rootCauses ?? []),
@@ -92,13 +121,20 @@ const stylesOf = (
evidence.declarations.base,
evidence.declarations.head,
causes.map((cause) => cause.property),
+ moved,
).map(({ key, ...block }) => ({ ...block, standIn: standIns(evidence, layout).get(key) }))
: [],
+ counterpart: (['base', 'head'] as const).find(
+ (side) => !evidence?.elements?.[side]?.length && evidence?.counterpart?.[side],
+ ),
+ moved: groupMoved(moved),
source,
usage: Object.fromEntries(
(['base', 'head'] as const).flatMap((side) => {
const chain = evidence?.elements?.[side];
- return chain?.length ? [[side, chain.map(usageOf)]] : [];
+ if (chain?.length) return [[side, chain.map(usageOf)]];
+ const counterpart = evidence?.counterpart?.[side];
+ return counterpart ? [[side, [counterpart]]] : [];
}),
),
};
@@ -109,13 +145,18 @@ type Extractions = Record<string, Partial<Record<'base' | 'head', { elements: St
export const standInsFor = (
key: string,
entry: Pick<CaseEntry, 'plan'> | undefined,
- plans: Array<{ file: string; standIns?: Record<string, string[]> }>,
+ plans: Array<Pick<FilePlan, 'file' | 'standIns'> & Partial<Pick<FilePlan, 'unpaired'>>>,
): Sides<string[]> => {
const unpaired = /^(.*)\|unpaired:(base|head):(.+)$/.exec(key);
if (!unpaired) return entry?.plan.standIns ?? {};
const [, file, side, id] = unpaired;
- const tags = plans.find((plan) => plan.file === file)?.standIns?.[`${side}:${id}`];
- return tags ? { [side]: tags } : {};
+ const plan = plans.find((item) => item.file === file);
+ const tags = plan?.standIns?.[`${side}:${id}`];
+ if (!tags) return {};
+ const mirrored = plan?.unpaired?.some(
+ (item) => item.side === side && item.elementId === id && item.counterpart,
+ );
+ return mirrored ? { base: tags, head: tags } : { [side]: tags };
};
const elementFor = (stored: StoredRun, key: string, entry: CaseEntry | undefined) => {
@@ -127,6 +168,36 @@ const elementFor = (stored: StoredRun, key: string, entry: CaseEntry | undefined
return extractions[file]?.[side]?.elements.find((element) => element.id === id);
};
+const headTextsOf = (stored: StoredRun, file: string) => {
+ const texts: Record<string, string> = {};
+ for (const [key, value] of Object.entries(stored.evidence))
+ if (key.startsWith(`${file}|`))
+ Object.assign(texts, (value as CaseEvidence | undefined)?.declarations?.head);
+ return texts;
+};
+
+const movedOf = (
+ stored: StoredRun,
+ entry: CaseEntry | undefined,
+ evidence: CaseEvidence | undefined,
+) => {
+ const base = evidence?.declarations?.base;
+ const file = entry?.plan.file;
+ const headId = entry?.plan.elementIds?.head;
+ if (!base || !file || !headId) return {};
+ const elements = (stored.extractions as Extractions)[file]?.head?.elements ?? [];
+ const byId = new Map(elements.map((element) => [element.id, element]));
+ const element = byId.get(headId);
+ if (!element) return {};
+ const baseSlots = (stored.extractions as Extractions)[file]?.base?.elements.flatMap(
+ (element) => element.slots,
+ );
+ return movedRules({
+ base: { declarations: base, slots: baseSlots },
+ head: { chain: chainOf(element, byId), elements, texts: headTextsOf(stored, file) },
+ });
+};
+
const titleOf = (key: string, element: StyleElement | undefined) => {
const id = key.slice(key.indexOf('|') + 1).replace(/^unpaired:\w+:/, '');
const slot = element?.slots[0]?.split('.').pop();
@@ -154,6 +225,7 @@ const describe = (
evidence?: CaseEvidence,
layout: Set<string> = new Set(),
standIns: Sides<string[]> = {},
+ moved: Record<string, MovedRule[]> = {},
) => {
const component = element && !isIntrinsicTag(element.tag) ? element.tag : undefined;
const binding = element?.bindings[0];
@@ -184,7 +256,7 @@ const describe = (
differingConditions: entry?.result?.differingConditions ?? [],
errors: entry?.result?.errors ?? [],
standIns,
- styles: stylesOf(entry, evidence, layout),
+ styles: stylesOf(entry, evidence, layout, moved),
summary: differenceSummary(entry?.result?.rootCauses ?? []),
title: titleOf(item.key, element),
};
@@ -221,6 +293,11 @@ export const reviewPayload = async (stored: StoredRun, layoutComponents: string[
stored.evidence[item.key] as CaseEvidence | undefined,
layout,
standInsFor(item.key, context.cases.get(item.key), stored.plans ?? []),
+ movedOf(
+ stored,
+ context.cases.get(item.key),
+ stored.evidence[item.key] as CaseEvidence | undefined,
+ ),
),
);
const resolved = [...reviews.reworks.values()].filter((rework) => rework.resolvedAt);
@@ -269,6 +346,7 @@ export const caseReview = async (
stored.evidence[key] as CaseEvidence | undefined,
new Set(layoutComponents),
standInsFor(key, caseEntry, stored.plans ?? []),
+ movedOf(stored, caseEntry, stored.evidence[key] as CaseEvidence | undefined),
),
queued: Boolean(queued),
};
diff --git a/packages/style-equivalence/src/server/reviewMoved.test.ts b/packages/style-equivalence/src/server/reviewMoved.test.ts
new file mode 100644
index 00000000000..6b9ad43ef9a
--- /dev/null
+++ b/packages/style-equivalence/src/server/reviewMoved.test.ts
@@ -0,0 +1,159 @@
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import type { StoredRun } from './api';
+import { caseReview } from './review';
+
+const FILE = 'src/T.tsx';
+
+const element = (id: string, tag: string, slots: string[], parent?: string) => ({
+ bindings: slots.length ? [{ expr: slots[0], prop: 'className', spread: false }] : [],
+ flags: [],
+ id,
+ literalProps: {},
+ owner: 'TableRenderer',
+ ...(parent ? { parent } : {}),
+ slots,
+ tag,
+ variables: [],
+});
+
+const baseTable = `table: css\`
+ border-collapse: collapse;
+
+ th,
+ td {
+ padding-block: 8px;
+ }
+
+ th {
+ font-size: 11px;
+ }
+ \``;
+
+const headTexts = {
+ 'styles.cell': `cell: { paddingBlock: '8px' }`,
+ 'styles.table': `table: { borderCollapse: 'collapse' }`,
+ 'styles.td': `td: { fontSize: '12px' }`,
+ 'styles.th': `th: { fontSize: '11px' }`,
+};
+
+let records: string;
+let stored: StoredRun;
+
+beforeAll(async () => {
+ records = await mkdtemp(path.join(tmpdir(), 'style-eq-moved-'));
+ stored = {
+ calibration: [],
+ evidence: {
+ [`${FILE}|T#1`]: {
+ declarations: {
+ base: { 'styles.table': baseTable },
+ head: { 'styles.table': headTexts['styles.table'] },
+ },
+ },
+ [`${FILE}|T#2`]: {
+ declarations: {
+ head: { 'styles.cell': headTexts['styles.cell'], 'styles.td': headTexts['styles.td'] },
+ },
+ },
+ [`${FILE}|unpaired:head:T#3`]: {
+ counterpart: { base: '<th>' },
+ declarations: {
+ head: { 'styles.cell': headTexts['styles.cell'], 'styles.th': headTexts['styles.th'] },
+ },
+ },
+ },
+ extractions: {
+ [FILE]: {
+ base: { elements: [element('T#1', 'table', ['styles.table'])] },
+ head: {
+ elements: [
+ element('T#1', 'table', ['styles.table']),
+ element('T#2', 'td', ['styles.cell', 'styles.td'], 'T#1'),
+ element('T#3', 'th', ['styles.cell', 'styles.th'], 'T#1'),
+ ],
+ },
+ },
+ },
+ items: [
+ {
+ category: 'unpaired',
+ file: FILE,
+ flags: ['UNPAIRED'],
+ hash: 'h3',
+ key: `${FILE}|unpaired:head:T#3`,
+ },
+ {
+ category: 'needs-signoff',
+ file: FILE,
+ flags: ['INNER_TARGET'],
+ hash: 'h1',
+ key: `${FILE}|T#1`,
+ },
+ ],
+ mutation: { passed: true },
+ plans: [],
+ recordsDir: records,
+ results: {
+ cases: [
+ {
+ category: 'needs-signoff',
+ key: `${FILE}|T#1`,
+ plan: {
+ combos: [{}],
+ elementIds: { base: 'T#1', head: 'T#1' },
+ file: FILE,
+ flags: ['INNER_TARGET'],
+ key: `${FILE}|T#1`,
+ variables: [],
+ },
+ result: { comboDifferences: [], differingConditions: [], errors: [], rootCauses: [] },
+ },
+ ],
+ },
+ run: { base: 'a'.repeat(40), head: 'b'.repeat(40), runId: 'run-moved' },
+ } as unknown as StoredRun;
+});
+
+afterAll(() => rm(records, { force: true, recursive: true }));
+
+describe('caseReview with rules moved onto child elements', () => {
+ it('lines up a base descendant rule with the child slot that now carries it', async () => {
+ const { item } = await caseReview(stored, `${FILE}|T#1`);
+ const [block] = item.styles.blocks;
+
+ expect(block.rows.find((row) => row.label === 'th, td padding')).toMatchObject({
+ after: ['padding-block: 8px'],
+ movedTo: ['<td> <th> · styles.cell'],
+ oneSided: false,
+ });
+ expect(block.rows.find((row) => row.label === 'th font-size')?.after).toEqual([
+ 'font-size: 11px',
+ ]);
+ });
+
+ it('lists the child slots under the base slot for the source view', async () => {
+ const { item } = await caseReview(stored, `${FILE}|T#1`);
+
+ expect(item.styles.moved['styles.table']).toEqual([
+ {
+ selectors: ['th, td'],
+ slot: 'styles.cell',
+ tags: ['td', 'th'],
+ text: headTexts['styles.cell'],
+ },
+ { selectors: ['th'], slot: 'styles.th', tags: ['th'], text: headTexts['styles.th'] },
+ ]);
+ });
+
+ it('shows the unstyled same-position element on the side that has no class', async () => {
+ const { item } = await caseReview(stored, `${FILE}|unpaired:head:T#3`);
+
+ expect(item.styles.usage.base).toEqual(['<th>']);
+ expect(item.styles.counterpart).toBe('base');
+ });
+});
diff --git a/packages/style-equivalence/src/server/standIns.test.ts b/packages/style-equivalence/src/server/standIns.test.ts
index ff458c7c062..a4a0794bdcf 100644
--- a/packages/style-equivalence/src/server/standIns.test.ts
+++ b/packages/style-equivalence/src/server/standIns.test.ts
@@ -16,4 +16,24 @@ describe('stand-ins shown on a review screenshot', () => {
expect(standInsFor('a.tsx|unpaired:head:A#1', undefined, plans)).toEqual({ head: ['Select'] });
expect(standInsFor('a.tsx|unpaired:base:A#1', undefined, plans)).toEqual({});
});
+
+ it('marks the rendered counterpart of a one-sided element as the same stand-in', () => {
+ const plans = [
+ {
+ file: 'a.tsx',
+ standIns: { 'head:A#1': ['Icon'] },
+ unpaired: [
+ {
+ counterpart: { ancestors: [], literalProps: {}, tag: 'Icon', variables: [] },
+ elementId: 'A#1',
+ side: 'head' as const,
+ },
+ ],
+ },
+ ];
+ expect(standInsFor('a.tsx|unpaired:head:A#1', undefined, plans)).toEqual({
+ base: ['Icon'],
+ head: ['Icon'],
+ });
+ });
});
diff --git a/packages/style-equivalence/src/signoff/hash.ts b/packages/style-equivalence/src/signoff/hash.ts
index c55e906dd28..1b65e9da4de 100644
--- a/packages/style-equivalence/src/signoff/hash.ts
+++ b/packages/style-equivalence/src/signoff/hash.ts
@@ -16,6 +16,7 @@ export interface HashedElement {
}
export interface CaseHashInput {
+ counterpart?: Partial<Record<Side, string>>;
declarations: Partial<Record<Side, Record<string, string>>>;
elements: Partial<Record<Side, HashedElement[]>>;
outcome?: string[];
diff --git a/packages/style-equivalence/src/source/counterpart.test.ts b/packages/style-equivalence/src/source/counterpart.test.ts
new file mode 100644
index 00000000000..9e4cd2f9267
--- /dev/null
+++ b/packages/style-equivalence/src/source/counterpart.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import { counterpartLeafOf, counterpartOf } from './counterpart';
+
+const base = `export const EvidenceItem = ({ flat }) => (
+ <Flexbox>
+ <Image
+ preview
+ variant={flat ? 'borderless' : 'outlined'}
+ style={flat ? { borderRadius: 0 } : { maxWidth: '100%' }}
+ />
+ <video controls className={styles.evidenceVideo} />
+ </Flexbox>
+);
+const Other = () => <Image src="x" />;
+`;
+
+const head = `export const EvidenceItem = ({ flat }) => (
+ <Flexbox>
+ <Image
+ preview
+ style={{ maxWidth: '100%' }}
+ {...(flat ? comparisonMedia.image : { variant: 'outlined' as const })}
+ />
+ <video controls {...videoProps} />
+ </Flexbox>
+);
+`;
+
+describe('counterpartOf', () => {
+ it('finds the same-position element on the other side when it has no style class', () => {
+ expect(
+ counterpartOf({
+ expr: "(flat ? comparisonMedia.image : { variant: 'outlined' as const })",
+ from: head,
+ owner: 'EvidenceItem',
+ tag: 'Image',
+ to: base,
+ }),
+ ).toBe(`<Image
+ preview
+ variant={flat ? 'borderless' : 'outlined'}
+ style={flat ? { borderRadius: 0 } : { maxWidth: '100%' }}
+/>`);
+ });
+
+ it('stays inside the owner component', () => {
+ expect(
+ counterpartOf({ expr: 'styles.x', from: head, owner: 'Other', tag: 'Image', to: base }),
+ ).toBe('<Image src="x" />');
+ });
+
+ it('gives up when the other side has no element with that tag in the owner', () => {
+ expect(
+ counterpartOf({
+ expr: 'styles.x',
+ from: head,
+ owner: 'EvidenceItem',
+ tag: 'audio',
+ to: base,
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('counterpartLeafOf', () => {
+ it('describes the other-side element so it can be rendered next to the unpaired one', () => {
+ expect(
+ counterpartLeafOf({
+ expr: "(flat ? comparisonMedia.image : { variant: 'outlined' as const })",
+ from: head,
+ owner: 'EvidenceItem',
+ tag: 'Image',
+ to: base,
+ }),
+ ).toEqual({
+ inlineStyle: "flat ? { borderRadius: 0 } : { maxWidth: '100%' }",
+ literalProps: { preview: true },
+ props: "{ \"variant\": (flat ? 'borderless' : 'outlined') }",
+ tag: 'Image',
+ variables: [{ kind: 'boolean', name: 'flat' }],
+ });
+ });
+
+ it('marks a configured real component imported from its source', () => {
+ const code = `import { Text } from '@lobehub/ui';
+export const Row = ({ label }) => <Text as="span" title={label.name}>x</Text>;
+`;
+ expect(
+ counterpartLeafOf({
+ expr: 'styles.x',
+ from: code,
+ owner: 'Row',
+ real: { Text: { source: '@lobehub/ui' } },
+ tag: 'Text',
+ to: code,
+ }),
+ ).toEqual({
+ literalProps: { as: 'span' },
+ props: '{ "title": (label.name) }',
+ real: true,
+ tag: 'Text',
+ variables: [{ kind: 'unknown', name: 'label' }],
+ });
+ });
+});
diff --git a/packages/style-equivalence/src/source/counterpart.ts b/packages/style-equivalence/src/source/counterpart.ts
new file mode 100644
index 00000000000..8580648bde2
--- /dev/null
+++ b/packages/style-equivalence/src/source/counterpart.ts
@@ -0,0 +1,159 @@
+import ts from 'typescript';
+
+import {
+ GLOBALS,
+ type LiteralValue,
+ type RealComponent,
+ type VariableKind,
+ type VariableUse,
+} from '../extract';
+import { literalOf } from '../extract/children';
+import { mergeKinds, usageKinds, valueIdentifierNodes } from '../extract/identifiers';
+import { parseSource } from './declarations';
+
+type Opening = ts.JsxOpeningElement | ts.JsxSelfClosingElement;
+
+const dedent = (text: string) => {
+ const [first, ...rest] = text.split('\n');
+ const indents = rest
+ .filter((line) => line.trim())
+ .map((line) => line.length - line.trimStart().length);
+ const common = indents.length ? Math.min(...indents) : 0;
+ return [first, ...rest.map((line) => line.slice(common))].join('\n');
+};
+
+const ownerNode = (sf: ts.SourceFile, owner: string) =>
+ sf.statements.find((statement) => {
+ if (ts.isFunctionDeclaration(statement)) return statement.name?.text === owner;
+ if (ts.isClassDeclaration(statement)) return statement.name?.text === owner;
+ return (
+ ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(
+ (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === owner,
+ )
+ );
+ });
+
+const openingsOf = (code: string, owner: string, tag: string) => {
+ const sf = parseSource(code);
+ const root = ownerNode(sf, owner);
+ const found: Opening[] = [];
+ const visit = (node: ts.Node) => {
+ if (
+ (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
+ node.tagName.getText(sf) === tag
+ )
+ found.push(node);
+ ts.forEachChild(node, visit);
+ };
+ if (root) visit(root);
+ return {
+ openings: found.map((node) => ({
+ attributes: node.attributes.getText(sf).replaceAll(/\s+/g, ''),
+ node,
+ text: dedent(node.getText(sf)),
+ })),
+ sf,
+ };
+};
+
+export interface CounterpartInput {
+ expr: string;
+ from: string;
+ owner: string;
+ tag: string;
+ to: string;
+}
+
+const counterpartOpening = ({ expr, from, owner, tag, to }: CounterpartInput) => {
+ const { openings: others, sf } = openingsOf(to, owner, tag);
+ if (!others.length) return undefined;
+ const needle = expr.replaceAll(/\s+/g, '');
+ const mine = openingsOf(from, owner, tag).openings;
+ const index = mine.findIndex((opening) => opening.attributes.includes(needle));
+ if (index !== -1 && mine.length === others.length) return { ...others[index], sf };
+ return others.length === 1 ? { ...others[0], sf } : undefined;
+};
+
+export const counterpartOf = (input: CounterpartInput) => counterpartOpening(input)?.text;
+
+export interface CounterpartLeaf {
+ inlineStyle?: string;
+ literalProps: Record<string, LiteralValue>;
+ props?: string;
+ real?: true;
+ tag: string;
+ variables: VariableUse[];
+}
+
+const importedFrom = (sf: ts.SourceFile, tag: string, source: string) =>
+ sf.statements.some(
+ (statement) =>
+ ts.isImportDeclaration(statement) &&
+ ts.isStringLiteral(statement.moduleSpecifier) &&
+ statement.moduleSpecifier.text === source &&
+ !!statement.importClause?.namedBindings &&
+ ts.isNamedImports(statement.importClause.namedBindings) &&
+ statement.importClause.namedBindings.elements.some(
+ (element) =>
+ element.name.text === tag && (element.propertyName ?? element.name).text === tag,
+ ),
+ );
+
+export const counterpartLeafOf = (
+ input: CounterpartInput & { real?: Record<string, RealComponent> },
+): CounterpartLeaf | undefined => {
+ const opening = counterpartOpening(input);
+ if (!opening) return undefined;
+ const { node, sf } = opening;
+ const literalProps: Record<string, LiteralValue> = {};
+ const props: string[] = [];
+ const expressions: ts.Expression[] = [];
+ let inlineStyle: string | undefined;
+ for (const attribute of node.attributes.properties) {
+ if (ts.isJsxSpreadAttribute(attribute)) continue;
+ const name = attribute.name.getText(sf);
+ const initializer = attribute.initializer;
+ if (!initializer) {
+ literalProps[name] = true;
+ continue;
+ }
+ if (ts.isStringLiteral(initializer)) {
+ literalProps[name] = initializer.text;
+ continue;
+ }
+ if (!ts.isJsxExpression(initializer) || !initializer.expression) continue;
+ const expression = initializer.expression;
+ const literal = literalOf(expression);
+ if (literal !== undefined) {
+ literalProps[name] = literal;
+ continue;
+ }
+ expressions.push(expression);
+ const text = expression.getText(sf).replaceAll(/\s+/g, ' ');
+ if (name === 'style') inlineStyle = text;
+ else props.push(`${JSON.stringify(name)}: (${text})`);
+ }
+ const names = new Set(
+ expressions
+ .flatMap((expression) => valueIdentifierNodes(expression, { skipJsx: true }))
+ .map((identifier) => identifier.text)
+ .filter((name) => !GLOBALS.has(name)),
+ );
+ const kinds = new Map<string, VariableKind[]>();
+ for (const expression of expressions)
+ for (const [name, list] of usageKinds(expression, names))
+ kinds.set(name, [...(kinds.get(name) ?? []), ...list]);
+ const component = input.real?.[input.tag];
+ return {
+ ...(inlineStyle ? { inlineStyle } : {}),
+ literalProps,
+ ...(props.length ? { props: `{ ${props.join(', ')} }` } : {}),
+ ...(component && importedFrom(sf, input.tag, component.source) ? { real: true as const } : {}),
+ tag: input.tag,
+ variables: [...names].sort().map((name) => ({
+ kind: mergeKinds(kinds.get(name) ?? ['unknown']),
+ name,
+ })),
+ };
+};
diff --git a/packages/style-equivalence/src/verdict/assemble.test.ts b/packages/style-equivalence/src/verdict/assemble.test.ts
new file mode 100644
index 00000000000..bc32d1a8720
--- /dev/null
+++ b/packages/style-equivalence/src/verdict/assemble.test.ts
@@ -0,0 +1,90 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+
+import type { FileExtraction } from '../extract';
+import { type AssembleInput, assembleVerdict } from './assemble';
+
+const FILE = 'src/Item.tsx';
+
+const baseCode = `export const Item = ({ flat }) => (
+ <Image variant={flat ? 'borderless' : 'outlined'} style={{ maxWidth: '100%' }} />
+);
+`;
+
+const headCode = `import * as stylex from '@stylexjs/stylex';
+const styles = stylex.create({ image: { width: '100%' } });
+export const Item = ({ flat }) => (
+ <Image style={{ maxWidth: '100%' }} {...stylex.props(flat && styles.image)} />
+);
+`;
+
+const extraction = (elements: FileExtraction['elements']) =>
+ ({ elements, outsideReferences: [] }) as unknown as FileExtraction;
+
+let dir: string;
+let input: AssembleInput;
+
+beforeAll(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'style-eq-assemble-'));
+ for (const [side, code] of [
+ ['base', baseCode],
+ ['head', headCode],
+ ] as const) {
+ await mkdir(path.join(dir, side, 'src'), { recursive: true });
+ await writeFile(path.join(dir, side, FILE), code);
+ }
+ input = {
+ aliases: {},
+ calibration: [],
+ cases: [],
+ extractions: {
+ [FILE]: {
+ base: extraction([]),
+ head: extraction([
+ {
+ bindings: [{ expr: 'stylex.props(flat && styles.image)', prop: '...', spread: true }],
+ flags: [],
+ id: 'Item#0',
+ literalProps: {},
+ owner: 'Item',
+ slots: ['styles.image'],
+ tag: 'Image',
+ variables: [],
+ },
+ ]),
+ },
+ },
+ mutation: { passed: true },
+ plans: [{ cases: [], file: FILE, gaps: [], unpaired: [{ elementId: 'Item#0', side: 'head' }] }],
+ recordsDir: path.join(dir, 'records'),
+ roots: { base: path.join(dir, 'base'), head: path.join(dir, 'head') },
+ scope: [{ base: FILE, head: FILE, reason: 'changed' }],
+ unparsedSelectors: [],
+ verifierVersion: '2.15.0',
+ } as unknown as AssembleInput;
+});
+
+afterAll(() => rm(dir, { force: true, recursive: true }));
+
+describe('assembleVerdict for an unpaired element', () => {
+ it('records the unstyled same-position element of the other side', async () => {
+ const { evidence } = await assembleVerdict(input);
+
+ expect(evidence[`${FILE}|unpaired:head:Item#0`].counterpart).toEqual({
+ base: "<Image variant={flat ? 'borderless' : 'outlined'} style={{ maxWidth: '100%' }} />",
+ });
+ });
+
+ it('keeps the counterpart out of the sign-off hash', async () => {
+ const { verdict } = await assembleVerdict(input);
+ const { verdict: without } = await assembleVerdict({
+ ...input,
+ roots: { ...input.roots, base: path.join(dir, 'missing') },
+ });
+
+ expect(verdict.items[0].hash).toBe(without.items[0].hash);
+ });
+});
diff --git a/packages/style-equivalence/src/verdict/assemble.ts b/packages/style-equivalence/src/verdict/assemble.ts
index 4ab0580293a..e666f090caf 100644
--- a/packages/style-equivalence/src/verdict/assemble.ts
+++ b/packages/style-equivalence/src/verdict/assemble.ts
@@ -1,5 +1,9 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
import type { CaseResult } from '../analyze/diff';
import type { FileExtraction } from '../extract';
+import { elementsOf } from '../plan/descendants';
import type { FilePlan, PlanCase, Side } from '../plan/planFile';
import { readReviews, reviewScope } from '../review/store';
import {
@@ -8,6 +12,7 @@ import {
collectFileHashInput,
contentHash,
} from '../signoff/hash';
+import { counterpartOf } from '../source/counterpart';
import type { ScopeFile } from '../source/scope';
import type { CaseCategory } from './categorize';
import { fileFlags, fileItemKey } from './fileItems';
@@ -80,6 +85,28 @@ export const assembleVerdict = async (input: AssembleInput) => {
})),
),
];
+ const readSide = (side: Side, file: string | undefined) => {
+ const absolute = file && path.join(input.roots[side], file);
+ return absolute && existsSync(absolute) ? readFileSync(absolute, 'utf8') : undefined;
+ };
+ for (const plan of input.plans)
+ for (const { elementId, side } of plan.unpaired) {
+ const extraction = input.extractions[plan.file]?.[side];
+ const element = extraction && elementsOf(extraction).find((item) => item.id === elementId);
+ const other: Side = side === 'base' ? 'head' : 'base';
+ const sources = sourcesOf(plan.file);
+ const from = readSide(side, sources[side]);
+ const to = readSide(other, sources[other]);
+ if (!element || !from || !to) continue;
+ const text = counterpartOf({
+ expr: element.bindings[0]?.expr ?? '',
+ from,
+ owner: element.owner,
+ tag: element.tag,
+ to,
+ });
+ if (text) evidence[unpairedKey(plan.file, side, elementId)].counterpart = { [other]: text };
+ }
for (const plan of input.plans) {
const flags = fileFlags(plan, input.extractions[plan.file] ?? {});
if (!flags.length) continue;